From 2740976d8b1a98c87431afdb5b98836b384a4f79 Mon Sep 17 00:00:00 2001 From: Richard Moore Date: Mon, 5 Sep 2022 16:57:11 -0400 Subject: [PATCH] admin: updated dist files. --- dist/ethers.js | 17096 ++++++++++++++++ dist/ethers.min.js | 1 + dist/wordlists-extra.js | 1344 ++ dist/wordlists-extra.min.js | 1 + lib.commonjs/_tests/test-abi.js | 46 + lib.commonjs/_tests/test-abi.js.map | 1 + lib.commonjs/_tests/test-address.js | 115 + lib.commonjs/_tests/test-address.js.map | 1 + lib.commonjs/_tests/test-contract.js | 99 + lib.commonjs/_tests/test-contract.js.map | 1 + lib.commonjs/_tests/test-crypto-algoswap.js | 87 + .../_tests/test-crypto-algoswap.js.map | 1 + lib.commonjs/_tests/test-crypto.js | 219 + lib.commonjs/_tests/test-crypto.js.map | 1 + lib.commonjs/_tests/test-hash-typeddata.js | 21 + .../_tests/test-hash-typeddata.js.map | 1 + lib.commonjs/_tests/test-hash.js | 112 + lib.commonjs/_tests/test-hash.js.map | 1 + lib.commonjs/_tests/test-rlp.js | 93 + lib.commonjs/_tests/test-rlp.js.map | 1 + lib.commonjs/_tests/test-transaction.js | 263 + lib.commonjs/_tests/test-transaction.js.map | 1 + lib.commonjs/_tests/test-wallet-hd.js | 125 + lib.commonjs/_tests/test-wallet-hd.js.map | 1 + lib.commonjs/_tests/test-wallet-json.js | 64 + lib.commonjs/_tests/test-wallet-json.js.map | 1 + lib.commonjs/_tests/test-wallet-mnemonic.js | 126 + .../_tests/test-wallet-mnemonic.js.map | 1 + lib.commonjs/_tests/test-wallet.js | 77 + lib.commonjs/_tests/test-wallet.js.map | 1 + lib.commonjs/_tests/test-wordlists.js | 71 + lib.commonjs/_tests/test-wordlists.js.map | 1 + lib.commonjs/_tests/types.js | 4 + lib.commonjs/_tests/types.js.map | 1 + lib.commonjs/_tests/utils.js | 40 + lib.commonjs/_tests/utils.js.map | 1 + lib.commonjs/_version.js | 5 + lib.commonjs/_version.js.map | 1 + lib.commonjs/abi/abi-coder.js | 80 + lib.commonjs/abi/abi-coder.js.map | 1 + lib.commonjs/abi/bytes32.js | 36 + lib.commonjs/abi/bytes32.js.map | 1 + lib.commonjs/abi/coders/abstract-coder.js | 273 + lib.commonjs/abi/coders/abstract-coder.js.map | 1 + lib.commonjs/abi/coders/address.js | 30 + lib.commonjs/abi/coders/address.js.map | 1 + lib.commonjs/abi/coders/anonymous.js | 23 + lib.commonjs/abi/coders/anonymous.js.map | 1 + lib.commonjs/abi/coders/array.js | 178 + lib.commonjs/abi/coders/array.js.map | 1 + lib.commonjs/abi/coders/boolean.js | 22 + lib.commonjs/abi/coders/boolean.js.map | 1 + lib.commonjs/abi/coders/bytes.js | 34 + lib.commonjs/abi/coders/bytes.js.map | 1 + lib.commonjs/abi/coders/fixed-bytes.js | 31 + lib.commonjs/abi/coders/fixed-bytes.js.map | 1 + lib.commonjs/abi/coders/null.js | 25 + lib.commonjs/abi/coders/null.js.map | 1 + lib.commonjs/abi/coders/number.js | 51 + lib.commonjs/abi/coders/number.js.map | 1 + lib.commonjs/abi/coders/string.js | 22 + lib.commonjs/abi/coders/string.js.map | 1 + lib.commonjs/abi/coders/tuple.js | 64 + lib.commonjs/abi/coders/tuple.js.map | 1 + lib.commonjs/abi/fragments.js | 933 + lib.commonjs/abi/fragments.js.map | 1 + lib.commonjs/abi/index.js | 26 + lib.commonjs/abi/index.js.map | 1 + lib.commonjs/abi/interface.js | 817 + lib.commonjs/abi/interface.js.map | 1 + lib.commonjs/abi/typed.js | 216 + lib.commonjs/abi/typed.js.map | 1 + lib.commonjs/address/address.js | 114 + lib.commonjs/address/address.js.map | 1 + lib.commonjs/address/checks.js | 52 + lib.commonjs/address/checks.js.map | 1 + lib.commonjs/address/contract-address.js | 37 + lib.commonjs/address/contract-address.js.map | 1 + lib.commonjs/address/index.js | 14 + lib.commonjs/address/index.js.map | 1 + lib.commonjs/constants/addresses.js | 8 + lib.commonjs/constants/addresses.js.map | 1 + lib.commonjs/constants/hashes.js | 8 + lib.commonjs/constants/hashes.js.map | 1 + lib.commonjs/constants/index.js | 21 + lib.commonjs/constants/index.js.map | 1 + lib.commonjs/constants/numbers.js | 49 + lib.commonjs/constants/numbers.js.map | 1 + lib.commonjs/constants/strings.js | 10 + lib.commonjs/constants/strings.js.map | 1 + lib.commonjs/contract/contract.js | 649 + lib.commonjs/contract/contract.js.map | 1 + lib.commonjs/contract/factory.js | 79 + lib.commonjs/contract/factory.js.map | 1 + lib.commonjs/contract/index.js | 14 + lib.commonjs/contract/index.js.map | 1 + lib.commonjs/contract/types.js | 6 + lib.commonjs/contract/types.js.map | 1 + lib.commonjs/contract/wrappers.js | 80 + lib.commonjs/contract/wrappers.js.map | 1 + lib.commonjs/crypto/crypto-browser.js | 63 + lib.commonjs/crypto/crypto-browser.js.map | 1 + lib.commonjs/crypto/crypto.js | 9 + lib.commonjs/crypto/crypto.js.map | 1 + lib.commonjs/crypto/hmac.js | 26 + lib.commonjs/crypto/hmac.js.map | 1 + lib.commonjs/crypto/index.js | 37 + lib.commonjs/crypto/index.js.map | 1 + lib.commonjs/crypto/keccak.js | 25 + lib.commonjs/crypto/keccak.js.map | 1 + lib.commonjs/crypto/pbkdf2.js | 26 + lib.commonjs/crypto/pbkdf2.js.map | 1 + lib.commonjs/crypto/random.js | 23 + lib.commonjs/crypto/random.js.map | 1 + lib.commonjs/crypto/ripemd160.js | 25 + lib.commonjs/crypto/ripemd160.js.map | 1 + lib.commonjs/crypto/scrypt.js | 45 + lib.commonjs/crypto/scrypt.js.map | 1 + lib.commonjs/crypto/sha2.js | 43 + lib.commonjs/crypto/sha2.js.map | 1 + lib.commonjs/crypto/signature.js | 233 + lib.commonjs/crypto/signature.js.map | 1 + lib.commonjs/crypto/signing-key.js | 133 + lib.commonjs/crypto/signing-key.js.map | 1 + lib.commonjs/ethers.js | 148 + lib.commonjs/ethers.js.map | 1 + lib.commonjs/hash/id.js | 10 + lib.commonjs/hash/id.js.map | 1 + lib.commonjs/hash/index.js | 18 + lib.commonjs/hash/index.js.map | 1 + lib.commonjs/hash/message.js | 18 + lib.commonjs/hash/message.js.map | 1 + lib.commonjs/hash/namehash.js | 79 + lib.commonjs/hash/namehash.js.map | 1 + lib.commonjs/hash/solidity.js | 111 + lib.commonjs/hash/solidity.js.map | 1 + lib.commonjs/hash/typed-data.js | 433 + lib.commonjs/hash/typed-data.js.map | 1 + lib.commonjs/index.js | 33 + lib.commonjs/index.js.map | 1 + lib.commonjs/package.json | 3 + lib.commonjs/providers/abstract-provider.js | 1094 + .../providers/abstract-provider.js.map | 1 + lib.commonjs/providers/abstract-signer.js | 149 + lib.commonjs/providers/abstract-signer.js.map | 1 + lib.commonjs/providers/common-networks.js | 81 + lib.commonjs/providers/common-networks.js.map | 1 + lib.commonjs/providers/community.js | 25 + lib.commonjs/providers/community.js.map | 1 + lib.commonjs/providers/contracts.js | 3 + lib.commonjs/providers/contracts.js.map | 1 + lib.commonjs/providers/default-provider.js | 98 + .../providers/default-provider.js.map | 1 + lib.commonjs/providers/ens-resolver.js | 471 + lib.commonjs/providers/ens-resolver.js.map | 1 + lib.commonjs/providers/formatter.js | 389 + lib.commonjs/providers/formatter.js.map | 1 + lib.commonjs/providers/index.js | 61 + lib.commonjs/providers/index.js.map | 1 + lib.commonjs/providers/network.js | 191 + lib.commonjs/providers/network.js.map | 1 + lib.commonjs/providers/pagination.js | 3 + lib.commonjs/providers/pagination.js.map | 1 + lib.commonjs/providers/plugins-network.js | 112 + lib.commonjs/providers/plugins-network.js.map | 1 + lib.commonjs/providers/provider-alchemy.js | 101 + .../providers/provider-alchemy.js.map | 1 + lib.commonjs/providers/provider-ankr.js | 67 + lib.commonjs/providers/provider-ankr.js.map | 1 + lib.commonjs/providers/provider-cloudflare.js | 17 + .../providers/provider-cloudflare.js.map | 1 + lib.commonjs/providers/provider-etherscan.js | 468 + .../providers/provider-etherscan.js.map | 1 + lib.commonjs/providers/provider-fallback.js | 417 + .../providers/provider-fallback.js.map | 1 + lib.commonjs/providers/provider-infura.js | 85 + lib.commonjs/providers/provider-infura.js.map | 1 + .../providers/provider-ipcsocket-browser.js | 6 + .../provider-ipcsocket-browser.js.map | 1 + lib.commonjs/providers/provider-ipcsocket.js | 90 + .../providers/provider-ipcsocket.js.map | 1 + lib.commonjs/providers/provider-jsonrpc.js | 693 + .../providers/provider-jsonrpc.js.map | 1 + lib.commonjs/providers/provider-pocket.js | 101 + lib.commonjs/providers/provider-pocket.js.map | 1 + lib.commonjs/providers/provider-socket.js | 225 + lib.commonjs/providers/provider-socket.js.map | 1 + lib.commonjs/providers/provider-websocket.js | 30 + .../providers/provider-websocket.js.map | 1 + lib.commonjs/providers/provider.js | 560 + lib.commonjs/providers/provider.js.map | 1 + lib.commonjs/providers/signer.js | 3 + lib.commonjs/providers/signer.js.map | 1 + .../providers/subscriber-connection.js | 41 + .../providers/subscriber-connection.js.map | 1 + lib.commonjs/providers/subscriber-filterid.js | 111 + .../providers/subscriber-filterid.js.map | 1 + lib.commonjs/providers/subscriber-hotswap.js | 43 + .../providers/subscriber-hotswap.js.map | 1 + lib.commonjs/providers/subscriber-polling.js | 183 + .../providers/subscriber-polling.js.map | 1 + lib.commonjs/providers/subscriber.js | 57 + lib.commonjs/providers/subscriber.js.map | 1 + lib.commonjs/providers/ws-browser.js | 19 + lib.commonjs/providers/ws-browser.js.map | 1 + lib.commonjs/providers/ws.js | 6 + lib.commonjs/providers/ws.js.map | 1 + lib.commonjs/transaction/accesslist.js | 42 + lib.commonjs/transaction/accesslist.js.map | 1 + lib.commonjs/transaction/address.js | 15 + lib.commonjs/transaction/address.js.map | 1 + lib.commonjs/transaction/index.js | 11 + lib.commonjs/transaction/index.js.map | 1 + lib.commonjs/transaction/transaction.js | 579 + lib.commonjs/transaction/transaction.js.map | 1 + lib.commonjs/utils/base58.js | 48 + lib.commonjs/utils/base58.js.map | 1 + lib.commonjs/utils/base64-browser.js | 24 + lib.commonjs/utils/base64-browser.js.map | 1 + lib.commonjs/utils/base64.js | 14 + lib.commonjs/utils/base64.js.map | 1 + lib.commonjs/utils/data.js | 89 + lib.commonjs/utils/data.js.map | 1 + lib.commonjs/utils/errors.js | 23 + lib.commonjs/utils/errors.js.map | 1 + lib.commonjs/utils/events.js | 21 + lib.commonjs/utils/events.js.map | 1 + lib.commonjs/utils/fetch.js | 569 + lib.commonjs/utils/fetch.js.map | 1 + lib.commonjs/utils/fixednumber.js | 347 + lib.commonjs/utils/fixednumber.js.map | 1 + lib.commonjs/utils/geturl-browser.js | 45 + lib.commonjs/utils/geturl-browser.js.map | 1 + lib.commonjs/utils/geturl.js | 85 + lib.commonjs/utils/geturl.js.map | 1 + lib.commonjs/utils/index.js | 69 + lib.commonjs/utils/index.js.map | 1 + lib.commonjs/utils/logger.js | 231 + lib.commonjs/utils/logger.js.map | 1 + lib.commonjs/utils/maths.js | 133 + lib.commonjs/utils/maths.js.map | 1 + lib.commonjs/utils/properties.js | 112 + lib.commonjs/utils/properties.js.map | 1 + lib.commonjs/utils/rlp-decode.js | 87 + lib.commonjs/utils/rlp-decode.js.map | 1 + lib.commonjs/utils/rlp-encode.js | 50 + lib.commonjs/utils/rlp-encode.js.map | 1 + lib.commonjs/utils/rlp.js | 8 + lib.commonjs/utils/rlp.js.map | 1 + lib.commonjs/utils/storage.js | 15 + lib.commonjs/utils/storage.js.map | 1 + lib.commonjs/utils/units.js | 66 + lib.commonjs/utils/units.js.map | 1 + lib.commonjs/utils/utf8.js | 214 + lib.commonjs/utils/utf8.js.map | 1 + lib.commonjs/wallet/base-wallet.js | 66 + lib.commonjs/wallet/base-wallet.js.map | 1 + lib.commonjs/wallet/hdwallet.js | 291 + lib.commonjs/wallet/hdwallet.js.map | 1 + lib.commonjs/wallet/index.js | 22 + lib.commonjs/wallet/index.js.map | 1 + lib.commonjs/wallet/json-crowdsale.js | 46 + lib.commonjs/wallet/json-crowdsale.js.map | 1 + lib.commonjs/wallet/json-keystore.js | 286 + lib.commonjs/wallet/json-keystore.js.map | 1 + lib.commonjs/wallet/mnemonic.js | 128 + lib.commonjs/wallet/mnemonic.js.map | 1 + lib.commonjs/wallet/utils.js | 145 + lib.commonjs/wallet/utils.js.map | 1 + lib.commonjs/wallet/wallet.js | 169 + lib.commonjs/wallet/wallet.js.map | 1 + lib.commonjs/wordlists/bit-reader.js | 33 + lib.commonjs/wordlists/bit-reader.js.map | 1 + lib.commonjs/wordlists/decode-owl.js | 54 + lib.commonjs/wordlists/decode-owl.js.map | 1 + lib.commonjs/wordlists/decode-owla.js | 29 + lib.commonjs/wordlists/decode-owla.js.map | 1 + .../wordlists/generation/encode-latin.js | 353 + .../wordlists/generation/encode-latin.js.map | 1 + lib.commonjs/wordlists/index.js | 15 + lib.commonjs/wordlists/index.js.map | 1 + lib.commonjs/wordlists/lang-cz.js | 12 + lib.commonjs/wordlists/lang-cz.js.map | 1 + lib.commonjs/wordlists/lang-en.js | 12 + lib.commonjs/wordlists/lang-en.js.map | 1 + lib.commonjs/wordlists/lang-es.js | 13 + lib.commonjs/wordlists/lang-es.js.map | 1 + lib.commonjs/wordlists/lang-fr.js | 13 + lib.commonjs/wordlists/lang-fr.js.map | 1 + lib.commonjs/wordlists/lang-it.js | 12 + lib.commonjs/wordlists/lang-it.js.map | 1 + lib.commonjs/wordlists/lang-ja.js | 136 + lib.commonjs/wordlists/lang-ja.js.map | 1 + lib.commonjs/wordlists/lang-ko.js | 71 + lib.commonjs/wordlists/lang-ko.js.map | 1 + lib.commonjs/wordlists/lang-pt.js | 12 + lib.commonjs/wordlists/lang-pt.js.map | 1 + lib.commonjs/wordlists/lang-zh.js | 69 + lib.commonjs/wordlists/lang-zh.js.map | 1 + lib.commonjs/wordlists/wordlist-owl.js | 50 + lib.commonjs/wordlists/wordlist-owl.js.map | 1 + lib.commonjs/wordlists/wordlist-owla.js | 18 + lib.commonjs/wordlists/wordlist-owla.js.map | 1 + lib.commonjs/wordlists/wordlist.js | 20 + lib.commonjs/wordlists/wordlist.js.map | 1 + lib.commonjs/wordlists/wordlists-browser.js | 9 + .../wordlists/wordlists-browser.js.map | 1 + lib.commonjs/wordlists/wordlists-extra.js | 15 + lib.commonjs/wordlists/wordlists-extra.js.map | 1 + lib.commonjs/wordlists/wordlists.js | 16 + lib.commonjs/wordlists/wordlists.js.map | 1 + lib.esm/_admin/update-version-const.js | 7 + lib.esm/_admin/update-version-const.js.map | 1 + lib.esm/_admin/utils/fs.js | 8 + lib.esm/_admin/utils/fs.js.map | 1 + lib.esm/_admin/utils/json.js | 26 + lib.esm/_admin/utils/json.js.map | 1 + lib.esm/_admin/utils/path.js | 12 + lib.esm/_admin/utils/path.js.map | 1 + lib.esm/_tests/test-abi.js | 41 + lib.esm/_tests/test-abi.js.map | 1 + lib.esm/_tests/test-address.js | 110 + lib.esm/_tests/test-address.js.map | 1 + lib.esm/_tests/test-contract.js | 99 + lib.esm/_tests/test-contract.js.map | 1 + lib.esm/_tests/test-crypto-algoswap.js | 82 + lib.esm/_tests/test-crypto-algoswap.js.map | 1 + lib.esm/_tests/test-crypto.js | 214 + lib.esm/_tests/test-crypto.js.map | 1 + lib.esm/_tests/test-hash-typeddata.js | 16 + lib.esm/_tests/test-hash-typeddata.js.map | 1 + lib.esm/_tests/test-hash.js | 112 + lib.esm/_tests/test-hash.js.map | 1 + lib.esm/_tests/test-rlp.js | 88 + lib.esm/_tests/test-rlp.js.map | 1 + lib.esm/_tests/test-transaction.js | 258 + lib.esm/_tests/test-transaction.js.map | 1 + lib.esm/_tests/test-wallet-hd.js | 120 + lib.esm/_tests/test-wallet-hd.js.map | 1 + lib.esm/_tests/test-wallet-json.js | 59 + lib.esm/_tests/test-wallet-json.js.map | 1 + lib.esm/_tests/test-wallet-mnemonic.js | 121 + lib.esm/_tests/test-wallet-mnemonic.js.map | 1 + lib.esm/_tests/test-wallet.js | 72 + lib.esm/_tests/test-wallet.js.map | 1 + lib.esm/_tests/test-wordlists.js | 66 + lib.esm/_tests/test-wordlists.js.map | 1 + lib.esm/_tests/types.js | 3 + lib.esm/_tests/types.js.map | 1 + lib.esm/_tests/utils.js | 32 + lib.esm/_tests/utils.js.map | 1 + lib.esm/_version.js | 2 + lib.esm/_version.js.map | 1 + lib.esm/abi/abi-coder.js | 76 + lib.esm/abi/abi-coder.js.map | 1 + lib.esm/abi/bytes32.js | 31 + lib.esm/abi/bytes32.js.map | 1 + lib.esm/abi/coders/abstract-coder.js | 265 + lib.esm/abi/coders/abstract-coder.js.map | 1 + lib.esm/abi/coders/address.js | 26 + lib.esm/abi/coders/address.js.map | 1 + lib.esm/abi/coders/anonymous.js | 19 + lib.esm/abi/coders/anonymous.js.map | 1 + lib.esm/abi/coders/array.js | 172 + lib.esm/abi/coders/array.js.map | 1 + lib.esm/abi/coders/boolean.js | 18 + lib.esm/abi/coders/boolean.js.map | 1 + lib.esm/abi/coders/bytes.js | 29 + lib.esm/abi/coders/bytes.js.map | 1 + lib.esm/abi/coders/fixed-bytes.js | 27 + lib.esm/abi/coders/fixed-bytes.js.map | 1 + lib.esm/abi/coders/null.js | 21 + lib.esm/abi/coders/null.js.map | 1 + lib.esm/abi/coders/number.js | 47 + lib.esm/abi/coders/number.js.map | 1 + lib.esm/abi/coders/string.js | 18 + lib.esm/abi/coders/string.js.map | 1 + lib.esm/abi/coders/tuple.js | 60 + lib.esm/abi/coders/tuple.js.map | 1 + lib.esm/abi/fragments.js | 920 + lib.esm/abi/fragments.js.map | 1 + lib.esm/abi/index.js | 6 + lib.esm/abi/index.js.map | 1 + lib.esm/abi/interface.js | 808 + lib.esm/abi/interface.js.map | 1 + lib.esm/abi/typed.js | 212 + lib.esm/abi/typed.js.map | 1 + lib.esm/address/address.js | 109 + lib.esm/address/address.js.map | 1 + lib.esm/address/checks.js | 46 + lib.esm/address/checks.js.map | 1 + lib.esm/address/contract-address.js | 32 + lib.esm/address/contract-address.js.map | 1 + lib.esm/address/index.js | 4 + lib.esm/address/index.js.map | 1 + lib.esm/constants/addresses.js | 5 + lib.esm/constants/addresses.js.map | 1 + lib.esm/constants/hashes.js | 5 + lib.esm/constants/hashes.js.map | 1 + lib.esm/constants/index.js | 5 + lib.esm/constants/index.js.map | 1 + lib.esm/constants/numbers.js | 38 + lib.esm/constants/numbers.js.map | 1 + lib.esm/constants/strings.js | 7 + lib.esm/constants/strings.js.map | 1 + lib.esm/contract/contract.js | 642 + lib.esm/contract/contract.js.map | 1 + lib.esm/contract/factory.js | 75 + lib.esm/contract/factory.js.map | 1 + lib.esm/contract/index.js | 4 + lib.esm/contract/index.js.map | 1 + lib.esm/contract/types.js | 5 + lib.esm/contract/types.js.map | 1 + lib.esm/contract/wrappers.js | 73 + lib.esm/contract/wrappers.js.map | 1 + lib.esm/crypto/crypto-browser.js | 56 + lib.esm/crypto/crypto-browser.js.map | 1 + lib.esm/crypto/crypto.js | 2 + lib.esm/crypto/crypto.js.map | 1 + lib.esm/crypto/hmac.js | 22 + lib.esm/crypto/hmac.js.map | 1 + lib.esm/crypto/index.js | 24 + lib.esm/crypto/index.js.map | 1 + lib.esm/crypto/keccak.js | 21 + lib.esm/crypto/keccak.js.map | 1 + lib.esm/crypto/pbkdf2.js | 22 + lib.esm/crypto/pbkdf2.js.map | 1 + lib.esm/crypto/random.js | 19 + lib.esm/crypto/random.js.map | 1 + lib.esm/crypto/ripemd160.js | 21 + lib.esm/crypto/ripemd160.js.map | 1 + lib.esm/crypto/scrypt.js | 40 + lib.esm/crypto/scrypt.js.map | 1 + lib.esm/crypto/sha2.js | 38 + lib.esm/crypto/sha2.js.map | 1 + lib.esm/crypto/signature.js | 229 + lib.esm/crypto/signature.js.map | 1 + lib.esm/crypto/signing-key.js | 106 + lib.esm/crypto/signing-key.js.map | 1 + lib.esm/ethers.js | 19 + lib.esm/ethers.js.map | 1 + lib.esm/hash/id.js | 6 + lib.esm/hash/id.js.map | 1 + lib.esm/hash/index.js | 6 + lib.esm/hash/index.js.map | 1 + lib.esm/hash/message.js | 14 + lib.esm/hash/message.js.map | 1 + lib.esm/hash/namehash.js | 72 + lib.esm/hash/namehash.js.map | 1 + lib.esm/hash/solidity.js | 104 + lib.esm/hash/solidity.js.map | 1 + lib.esm/hash/typed-data.js | 429 + lib.esm/hash/typed-data.js.map | 1 + lib.esm/index.js | 4 + lib.esm/index.js.map | 1 + lib.esm/providers/abstract-provider.js | 1088 + lib.esm/providers/abstract-provider.js.map | 1 + lib.esm/providers/abstract-signer.js | 143 + lib.esm/providers/abstract-signer.js.map | 1 + lib.esm/providers/common-networks.js | 77 + lib.esm/providers/common-networks.js.map | 1 + lib.esm/providers/community.js | 21 + lib.esm/providers/community.js.map | 1 + lib.esm/providers/contracts.js | 2 + lib.esm/providers/contracts.js.map | 1 + lib.esm/providers/default-provider.js | 94 + lib.esm/providers/default-provider.js.map | 1 + lib.esm/providers/ens-resolver.js | 465 + lib.esm/providers/ens-resolver.js.map | 1 + lib.esm/providers/formatter.js | 385 + lib.esm/providers/formatter.js.map | 1 + lib.esm/providers/index.js | 38 + lib.esm/providers/index.js.map | 1 + lib.esm/providers/network.js | 187 + lib.esm/providers/network.js.map | 1 + lib.esm/providers/pagination.js | 2 + lib.esm/providers/pagination.js.map | 1 + lib.esm/providers/plugins-network.js | 105 + lib.esm/providers/plugins-network.js.map | 1 + lib.esm/providers/provider-alchemy.js | 97 + lib.esm/providers/provider-alchemy.js.map | 1 + lib.esm/providers/provider-ankr.js | 63 + lib.esm/providers/provider-ankr.js.map | 1 + lib.esm/providers/provider-cloudflare.js | 13 + lib.esm/providers/provider-cloudflare.js.map | 1 + lib.esm/providers/provider-etherscan.js | 463 + lib.esm/providers/provider-etherscan.js.map | 1 + lib.esm/providers/provider-fallback.js | 413 + lib.esm/providers/provider-fallback.js.map | 1 + lib.esm/providers/provider-infura.js | 81 + lib.esm/providers/provider-infura.js.map | 1 + .../providers/provider-ipcsocket-browser.js | 3 + .../provider-ipcsocket-browser.js.map | 1 + lib.esm/providers/provider-ipcsocket.js | 86 + lib.esm/providers/provider-ipcsocket.js.map | 1 + lib.esm/providers/provider-jsonrpc.js | 687 + lib.esm/providers/provider-jsonrpc.js.map | 1 + lib.esm/providers/provider-pocket.js | 101 + lib.esm/providers/provider-pocket.js.map | 1 + lib.esm/providers/provider-socket.js | 217 + lib.esm/providers/provider-socket.js.map | 1 + lib.esm/providers/provider-websocket.js | 26 + lib.esm/providers/provider-websocket.js.map | 1 + lib.esm/providers/provider.js | 551 + lib.esm/providers/provider.js.map | 1 + lib.esm/providers/signer.js | 2 + lib.esm/providers/signer.js.map | 1 + lib.esm/providers/subscriber-connection.js | 37 + .../providers/subscriber-connection.js.map | 1 + lib.esm/providers/subscriber-filterid.js | 105 + lib.esm/providers/subscriber-filterid.js.map | 1 + lib.esm/providers/subscriber-hotswap.js | 43 + lib.esm/providers/subscriber-hotswap.js.map | 1 + lib.esm/providers/subscriber-polling.js | 174 + lib.esm/providers/subscriber-polling.js.map | 1 + lib.esm/providers/subscriber.js | 57 + lib.esm/providers/subscriber.js.map | 1 + lib.esm/providers/ws-browser.js | 16 + lib.esm/providers/ws-browser.js.map | 1 + lib.esm/providers/ws.js | 2 + lib.esm/providers/ws.js.map | 1 + lib.esm/transaction/accesslist.js | 38 + lib.esm/transaction/accesslist.js.map | 1 + lib.esm/transaction/address.js | 10 + lib.esm/transaction/address.js.map | 1 + lib.esm/transaction/index.js | 4 + lib.esm/transaction/index.js.map | 1 + lib.esm/transaction/transaction.js | 575 + lib.esm/transaction/transaction.js.map | 1 + lib.esm/utils/base58.js | 43 + lib.esm/utils/base58.js.map | 1 + lib.esm/utils/base64-browser.js | 19 + lib.esm/utils/base64-browser.js.map | 1 + lib.esm/utils/base64.js | 9 + lib.esm/utils/base64.js.map | 1 + lib.esm/utils/data.js | 77 + lib.esm/utils/data.js.map | 1 + lib.esm/utils/errors.js | 18 + lib.esm/utils/errors.js.map | 1 + lib.esm/utils/events.js | 17 + lib.esm/utils/events.js.map | 1 + lib.esm/utils/fetch.js | 562 + lib.esm/utils/fetch.js.map | 1 + lib.esm/utils/fixednumber.js | 340 + lib.esm/utils/fixednumber.js.map | 1 + lib.esm/utils/geturl-browser.js | 41 + lib.esm/utils/geturl-browser.js.map | 1 + lib.esm/utils/geturl.js | 78 + lib.esm/utils/geturl.js.map | 1 + lib.esm/utils/index.js | 17 + lib.esm/utils/index.js.map | 1 + lib.esm/utils/logger.js | 226 + lib.esm/utils/logger.js.map | 1 + lib.esm/utils/maths.js | 122 + lib.esm/utils/maths.js.map | 1 + lib.esm/utils/properties.js | 106 + lib.esm/utils/properties.js.map | 1 + lib.esm/utils/rlp-decode.js | 83 + lib.esm/utils/rlp-decode.js.map | 1 + lib.esm/utils/rlp-encode.js | 46 + lib.esm/utils/rlp-encode.js.map | 1 + lib.esm/utils/rlp.js | 3 + lib.esm/utils/rlp.js.map | 1 + lib.esm/utils/storage.js | 10 + lib.esm/utils/storage.js.map | 1 + lib.esm/utils/units.js | 59 + lib.esm/utils/units.js.map | 1 + lib.esm/utils/utf8.js | 206 + lib.esm/utils/utf8.js.map | 1 + lib.esm/wallet/base-wallet.js | 62 + lib.esm/wallet/base-wallet.js.map | 1 + lib.esm/wallet/hdwallet.js | 284 + lib.esm/wallet/hdwallet.js.map | 1 + lib.esm/wallet/index.js | 6 + lib.esm/wallet/index.js.map | 1 + lib.esm/wallet/json-crowdsale.js | 41 + lib.esm/wallet/json-crowdsale.js.map | 1 + lib.esm/wallet/json-keystore.js | 279 + lib.esm/wallet/json-keystore.js.map | 1 + lib.esm/wallet/mnemonic.js | 124 + lib.esm/wallet/mnemonic.js.map | 1 + lib.esm/wallet/utils.js | 137 + lib.esm/wallet/utils.js.map | 1 + lib.esm/wallet/wallet.js | 165 + lib.esm/wallet/wallet.js.map | 1 + lib.esm/wordlists/bit-reader.js | 29 + lib.esm/wordlists/bit-reader.js.map | 1 + lib.esm/wordlists/decode-owl.js | 49 + lib.esm/wordlists/decode-owl.js.map | 1 + lib.esm/wordlists/decode-owla.js | 25 + lib.esm/wordlists/decode-owla.js.map | 1 + lib.esm/wordlists/generation/encode-latin.js | 344 + .../wordlists/generation/encode-latin.js.map | 1 + lib.esm/wordlists/index.js | 6 + lib.esm/wordlists/index.js.map | 1 + lib.esm/wordlists/lang-cz.js | 8 + lib.esm/wordlists/lang-cz.js.map | 1 + lib.esm/wordlists/lang-en.js | 8 + lib.esm/wordlists/lang-en.js.map | 1 + lib.esm/wordlists/lang-es.js | 9 + lib.esm/wordlists/lang-es.js.map | 1 + lib.esm/wordlists/lang-fr.js | 9 + lib.esm/wordlists/lang-fr.js.map | 1 + lib.esm/wordlists/lang-it.js | 8 + lib.esm/wordlists/lang-it.js.map | 1 + lib.esm/wordlists/lang-ja.js | 133 + lib.esm/wordlists/lang-ja.js.map | 1 + lib.esm/wordlists/lang-ko.js | 68 + lib.esm/wordlists/lang-ko.js.map | 1 + lib.esm/wordlists/lang-pt.js | 8 + lib.esm/wordlists/lang-pt.js.map | 1 + lib.esm/wordlists/lang-zh.js | 66 + lib.esm/wordlists/lang-zh.js.map | 1 + lib.esm/wordlists/wordlist-owl.js | 46 + lib.esm/wordlists/wordlist-owl.js.map | 1 + lib.esm/wordlists/wordlist-owla.js | 14 + lib.esm/wordlists/wordlist-owla.js.map | 1 + lib.esm/wordlists/wordlist.js | 16 + lib.esm/wordlists/wordlist.js.map | 1 + lib.esm/wordlists/wordlists-browser.js | 6 + lib.esm/wordlists/wordlists-browser.js.map | 1 + lib.esm/wordlists/wordlists-extra.js | 12 + lib.esm/wordlists/wordlists-extra.js.map | 1 + lib.esm/wordlists/wordlists.js | 13 + lib.esm/wordlists/wordlists.js.map | 1 + tsconfig.types.json | 3 +- types/_version.d.ts | 2 + types/_version.d.ts.map | 1 + types/abi/abi-coder.d.ts | 11 + types/abi/abi-coder.d.ts.map | 1 + types/abi/bytes32.d.ts | 4 + types/abi/bytes32.d.ts.map | 1 + types/abi/coders/abstract-coder.d.ts | 49 + types/abi/coders/abstract-coder.d.ts.map | 1 + types/abi/coders/address.d.ts | 10 + types/abi/coders/address.d.ts.map | 1 + types/abi/coders/anonymous.d.ts | 10 + types/abi/coders/anonymous.d.ts.map | 1 + types/abi/coders/array.d.ts | 16 + types/abi/coders/array.d.ts.map | 1 + types/abi/coders/boolean.d.ts | 10 + types/abi/coders/boolean.d.ts.map | 1 + types/abi/coders/bytes.d.ts | 13 + types/abi/coders/bytes.d.ts.map | 1 + types/abi/coders/fixed-bytes.d.ts | 12 + types/abi/coders/fixed-bytes.d.ts.map | 1 + types/abi/coders/null.d.ts | 9 + types/abi/coders/null.d.ts.map | 1 + types/abi/coders/number.d.ts | 13 + types/abi/coders/number.d.ts.map | 1 + types/abi/coders/string.d.ts | 10 + types/abi/coders/string.d.ts.map | 1 + types/abi/coders/tuple.d.ts | 13 + types/abi/coders/tuple.d.ts.map | 1 + types/abi/fragments.d.ts | 153 + types/abi/fragments.d.ts.map | 1 + types/abi/index.d.ts | 8 + types/abi/index.d.ts.map | 1 + types/abi/interface.d.ts | 83 + types/abi/interface.d.ts.map | 1 + types/abi/typed.d.ts | 144 + types/abi/typed.d.ts.map | 1 + types/address/address.d.ts | 3 + types/address/address.d.ts.map | 1 + types/address/checks.d.ts | 5 + types/address/checks.d.ts.map | 1 + types/address/contract-address.d.ts | 7 + types/address/contract-address.d.ts.map | 1 + types/address/index.d.ts | 11 + types/address/index.d.ts.map | 1 + types/constants/addresses.d.ts | 5 + types/constants/addresses.d.ts.map | 1 + types/constants/hashes.d.ts | 5 + types/constants/hashes.d.ts.map | 1 + types/constants/index.d.ts | 5 + types/constants/index.d.ts.map | 1 + types/constants/numbers.d.ts | 38 + types/constants/numbers.d.ts.map | 1 + types/constants/strings.d.ts | 6 + types/constants/strings.d.ts.map | 1 + types/contract/contract.d.ts | 43 + types/contract/contract.d.ts.map | 1 + types/contract/factory.d.ts | 22 + types/contract/factory.d.ts.map | 1 + types/contract/index.d.ts | 5 + types/contract/index.d.ts.map | 1 + types/contract/types.d.ts | 48 + types/contract/types.d.ts.map | 1 + types/contract/wrappers.d.ts | 37 + types/contract/wrappers.d.ts.map | 1 + types/crypto/crypto-browser.d.ts | 15 + types/crypto/crypto-browser.d.ts.map | 1 + types/crypto/crypto.d.ts | 2 + types/crypto/crypto.d.ts.map | 1 + types/crypto/hmac.d.ts | 8 + types/crypto/hmac.d.ts.map | 1 + types/crypto/index.d.ts | 15 + types/crypto/index.d.ts.map | 1 + types/crypto/keccak.d.ts | 8 + types/crypto/keccak.d.ts.map | 1 + types/crypto/pbkdf2.d.ts | 8 + types/crypto/pbkdf2.d.ts.map | 1 + types/crypto/random.d.ts | 7 + types/crypto/random.d.ts.map | 1 + types/crypto/ripemd160.d.ts | 8 + types/crypto/ripemd160.d.ts.map | 1 + types/crypto/scrypt.d.ts | 15 + types/crypto/scrypt.d.ts.map | 1 + types/crypto/sha2.d.ts | 14 + types/crypto/sha2.d.ts.map | 1 + types/crypto/signature.d.ts | 46 + types/crypto/signature.d.ts.map | 1 + types/crypto/signing-key.d.ts | 16 + types/crypto/signing-key.d.ts.map | 1 + types/ethers.d.ts | 21 + types/ethers.d.ts.map | 1 + types/hash/id.d.ts | 2 + types/hash/id.d.ts.map | 1 + types/hash/index.d.ts | 7 + types/hash/index.d.ts.map | 1 + types/hash/message.d.ts | 2 + types/hash/message.d.ts.map | 1 + types/hash/namehash.d.ts | 5 + types/hash/namehash.d.ts.map | 1 + types/hash/solidity.d.ts | 24 + types/hash/solidity.d.ts.map | 1 + types/hash/typed-data.d.ts | 38 + types/hash/typed-data.d.ts.map | 1 + types/index.d.ts | 4 + types/index.d.ts.map | 1 + types/providers/abstract-provider.d.ts | 184 + types/providers/abstract-provider.d.ts.map | 1 + types/providers/abstract-signer.d.ts | 48 + types/providers/abstract-signer.d.ts.map | 1 + types/providers/common-networks.d.ts | 8 + types/providers/common-networks.d.ts.map | 1 + types/providers/community.d.ts | 5 + types/providers/community.d.ts.map | 1 + types/providers/contracts.d.ts | 9 + types/providers/contracts.d.ts.map | 1 + types/providers/default-provider.d.ts | 5 + types/providers/default-provider.d.ts.map | 1 + types/providers/ens-resolver.d.ts | 39 + types/providers/ens-resolver.d.ts.map | 1 + types/providers/formatter.d.ts | 36 + types/providers/formatter.d.ts.map | 1 + types/providers/index.d.ts | 23 + types/providers/index.d.ts.map | 1 + types/providers/network.d.ts | 40 + types/providers/network.d.ts.map | 1 + types/providers/pagination.d.ts | 6 + types/providers/pagination.d.ts.map | 1 + types/providers/plugins-network.d.ts | 42 + types/providers/plugins-network.d.ts.map | 1 + types/providers/provider-alchemy.d.ts | 15 + types/providers/provider-alchemy.d.ts.map | 1 + types/providers/provider-ankr.d.ts | 14 + types/providers/provider-ankr.d.ts.map | 1 + types/providers/provider-cloudflare.d.ts | 6 + types/providers/provider-cloudflare.d.ts.map | 1 + types/providers/provider-etherscan.d.ts | 31 + types/providers/provider-etherscan.d.ts.map | 1 + types/providers/provider-fallback.d.ts | 49 + types/providers/provider-fallback.d.ts.map | 1 + types/providers/provider-infura.d.ts | 15 + types/providers/provider-infura.d.ts.map | 1 + .../providers/provider-ipcsocket-browser.d.ts | 3 + .../provider-ipcsocket-browser.d.ts.map | 1 + types/providers/provider-ipcsocket.d.ts | 12 + types/providers/provider-ipcsocket.d.ts.map | 1 + types/providers/provider-jsonrpc.d.ts | 91 + types/providers/provider-jsonrpc.d.ts.map | 1 + types/providers/provider-pocket.d.ts | 1 + types/providers/provider-pocket.d.ts.map | 1 + types/providers/provider-socket.d.ts | 51 + types/providers/provider-socket.d.ts.map | 1 + types/providers/provider-websocket.d.ts | 18 + types/providers/provider-websocket.d.ts.map | 1 + types/providers/provider.d.ts | 404 + types/providers/provider.d.ts.map | 1 + types/providers/signer.d.ts | 118 + types/providers/signer.d.ts.map | 1 + types/providers/subscriber-connection.d.ts | 15 + .../providers/subscriber-connection.d.ts.map | 1 + types/providers/subscriber-filterid.d.ts | 26 + types/providers/subscriber-filterid.d.ts.map | 1 + types/providers/subscriber-hotswap.d.ts | 1 + types/providers/subscriber-hotswap.d.ts.map | 1 + types/providers/subscriber-polling.d.ts | 41 + types/providers/subscriber-polling.d.ts.map | 1 + types/providers/subscriber.d.ts | 1 + types/providers/subscriber.d.ts.map | 1 + types/providers/ws-browser.d.ts | 3 + types/providers/ws-browser.d.ts.map | 1 + types/providers/ws.d.ts | 2 + types/providers/ws.d.ts.map | 1 + types/transaction/accesslist.d.ts | 3 + types/transaction/accesslist.d.ts.map | 1 + types/transaction/address.d.ts | 5 + types/transaction/address.d.ts.map | 1 + types/transaction/index.d.ts | 11 + types/transaction/index.d.ts.map | 1 + types/transaction/transaction.d.ts | 86 + types/transaction/transaction.d.ts.map | 1 + types/utils/base58.d.ts | 10 + types/utils/base58.d.ts.map | 1 + types/utils/base64-browser.d.ts | 4 + types/utils/base64-browser.d.ts.map | 1 + types/utils/base64.d.ts | 4 + types/utils/base64.d.ts.map | 1 + types/utils/data.d.ts | 11 + types/utils/data.d.ts.map | 1 + types/utils/errors.d.ts | 140 + types/utils/errors.d.ts.map | 1 + types/utils/events.d.ts | 20 + types/utils/events.d.ts.map | 1 + types/utils/fetch.d.ts | 105 + types/utils/fetch.d.ts.map | 1 + types/utils/fixednumber.d.ts | 37 + types/utils/fixednumber.d.ts.map | 1 + types/utils/geturl-browser.d.ts | 21 + types/utils/geturl-browser.d.ts.map | 1 + types/utils/geturl.d.ts | 3 + types/utils/geturl.d.ts.map | 1 + types/utils/index.d.ts | 31 + types/utils/index.d.ts.map | 1 + types/utils/logger.d.ts | 28 + types/utils/logger.d.ts.map | 1 + types/utils/maths.d.ts | 28 + types/utils/maths.d.ts.map | 1 + types/utils/properties.d.ts | 12 + types/utils/properties.d.ts.map | 1 + types/utils/rlp-decode.d.ts | 3 + types/utils/rlp-decode.d.ts.map | 1 + types/utils/rlp-encode.d.ts | 3 + types/utils/rlp-encode.d.ts.map | 1 + types/utils/rlp.d.ts | 4 + types/utils/rlp.d.ts.map | 1 + types/utils/storage.d.ts | 3 + types/utils/storage.d.ts.map | 1 + types/utils/units.d.ts | 24 + types/utils/units.d.ts.map | 1 + types/utils/utf8.d.ts | 11 + types/utils/utf8.d.ts.map | 1 + types/wallet/base-wallet.d.ts | 17 + types/wallet/base-wallet.d.ts.map | 1 + types/wallet/hdwallet.d.ts | 60 + types/wallet/hdwallet.d.ts.map | 1 + types/wallet/index.d.ts | 7 + types/wallet/index.d.ts.map | 1 + types/wallet/json-crowdsale.d.ts | 7 + types/wallet/json-crowdsale.d.ts.map | 1 + types/wallet/json-keystore.d.ts | 37 + types/wallet/json-keystore.d.ts.map | 1 + types/wallet/mnemonic.d.ts | 16 + types/wallet/mnemonic.d.ts.map | 1 + types/wallet/utils.d.ts | 7 + types/wallet/utils.d.ts.map | 1 + types/wallet/wallet.d.ts | 20 + types/wallet/wallet.d.ts.map | 1 + types/wordlists/bit-reader.d.ts | 2 + types/wordlists/bit-reader.d.ts.map | 1 + types/wordlists/decode-owl.d.ts | 3 + types/wordlists/decode-owl.d.ts.map | 1 + types/wordlists/decode-owla.d.ts | 2 + types/wordlists/decode-owla.d.ts.map | 1 + types/wordlists/generation/encode-latin.d.ts | 25 + .../generation/encode-latin.d.ts.map | 1 + types/wordlists/index.d.ts | 6 + types/wordlists/index.d.ts.map | 1 + types/wordlists/lang-cz.d.ts | 6 + types/wordlists/lang-cz.d.ts.map | 1 + types/wordlists/lang-en.d.ts | 6 + types/wordlists/lang-en.d.ts.map | 1 + types/wordlists/lang-es.d.ts | 6 + types/wordlists/lang-es.d.ts.map | 1 + types/wordlists/lang-fr.d.ts | 6 + types/wordlists/lang-fr.d.ts.map | 1 + types/wordlists/lang-it.d.ts | 6 + types/wordlists/lang-it.d.ts.map | 1 + types/wordlists/lang-ja.d.ts | 11 + types/wordlists/lang-ja.d.ts.map | 1 + types/wordlists/lang-ko.d.ts | 9 + types/wordlists/lang-ko.d.ts.map | 1 + types/wordlists/lang-pt.d.ts | 6 + types/wordlists/lang-pt.d.ts.map | 1 + types/wordlists/lang-zh.d.ts | 11 + types/wordlists/lang-zh.d.ts.map | 1 + types/wordlists/wordlist-owl.d.ts | 10 + types/wordlists/wordlist-owl.d.ts.map | 1 + types/wordlists/wordlist-owla.d.ts | 8 + types/wordlists/wordlist-owla.d.ts.map | 1 + types/wordlists/wordlist.d.ts | 9 + types/wordlists/wordlist.d.ts.map | 1 + types/wordlists/wordlists-browser.d.ts | 3 + types/wordlists/wordlists-browser.d.ts.map | 1 + types/wordlists/wordlists-extra.d.ts | 3 + types/wordlists/wordlists-extra.d.ts.map | 1 + types/wordlists/wordlists.d.ts | 3 + types/wordlists/wordlists.d.ts.map | 1 + 900 files changed, 57504 insertions(+), 1 deletion(-) create mode 100644 dist/ethers.js create mode 100644 dist/ethers.min.js create mode 100644 dist/wordlists-extra.js create mode 100644 dist/wordlists-extra.min.js create mode 100644 lib.commonjs/_tests/test-abi.js create mode 100644 lib.commonjs/_tests/test-abi.js.map create mode 100644 lib.commonjs/_tests/test-address.js create mode 100644 lib.commonjs/_tests/test-address.js.map create mode 100644 lib.commonjs/_tests/test-contract.js create mode 100644 lib.commonjs/_tests/test-contract.js.map create mode 100644 lib.commonjs/_tests/test-crypto-algoswap.js create mode 100644 lib.commonjs/_tests/test-crypto-algoswap.js.map create mode 100644 lib.commonjs/_tests/test-crypto.js create mode 100644 lib.commonjs/_tests/test-crypto.js.map create mode 100644 lib.commonjs/_tests/test-hash-typeddata.js create mode 100644 lib.commonjs/_tests/test-hash-typeddata.js.map create mode 100644 lib.commonjs/_tests/test-hash.js create mode 100644 lib.commonjs/_tests/test-hash.js.map create mode 100644 lib.commonjs/_tests/test-rlp.js create mode 100644 lib.commonjs/_tests/test-rlp.js.map create mode 100644 lib.commonjs/_tests/test-transaction.js create mode 100644 lib.commonjs/_tests/test-transaction.js.map create mode 100644 lib.commonjs/_tests/test-wallet-hd.js create mode 100644 lib.commonjs/_tests/test-wallet-hd.js.map create mode 100644 lib.commonjs/_tests/test-wallet-json.js create mode 100644 lib.commonjs/_tests/test-wallet-json.js.map create mode 100644 lib.commonjs/_tests/test-wallet-mnemonic.js create mode 100644 lib.commonjs/_tests/test-wallet-mnemonic.js.map create mode 100644 lib.commonjs/_tests/test-wallet.js create mode 100644 lib.commonjs/_tests/test-wallet.js.map create mode 100644 lib.commonjs/_tests/test-wordlists.js create mode 100644 lib.commonjs/_tests/test-wordlists.js.map create mode 100644 lib.commonjs/_tests/types.js create mode 100644 lib.commonjs/_tests/types.js.map create mode 100644 lib.commonjs/_tests/utils.js create mode 100644 lib.commonjs/_tests/utils.js.map create mode 100644 lib.commonjs/_version.js create mode 100644 lib.commonjs/_version.js.map create mode 100644 lib.commonjs/abi/abi-coder.js create mode 100644 lib.commonjs/abi/abi-coder.js.map create mode 100644 lib.commonjs/abi/bytes32.js create mode 100644 lib.commonjs/abi/bytes32.js.map create mode 100644 lib.commonjs/abi/coders/abstract-coder.js create mode 100644 lib.commonjs/abi/coders/abstract-coder.js.map create mode 100644 lib.commonjs/abi/coders/address.js create mode 100644 lib.commonjs/abi/coders/address.js.map create mode 100644 lib.commonjs/abi/coders/anonymous.js create mode 100644 lib.commonjs/abi/coders/anonymous.js.map create mode 100644 lib.commonjs/abi/coders/array.js create mode 100644 lib.commonjs/abi/coders/array.js.map create mode 100644 lib.commonjs/abi/coders/boolean.js create mode 100644 lib.commonjs/abi/coders/boolean.js.map create mode 100644 lib.commonjs/abi/coders/bytes.js create mode 100644 lib.commonjs/abi/coders/bytes.js.map create mode 100644 lib.commonjs/abi/coders/fixed-bytes.js create mode 100644 lib.commonjs/abi/coders/fixed-bytes.js.map create mode 100644 lib.commonjs/abi/coders/null.js create mode 100644 lib.commonjs/abi/coders/null.js.map create mode 100644 lib.commonjs/abi/coders/number.js create mode 100644 lib.commonjs/abi/coders/number.js.map create mode 100644 lib.commonjs/abi/coders/string.js create mode 100644 lib.commonjs/abi/coders/string.js.map create mode 100644 lib.commonjs/abi/coders/tuple.js create mode 100644 lib.commonjs/abi/coders/tuple.js.map create mode 100644 lib.commonjs/abi/fragments.js create mode 100644 lib.commonjs/abi/fragments.js.map create mode 100644 lib.commonjs/abi/index.js create mode 100644 lib.commonjs/abi/index.js.map create mode 100644 lib.commonjs/abi/interface.js create mode 100644 lib.commonjs/abi/interface.js.map create mode 100644 lib.commonjs/abi/typed.js create mode 100644 lib.commonjs/abi/typed.js.map create mode 100644 lib.commonjs/address/address.js create mode 100644 lib.commonjs/address/address.js.map create mode 100644 lib.commonjs/address/checks.js create mode 100644 lib.commonjs/address/checks.js.map create mode 100644 lib.commonjs/address/contract-address.js create mode 100644 lib.commonjs/address/contract-address.js.map create mode 100644 lib.commonjs/address/index.js create mode 100644 lib.commonjs/address/index.js.map create mode 100644 lib.commonjs/constants/addresses.js create mode 100644 lib.commonjs/constants/addresses.js.map create mode 100644 lib.commonjs/constants/hashes.js create mode 100644 lib.commonjs/constants/hashes.js.map create mode 100644 lib.commonjs/constants/index.js create mode 100644 lib.commonjs/constants/index.js.map create mode 100644 lib.commonjs/constants/numbers.js create mode 100644 lib.commonjs/constants/numbers.js.map create mode 100644 lib.commonjs/constants/strings.js create mode 100644 lib.commonjs/constants/strings.js.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.js create mode 100644 lib.commonjs/contract/factory.js.map create mode 100644 lib.commonjs/contract/index.js create mode 100644 lib.commonjs/contract/index.js.map create mode 100644 lib.commonjs/contract/types.js create mode 100644 lib.commonjs/contract/types.js.map create mode 100644 lib.commonjs/contract/wrappers.js create mode 100644 lib.commonjs/contract/wrappers.js.map create mode 100644 lib.commonjs/crypto/crypto-browser.js create mode 100644 lib.commonjs/crypto/crypto-browser.js.map create mode 100644 lib.commonjs/crypto/crypto.js create mode 100644 lib.commonjs/crypto/crypto.js.map create mode 100644 lib.commonjs/crypto/hmac.js create mode 100644 lib.commonjs/crypto/hmac.js.map create mode 100644 lib.commonjs/crypto/index.js create mode 100644 lib.commonjs/crypto/index.js.map create mode 100644 lib.commonjs/crypto/keccak.js create mode 100644 lib.commonjs/crypto/keccak.js.map create mode 100644 lib.commonjs/crypto/pbkdf2.js create mode 100644 lib.commonjs/crypto/pbkdf2.js.map create mode 100644 lib.commonjs/crypto/random.js create mode 100644 lib.commonjs/crypto/random.js.map create mode 100644 lib.commonjs/crypto/ripemd160.js create mode 100644 lib.commonjs/crypto/ripemd160.js.map create mode 100644 lib.commonjs/crypto/scrypt.js create mode 100644 lib.commonjs/crypto/scrypt.js.map create mode 100644 lib.commonjs/crypto/sha2.js create mode 100644 lib.commonjs/crypto/sha2.js.map create mode 100644 lib.commonjs/crypto/signature.js create mode 100644 lib.commonjs/crypto/signature.js.map create mode 100644 lib.commonjs/crypto/signing-key.js create mode 100644 lib.commonjs/crypto/signing-key.js.map create mode 100644 lib.commonjs/ethers.js create mode 100644 lib.commonjs/ethers.js.map create mode 100644 lib.commonjs/hash/id.js create mode 100644 lib.commonjs/hash/id.js.map create mode 100644 lib.commonjs/hash/index.js create mode 100644 lib.commonjs/hash/index.js.map create mode 100644 lib.commonjs/hash/message.js create mode 100644 lib.commonjs/hash/message.js.map create mode 100644 lib.commonjs/hash/namehash.js create mode 100644 lib.commonjs/hash/namehash.js.map create mode 100644 lib.commonjs/hash/solidity.js create mode 100644 lib.commonjs/hash/solidity.js.map create mode 100644 lib.commonjs/hash/typed-data.js create mode 100644 lib.commonjs/hash/typed-data.js.map create mode 100644 lib.commonjs/index.js create mode 100644 lib.commonjs/index.js.map create mode 100644 lib.commonjs/package.json 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.js create mode 100644 lib.commonjs/providers/abstract-signer.js.map create mode 100644 lib.commonjs/providers/common-networks.js create mode 100644 lib.commonjs/providers/common-networks.js.map create mode 100644 lib.commonjs/providers/community.js create mode 100644 lib.commonjs/providers/community.js.map create mode 100644 lib.commonjs/providers/contracts.js create mode 100644 lib.commonjs/providers/contracts.js.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/ens-resolver.js create mode 100644 lib.commonjs/providers/ens-resolver.js.map create mode 100644 lib.commonjs/providers/formatter.js create mode 100644 lib.commonjs/providers/formatter.js.map create mode 100644 lib.commonjs/providers/index.js create mode 100644 lib.commonjs/providers/index.js.map create mode 100644 lib.commonjs/providers/network.js create mode 100644 lib.commonjs/providers/network.js.map create mode 100644 lib.commonjs/providers/pagination.js create mode 100644 lib.commonjs/providers/pagination.js.map create mode 100644 lib.commonjs/providers/plugins-network.js create mode 100644 lib.commonjs/providers/plugins-network.js.map create mode 100644 lib.commonjs/providers/provider-alchemy.js create mode 100644 lib.commonjs/providers/provider-alchemy.js.map create mode 100644 lib.commonjs/providers/provider-ankr.js create mode 100644 lib.commonjs/providers/provider-ankr.js.map create mode 100644 lib.commonjs/providers/provider-cloudflare.js create mode 100644 lib.commonjs/providers/provider-cloudflare.js.map create mode 100644 lib.commonjs/providers/provider-etherscan.js create mode 100644 lib.commonjs/providers/provider-etherscan.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-infura.js create mode 100644 lib.commonjs/providers/provider-infura.js.map create mode 100644 lib.commonjs/providers/provider-ipcsocket-browser.js create mode 100644 lib.commonjs/providers/provider-ipcsocket-browser.js.map create mode 100644 lib.commonjs/providers/provider-ipcsocket.js create mode 100644 lib.commonjs/providers/provider-ipcsocket.js.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-pocket.js create mode 100644 lib.commonjs/providers/provider-pocket.js.map create mode 100644 lib.commonjs/providers/provider-socket.js create mode 100644 lib.commonjs/providers/provider-socket.js.map create mode 100644 lib.commonjs/providers/provider-websocket.js create mode 100644 lib.commonjs/providers/provider-websocket.js.map create mode 100644 lib.commonjs/providers/provider.js create mode 100644 lib.commonjs/providers/provider.js.map create mode 100644 lib.commonjs/providers/signer.js create mode 100644 lib.commonjs/providers/signer.js.map create mode 100644 lib.commonjs/providers/subscriber-connection.js create mode 100644 lib.commonjs/providers/subscriber-connection.js.map create mode 100644 lib.commonjs/providers/subscriber-filterid.js create mode 100644 lib.commonjs/providers/subscriber-filterid.js.map create mode 100644 lib.commonjs/providers/subscriber-hotswap.js create mode 100644 lib.commonjs/providers/subscriber-hotswap.js.map create mode 100644 lib.commonjs/providers/subscriber-polling.js create mode 100644 lib.commonjs/providers/subscriber-polling.js.map create mode 100644 lib.commonjs/providers/subscriber.js create mode 100644 lib.commonjs/providers/subscriber.js.map create mode 100644 lib.commonjs/providers/ws-browser.js create mode 100644 lib.commonjs/providers/ws-browser.js.map create mode 100644 lib.commonjs/providers/ws.js create mode 100644 lib.commonjs/providers/ws.js.map create mode 100644 lib.commonjs/transaction/accesslist.js create mode 100644 lib.commonjs/transaction/accesslist.js.map create mode 100644 lib.commonjs/transaction/address.js create mode 100644 lib.commonjs/transaction/address.js.map create mode 100644 lib.commonjs/transaction/index.js create mode 100644 lib.commonjs/transaction/index.js.map create mode 100644 lib.commonjs/transaction/transaction.js create mode 100644 lib.commonjs/transaction/transaction.js.map create mode 100644 lib.commonjs/utils/base58.js create mode 100644 lib.commonjs/utils/base58.js.map create mode 100644 lib.commonjs/utils/base64-browser.js create mode 100644 lib.commonjs/utils/base64-browser.js.map create mode 100644 lib.commonjs/utils/base64.js create mode 100644 lib.commonjs/utils/base64.js.map create mode 100644 lib.commonjs/utils/data.js create mode 100644 lib.commonjs/utils/data.js.map create mode 100644 lib.commonjs/utils/errors.js create mode 100644 lib.commonjs/utils/errors.js.map create mode 100644 lib.commonjs/utils/events.js create mode 100644 lib.commonjs/utils/events.js.map create mode 100644 lib.commonjs/utils/fetch.js create mode 100644 lib.commonjs/utils/fetch.js.map create mode 100644 lib.commonjs/utils/fixednumber.js create mode 100644 lib.commonjs/utils/fixednumber.js.map create mode 100644 lib.commonjs/utils/geturl-browser.js create mode 100644 lib.commonjs/utils/geturl-browser.js.map create mode 100644 lib.commonjs/utils/geturl.js create mode 100644 lib.commonjs/utils/geturl.js.map create mode 100644 lib.commonjs/utils/index.js create mode 100644 lib.commonjs/utils/index.js.map create mode 100644 lib.commonjs/utils/logger.js create mode 100644 lib.commonjs/utils/logger.js.map create mode 100644 lib.commonjs/utils/maths.js create mode 100644 lib.commonjs/utils/maths.js.map create mode 100644 lib.commonjs/utils/properties.js create mode 100644 lib.commonjs/utils/properties.js.map create mode 100644 lib.commonjs/utils/rlp-decode.js create mode 100644 lib.commonjs/utils/rlp-decode.js.map create mode 100644 lib.commonjs/utils/rlp-encode.js create mode 100644 lib.commonjs/utils/rlp-encode.js.map create mode 100644 lib.commonjs/utils/rlp.js create mode 100644 lib.commonjs/utils/rlp.js.map create mode 100644 lib.commonjs/utils/storage.js create mode 100644 lib.commonjs/utils/storage.js.map create mode 100644 lib.commonjs/utils/units.js create mode 100644 lib.commonjs/utils/units.js.map create mode 100644 lib.commonjs/utils/utf8.js create mode 100644 lib.commonjs/utils/utf8.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.commonjs/wallet/hdwallet.js create mode 100644 lib.commonjs/wallet/hdwallet.js.map create mode 100644 lib.commonjs/wallet/index.js create mode 100644 lib.commonjs/wallet/index.js.map create mode 100644 lib.commonjs/wallet/json-crowdsale.js create mode 100644 lib.commonjs/wallet/json-crowdsale.js.map create mode 100644 lib.commonjs/wallet/json-keystore.js create mode 100644 lib.commonjs/wallet/json-keystore.js.map create mode 100644 lib.commonjs/wallet/mnemonic.js create mode 100644 lib.commonjs/wallet/mnemonic.js.map create mode 100644 lib.commonjs/wallet/utils.js create mode 100644 lib.commonjs/wallet/utils.js.map create mode 100644 lib.commonjs/wallet/wallet.js create mode 100644 lib.commonjs/wallet/wallet.js.map create mode 100644 lib.commonjs/wordlists/bit-reader.js create mode 100644 lib.commonjs/wordlists/bit-reader.js.map create mode 100644 lib.commonjs/wordlists/decode-owl.js create mode 100644 lib.commonjs/wordlists/decode-owl.js.map create mode 100644 lib.commonjs/wordlists/decode-owla.js create mode 100644 lib.commonjs/wordlists/decode-owla.js.map create mode 100644 lib.commonjs/wordlists/generation/encode-latin.js create mode 100644 lib.commonjs/wordlists/generation/encode-latin.js.map create mode 100644 lib.commonjs/wordlists/index.js create mode 100644 lib.commonjs/wordlists/index.js.map create mode 100644 lib.commonjs/wordlists/lang-cz.js create mode 100644 lib.commonjs/wordlists/lang-cz.js.map create mode 100644 lib.commonjs/wordlists/lang-en.js create mode 100644 lib.commonjs/wordlists/lang-en.js.map create mode 100644 lib.commonjs/wordlists/lang-es.js create mode 100644 lib.commonjs/wordlists/lang-es.js.map create mode 100644 lib.commonjs/wordlists/lang-fr.js create mode 100644 lib.commonjs/wordlists/lang-fr.js.map create mode 100644 lib.commonjs/wordlists/lang-it.js create mode 100644 lib.commonjs/wordlists/lang-it.js.map create mode 100644 lib.commonjs/wordlists/lang-ja.js create mode 100644 lib.commonjs/wordlists/lang-ja.js.map create mode 100644 lib.commonjs/wordlists/lang-ko.js create mode 100644 lib.commonjs/wordlists/lang-ko.js.map create mode 100644 lib.commonjs/wordlists/lang-pt.js create mode 100644 lib.commonjs/wordlists/lang-pt.js.map create mode 100644 lib.commonjs/wordlists/lang-zh.js create mode 100644 lib.commonjs/wordlists/lang-zh.js.map create mode 100644 lib.commonjs/wordlists/wordlist-owl.js create mode 100644 lib.commonjs/wordlists/wordlist-owl.js.map create mode 100644 lib.commonjs/wordlists/wordlist-owla.js create mode 100644 lib.commonjs/wordlists/wordlist-owla.js.map create mode 100644 lib.commonjs/wordlists/wordlist.js create mode 100644 lib.commonjs/wordlists/wordlist.js.map create mode 100644 lib.commonjs/wordlists/wordlists-browser.js create mode 100644 lib.commonjs/wordlists/wordlists-browser.js.map create mode 100644 lib.commonjs/wordlists/wordlists-extra.js create mode 100644 lib.commonjs/wordlists/wordlists-extra.js.map create mode 100644 lib.commonjs/wordlists/wordlists.js create mode 100644 lib.commonjs/wordlists/wordlists.js.map create mode 100644 lib.esm/_admin/update-version-const.js create mode 100644 lib.esm/_admin/update-version-const.js.map create mode 100644 lib.esm/_admin/utils/fs.js create mode 100644 lib.esm/_admin/utils/fs.js.map create mode 100644 lib.esm/_admin/utils/json.js create mode 100644 lib.esm/_admin/utils/json.js.map create mode 100644 lib.esm/_admin/utils/path.js create mode 100644 lib.esm/_admin/utils/path.js.map create mode 100644 lib.esm/_tests/test-abi.js create mode 100644 lib.esm/_tests/test-abi.js.map create mode 100644 lib.esm/_tests/test-address.js create mode 100644 lib.esm/_tests/test-address.js.map create mode 100644 lib.esm/_tests/test-contract.js create mode 100644 lib.esm/_tests/test-contract.js.map create mode 100644 lib.esm/_tests/test-crypto-algoswap.js create mode 100644 lib.esm/_tests/test-crypto-algoswap.js.map create mode 100644 lib.esm/_tests/test-crypto.js create mode 100644 lib.esm/_tests/test-crypto.js.map create mode 100644 lib.esm/_tests/test-hash-typeddata.js create mode 100644 lib.esm/_tests/test-hash-typeddata.js.map create mode 100644 lib.esm/_tests/test-hash.js create mode 100644 lib.esm/_tests/test-hash.js.map create mode 100644 lib.esm/_tests/test-rlp.js create mode 100644 lib.esm/_tests/test-rlp.js.map create mode 100644 lib.esm/_tests/test-transaction.js create mode 100644 lib.esm/_tests/test-transaction.js.map create mode 100644 lib.esm/_tests/test-wallet-hd.js create mode 100644 lib.esm/_tests/test-wallet-hd.js.map create mode 100644 lib.esm/_tests/test-wallet-json.js create mode 100644 lib.esm/_tests/test-wallet-json.js.map create mode 100644 lib.esm/_tests/test-wallet-mnemonic.js create mode 100644 lib.esm/_tests/test-wallet-mnemonic.js.map create mode 100644 lib.esm/_tests/test-wallet.js create mode 100644 lib.esm/_tests/test-wallet.js.map create mode 100644 lib.esm/_tests/test-wordlists.js create mode 100644 lib.esm/_tests/test-wordlists.js.map create mode 100644 lib.esm/_tests/types.js create mode 100644 lib.esm/_tests/types.js.map create mode 100644 lib.esm/_tests/utils.js create mode 100644 lib.esm/_tests/utils.js.map create mode 100644 lib.esm/_version.js create mode 100644 lib.esm/_version.js.map create mode 100644 lib.esm/abi/abi-coder.js create mode 100644 lib.esm/abi/abi-coder.js.map create mode 100644 lib.esm/abi/bytes32.js create mode 100644 lib.esm/abi/bytes32.js.map create mode 100644 lib.esm/abi/coders/abstract-coder.js create mode 100644 lib.esm/abi/coders/abstract-coder.js.map create mode 100644 lib.esm/abi/coders/address.js create mode 100644 lib.esm/abi/coders/address.js.map create mode 100644 lib.esm/abi/coders/anonymous.js create mode 100644 lib.esm/abi/coders/anonymous.js.map create mode 100644 lib.esm/abi/coders/array.js create mode 100644 lib.esm/abi/coders/array.js.map create mode 100644 lib.esm/abi/coders/boolean.js create mode 100644 lib.esm/abi/coders/boolean.js.map create mode 100644 lib.esm/abi/coders/bytes.js create mode 100644 lib.esm/abi/coders/bytes.js.map create mode 100644 lib.esm/abi/coders/fixed-bytes.js create mode 100644 lib.esm/abi/coders/fixed-bytes.js.map create mode 100644 lib.esm/abi/coders/null.js create mode 100644 lib.esm/abi/coders/null.js.map create mode 100644 lib.esm/abi/coders/number.js create mode 100644 lib.esm/abi/coders/number.js.map create mode 100644 lib.esm/abi/coders/string.js create mode 100644 lib.esm/abi/coders/string.js.map create mode 100644 lib.esm/abi/coders/tuple.js create mode 100644 lib.esm/abi/coders/tuple.js.map create mode 100644 lib.esm/abi/fragments.js create mode 100644 lib.esm/abi/fragments.js.map create mode 100644 lib.esm/abi/index.js create mode 100644 lib.esm/abi/index.js.map create mode 100644 lib.esm/abi/interface.js create mode 100644 lib.esm/abi/interface.js.map create mode 100644 lib.esm/abi/typed.js create mode 100644 lib.esm/abi/typed.js.map create mode 100644 lib.esm/address/address.js create mode 100644 lib.esm/address/address.js.map create mode 100644 lib.esm/address/checks.js create mode 100644 lib.esm/address/checks.js.map create mode 100644 lib.esm/address/contract-address.js create mode 100644 lib.esm/address/contract-address.js.map create mode 100644 lib.esm/address/index.js create mode 100644 lib.esm/address/index.js.map create mode 100644 lib.esm/constants/addresses.js create mode 100644 lib.esm/constants/addresses.js.map create mode 100644 lib.esm/constants/hashes.js create mode 100644 lib.esm/constants/hashes.js.map create mode 100644 lib.esm/constants/index.js create mode 100644 lib.esm/constants/index.js.map create mode 100644 lib.esm/constants/numbers.js create mode 100644 lib.esm/constants/numbers.js.map create mode 100644 lib.esm/constants/strings.js create mode 100644 lib.esm/constants/strings.js.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.js create mode 100644 lib.esm/contract/factory.js.map create mode 100644 lib.esm/contract/index.js create mode 100644 lib.esm/contract/index.js.map create mode 100644 lib.esm/contract/types.js create mode 100644 lib.esm/contract/types.js.map create mode 100644 lib.esm/contract/wrappers.js create mode 100644 lib.esm/contract/wrappers.js.map create mode 100644 lib.esm/crypto/crypto-browser.js create mode 100644 lib.esm/crypto/crypto-browser.js.map create mode 100644 lib.esm/crypto/crypto.js create mode 100644 lib.esm/crypto/crypto.js.map create mode 100644 lib.esm/crypto/hmac.js create mode 100644 lib.esm/crypto/hmac.js.map create mode 100644 lib.esm/crypto/index.js create mode 100644 lib.esm/crypto/index.js.map create mode 100644 lib.esm/crypto/keccak.js create mode 100644 lib.esm/crypto/keccak.js.map create mode 100644 lib.esm/crypto/pbkdf2.js create mode 100644 lib.esm/crypto/pbkdf2.js.map create mode 100644 lib.esm/crypto/random.js create mode 100644 lib.esm/crypto/random.js.map create mode 100644 lib.esm/crypto/ripemd160.js create mode 100644 lib.esm/crypto/ripemd160.js.map create mode 100644 lib.esm/crypto/scrypt.js create mode 100644 lib.esm/crypto/scrypt.js.map create mode 100644 lib.esm/crypto/sha2.js create mode 100644 lib.esm/crypto/sha2.js.map create mode 100644 lib.esm/crypto/signature.js create mode 100644 lib.esm/crypto/signature.js.map create mode 100644 lib.esm/crypto/signing-key.js create mode 100644 lib.esm/crypto/signing-key.js.map create mode 100644 lib.esm/ethers.js create mode 100644 lib.esm/ethers.js.map create mode 100644 lib.esm/hash/id.js create mode 100644 lib.esm/hash/id.js.map create mode 100644 lib.esm/hash/index.js create mode 100644 lib.esm/hash/index.js.map create mode 100644 lib.esm/hash/message.js create mode 100644 lib.esm/hash/message.js.map create mode 100644 lib.esm/hash/namehash.js create mode 100644 lib.esm/hash/namehash.js.map create mode 100644 lib.esm/hash/solidity.js create mode 100644 lib.esm/hash/solidity.js.map create mode 100644 lib.esm/hash/typed-data.js create mode 100644 lib.esm/hash/typed-data.js.map create mode 100644 lib.esm/index.js create mode 100644 lib.esm/index.js.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.js create mode 100644 lib.esm/providers/abstract-signer.js.map create mode 100644 lib.esm/providers/common-networks.js create mode 100644 lib.esm/providers/common-networks.js.map create mode 100644 lib.esm/providers/community.js create mode 100644 lib.esm/providers/community.js.map create mode 100644 lib.esm/providers/contracts.js create mode 100644 lib.esm/providers/contracts.js.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/ens-resolver.js create mode 100644 lib.esm/providers/ens-resolver.js.map create mode 100644 lib.esm/providers/formatter.js create mode 100644 lib.esm/providers/formatter.js.map create mode 100644 lib.esm/providers/index.js create mode 100644 lib.esm/providers/index.js.map create mode 100644 lib.esm/providers/network.js create mode 100644 lib.esm/providers/network.js.map create mode 100644 lib.esm/providers/pagination.js create mode 100644 lib.esm/providers/pagination.js.map create mode 100644 lib.esm/providers/plugins-network.js create mode 100644 lib.esm/providers/plugins-network.js.map create mode 100644 lib.esm/providers/provider-alchemy.js create mode 100644 lib.esm/providers/provider-alchemy.js.map create mode 100644 lib.esm/providers/provider-ankr.js create mode 100644 lib.esm/providers/provider-ankr.js.map create mode 100644 lib.esm/providers/provider-cloudflare.js create mode 100644 lib.esm/providers/provider-cloudflare.js.map create mode 100644 lib.esm/providers/provider-etherscan.js create mode 100644 lib.esm/providers/provider-etherscan.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-infura.js create mode 100644 lib.esm/providers/provider-infura.js.map create mode 100644 lib.esm/providers/provider-ipcsocket-browser.js create mode 100644 lib.esm/providers/provider-ipcsocket-browser.js.map create mode 100644 lib.esm/providers/provider-ipcsocket.js create mode 100644 lib.esm/providers/provider-ipcsocket.js.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-pocket.js create mode 100644 lib.esm/providers/provider-pocket.js.map create mode 100644 lib.esm/providers/provider-socket.js create mode 100644 lib.esm/providers/provider-socket.js.map create mode 100644 lib.esm/providers/provider-websocket.js create mode 100644 lib.esm/providers/provider-websocket.js.map create mode 100644 lib.esm/providers/provider.js create mode 100644 lib.esm/providers/provider.js.map create mode 100644 lib.esm/providers/signer.js create mode 100644 lib.esm/providers/signer.js.map create mode 100644 lib.esm/providers/subscriber-connection.js create mode 100644 lib.esm/providers/subscriber-connection.js.map create mode 100644 lib.esm/providers/subscriber-filterid.js create mode 100644 lib.esm/providers/subscriber-filterid.js.map create mode 100644 lib.esm/providers/subscriber-hotswap.js create mode 100644 lib.esm/providers/subscriber-hotswap.js.map create mode 100644 lib.esm/providers/subscriber-polling.js create mode 100644 lib.esm/providers/subscriber-polling.js.map create mode 100644 lib.esm/providers/subscriber.js create mode 100644 lib.esm/providers/subscriber.js.map create mode 100644 lib.esm/providers/ws-browser.js create mode 100644 lib.esm/providers/ws-browser.js.map create mode 100644 lib.esm/providers/ws.js create mode 100644 lib.esm/providers/ws.js.map create mode 100644 lib.esm/transaction/accesslist.js create mode 100644 lib.esm/transaction/accesslist.js.map create mode 100644 lib.esm/transaction/address.js create mode 100644 lib.esm/transaction/address.js.map create mode 100644 lib.esm/transaction/index.js create mode 100644 lib.esm/transaction/index.js.map create mode 100644 lib.esm/transaction/transaction.js create mode 100644 lib.esm/transaction/transaction.js.map create mode 100644 lib.esm/utils/base58.js create mode 100644 lib.esm/utils/base58.js.map create mode 100644 lib.esm/utils/base64-browser.js create mode 100644 lib.esm/utils/base64-browser.js.map create mode 100644 lib.esm/utils/base64.js create mode 100644 lib.esm/utils/base64.js.map create mode 100644 lib.esm/utils/data.js create mode 100644 lib.esm/utils/data.js.map create mode 100644 lib.esm/utils/errors.js create mode 100644 lib.esm/utils/errors.js.map create mode 100644 lib.esm/utils/events.js create mode 100644 lib.esm/utils/events.js.map create mode 100644 lib.esm/utils/fetch.js create mode 100644 lib.esm/utils/fetch.js.map create mode 100644 lib.esm/utils/fixednumber.js create mode 100644 lib.esm/utils/fixednumber.js.map create mode 100644 lib.esm/utils/geturl-browser.js create mode 100644 lib.esm/utils/geturl-browser.js.map create mode 100644 lib.esm/utils/geturl.js create mode 100644 lib.esm/utils/geturl.js.map create mode 100644 lib.esm/utils/index.js create mode 100644 lib.esm/utils/index.js.map create mode 100644 lib.esm/utils/logger.js create mode 100644 lib.esm/utils/logger.js.map create mode 100644 lib.esm/utils/maths.js create mode 100644 lib.esm/utils/maths.js.map create mode 100644 lib.esm/utils/properties.js create mode 100644 lib.esm/utils/properties.js.map create mode 100644 lib.esm/utils/rlp-decode.js create mode 100644 lib.esm/utils/rlp-decode.js.map create mode 100644 lib.esm/utils/rlp-encode.js create mode 100644 lib.esm/utils/rlp-encode.js.map create mode 100644 lib.esm/utils/rlp.js create mode 100644 lib.esm/utils/rlp.js.map create mode 100644 lib.esm/utils/storage.js create mode 100644 lib.esm/utils/storage.js.map create mode 100644 lib.esm/utils/units.js create mode 100644 lib.esm/utils/units.js.map create mode 100644 lib.esm/utils/utf8.js create mode 100644 lib.esm/utils/utf8.js.map create mode 100644 lib.esm/wallet/base-wallet.js create mode 100644 lib.esm/wallet/base-wallet.js.map create mode 100644 lib.esm/wallet/hdwallet.js create mode 100644 lib.esm/wallet/hdwallet.js.map create mode 100644 lib.esm/wallet/index.js create mode 100644 lib.esm/wallet/index.js.map create mode 100644 lib.esm/wallet/json-crowdsale.js create mode 100644 lib.esm/wallet/json-crowdsale.js.map create mode 100644 lib.esm/wallet/json-keystore.js create mode 100644 lib.esm/wallet/json-keystore.js.map create mode 100644 lib.esm/wallet/mnemonic.js create mode 100644 lib.esm/wallet/mnemonic.js.map create mode 100644 lib.esm/wallet/utils.js create mode 100644 lib.esm/wallet/utils.js.map create mode 100644 lib.esm/wallet/wallet.js create mode 100644 lib.esm/wallet/wallet.js.map create mode 100644 lib.esm/wordlists/bit-reader.js create mode 100644 lib.esm/wordlists/bit-reader.js.map create mode 100644 lib.esm/wordlists/decode-owl.js create mode 100644 lib.esm/wordlists/decode-owl.js.map create mode 100644 lib.esm/wordlists/decode-owla.js create mode 100644 lib.esm/wordlists/decode-owla.js.map create mode 100644 lib.esm/wordlists/generation/encode-latin.js create mode 100644 lib.esm/wordlists/generation/encode-latin.js.map create mode 100644 lib.esm/wordlists/index.js create mode 100644 lib.esm/wordlists/index.js.map create mode 100644 lib.esm/wordlists/lang-cz.js create mode 100644 lib.esm/wordlists/lang-cz.js.map create mode 100644 lib.esm/wordlists/lang-en.js create mode 100644 lib.esm/wordlists/lang-en.js.map create mode 100644 lib.esm/wordlists/lang-es.js create mode 100644 lib.esm/wordlists/lang-es.js.map create mode 100644 lib.esm/wordlists/lang-fr.js create mode 100644 lib.esm/wordlists/lang-fr.js.map create mode 100644 lib.esm/wordlists/lang-it.js create mode 100644 lib.esm/wordlists/lang-it.js.map create mode 100644 lib.esm/wordlists/lang-ja.js create mode 100644 lib.esm/wordlists/lang-ja.js.map create mode 100644 lib.esm/wordlists/lang-ko.js create mode 100644 lib.esm/wordlists/lang-ko.js.map create mode 100644 lib.esm/wordlists/lang-pt.js create mode 100644 lib.esm/wordlists/lang-pt.js.map create mode 100644 lib.esm/wordlists/lang-zh.js create mode 100644 lib.esm/wordlists/lang-zh.js.map create mode 100644 lib.esm/wordlists/wordlist-owl.js create mode 100644 lib.esm/wordlists/wordlist-owl.js.map create mode 100644 lib.esm/wordlists/wordlist-owla.js create mode 100644 lib.esm/wordlists/wordlist-owla.js.map create mode 100644 lib.esm/wordlists/wordlist.js create mode 100644 lib.esm/wordlists/wordlist.js.map create mode 100644 lib.esm/wordlists/wordlists-browser.js create mode 100644 lib.esm/wordlists/wordlists-browser.js.map create mode 100644 lib.esm/wordlists/wordlists-extra.js create mode 100644 lib.esm/wordlists/wordlists-extra.js.map create mode 100644 lib.esm/wordlists/wordlists.js create mode 100644 lib.esm/wordlists/wordlists.js.map create mode 100644 types/_version.d.ts create mode 100644 types/_version.d.ts.map create mode 100644 types/abi/abi-coder.d.ts create mode 100644 types/abi/abi-coder.d.ts.map create mode 100644 types/abi/bytes32.d.ts create mode 100644 types/abi/bytes32.d.ts.map create mode 100644 types/abi/coders/abstract-coder.d.ts create mode 100644 types/abi/coders/abstract-coder.d.ts.map create mode 100644 types/abi/coders/address.d.ts create mode 100644 types/abi/coders/address.d.ts.map create mode 100644 types/abi/coders/anonymous.d.ts create mode 100644 types/abi/coders/anonymous.d.ts.map create mode 100644 types/abi/coders/array.d.ts create mode 100644 types/abi/coders/array.d.ts.map create mode 100644 types/abi/coders/boolean.d.ts create mode 100644 types/abi/coders/boolean.d.ts.map create mode 100644 types/abi/coders/bytes.d.ts create mode 100644 types/abi/coders/bytes.d.ts.map create mode 100644 types/abi/coders/fixed-bytes.d.ts create mode 100644 types/abi/coders/fixed-bytes.d.ts.map create mode 100644 types/abi/coders/null.d.ts create mode 100644 types/abi/coders/null.d.ts.map create mode 100644 types/abi/coders/number.d.ts create mode 100644 types/abi/coders/number.d.ts.map create mode 100644 types/abi/coders/string.d.ts create mode 100644 types/abi/coders/string.d.ts.map create mode 100644 types/abi/coders/tuple.d.ts create mode 100644 types/abi/coders/tuple.d.ts.map create mode 100644 types/abi/fragments.d.ts create mode 100644 types/abi/fragments.d.ts.map create mode 100644 types/abi/index.d.ts create mode 100644 types/abi/index.d.ts.map create mode 100644 types/abi/interface.d.ts create mode 100644 types/abi/interface.d.ts.map create mode 100644 types/abi/typed.d.ts create mode 100644 types/abi/typed.d.ts.map create mode 100644 types/address/address.d.ts create mode 100644 types/address/address.d.ts.map create mode 100644 types/address/checks.d.ts create mode 100644 types/address/checks.d.ts.map create mode 100644 types/address/contract-address.d.ts create mode 100644 types/address/contract-address.d.ts.map create mode 100644 types/address/index.d.ts create mode 100644 types/address/index.d.ts.map create mode 100644 types/constants/addresses.d.ts create mode 100644 types/constants/addresses.d.ts.map create mode 100644 types/constants/hashes.d.ts create mode 100644 types/constants/hashes.d.ts.map create mode 100644 types/constants/index.d.ts create mode 100644 types/constants/index.d.ts.map create mode 100644 types/constants/numbers.d.ts create mode 100644 types/constants/numbers.d.ts.map create mode 100644 types/constants/strings.d.ts create mode 100644 types/constants/strings.d.ts.map create mode 100644 types/contract/contract.d.ts create mode 100644 types/contract/contract.d.ts.map create mode 100644 types/contract/factory.d.ts create mode 100644 types/contract/factory.d.ts.map create mode 100644 types/contract/index.d.ts create mode 100644 types/contract/index.d.ts.map create mode 100644 types/contract/types.d.ts create mode 100644 types/contract/types.d.ts.map create mode 100644 types/contract/wrappers.d.ts create mode 100644 types/contract/wrappers.d.ts.map create mode 100644 types/crypto/crypto-browser.d.ts create mode 100644 types/crypto/crypto-browser.d.ts.map create mode 100644 types/crypto/crypto.d.ts create mode 100644 types/crypto/crypto.d.ts.map create mode 100644 types/crypto/hmac.d.ts create mode 100644 types/crypto/hmac.d.ts.map create mode 100644 types/crypto/index.d.ts create mode 100644 types/crypto/index.d.ts.map create mode 100644 types/crypto/keccak.d.ts create mode 100644 types/crypto/keccak.d.ts.map create mode 100644 types/crypto/pbkdf2.d.ts create mode 100644 types/crypto/pbkdf2.d.ts.map create mode 100644 types/crypto/random.d.ts create mode 100644 types/crypto/random.d.ts.map create mode 100644 types/crypto/ripemd160.d.ts create mode 100644 types/crypto/ripemd160.d.ts.map create mode 100644 types/crypto/scrypt.d.ts create mode 100644 types/crypto/scrypt.d.ts.map create mode 100644 types/crypto/sha2.d.ts create mode 100644 types/crypto/sha2.d.ts.map create mode 100644 types/crypto/signature.d.ts create mode 100644 types/crypto/signature.d.ts.map create mode 100644 types/crypto/signing-key.d.ts create mode 100644 types/crypto/signing-key.d.ts.map create mode 100644 types/ethers.d.ts create mode 100644 types/ethers.d.ts.map create mode 100644 types/hash/id.d.ts create mode 100644 types/hash/id.d.ts.map create mode 100644 types/hash/index.d.ts create mode 100644 types/hash/index.d.ts.map create mode 100644 types/hash/message.d.ts create mode 100644 types/hash/message.d.ts.map create mode 100644 types/hash/namehash.d.ts create mode 100644 types/hash/namehash.d.ts.map create mode 100644 types/hash/solidity.d.ts create mode 100644 types/hash/solidity.d.ts.map create mode 100644 types/hash/typed-data.d.ts create mode 100644 types/hash/typed-data.d.ts.map create mode 100644 types/index.d.ts create mode 100644 types/index.d.ts.map create mode 100644 types/providers/abstract-provider.d.ts create mode 100644 types/providers/abstract-provider.d.ts.map create mode 100644 types/providers/abstract-signer.d.ts create mode 100644 types/providers/abstract-signer.d.ts.map create mode 100644 types/providers/common-networks.d.ts create mode 100644 types/providers/common-networks.d.ts.map create mode 100644 types/providers/community.d.ts create mode 100644 types/providers/community.d.ts.map create mode 100644 types/providers/contracts.d.ts create mode 100644 types/providers/contracts.d.ts.map create mode 100644 types/providers/default-provider.d.ts create mode 100644 types/providers/default-provider.d.ts.map create mode 100644 types/providers/ens-resolver.d.ts create mode 100644 types/providers/ens-resolver.d.ts.map create mode 100644 types/providers/formatter.d.ts create mode 100644 types/providers/formatter.d.ts.map create mode 100644 types/providers/index.d.ts create mode 100644 types/providers/index.d.ts.map create mode 100644 types/providers/network.d.ts create mode 100644 types/providers/network.d.ts.map create mode 100644 types/providers/pagination.d.ts create mode 100644 types/providers/pagination.d.ts.map create mode 100644 types/providers/plugins-network.d.ts create mode 100644 types/providers/plugins-network.d.ts.map create mode 100644 types/providers/provider-alchemy.d.ts create mode 100644 types/providers/provider-alchemy.d.ts.map create mode 100644 types/providers/provider-ankr.d.ts create mode 100644 types/providers/provider-ankr.d.ts.map create mode 100644 types/providers/provider-cloudflare.d.ts create mode 100644 types/providers/provider-cloudflare.d.ts.map create mode 100644 types/providers/provider-etherscan.d.ts create mode 100644 types/providers/provider-etherscan.d.ts.map create mode 100644 types/providers/provider-fallback.d.ts create mode 100644 types/providers/provider-fallback.d.ts.map create mode 100644 types/providers/provider-infura.d.ts create mode 100644 types/providers/provider-infura.d.ts.map create mode 100644 types/providers/provider-ipcsocket-browser.d.ts create mode 100644 types/providers/provider-ipcsocket-browser.d.ts.map create mode 100644 types/providers/provider-ipcsocket.d.ts create mode 100644 types/providers/provider-ipcsocket.d.ts.map create mode 100644 types/providers/provider-jsonrpc.d.ts create mode 100644 types/providers/provider-jsonrpc.d.ts.map create mode 100644 types/providers/provider-pocket.d.ts create mode 100644 types/providers/provider-pocket.d.ts.map create mode 100644 types/providers/provider-socket.d.ts create mode 100644 types/providers/provider-socket.d.ts.map create mode 100644 types/providers/provider-websocket.d.ts create mode 100644 types/providers/provider-websocket.d.ts.map create mode 100644 types/providers/provider.d.ts create mode 100644 types/providers/provider.d.ts.map create mode 100644 types/providers/signer.d.ts create mode 100644 types/providers/signer.d.ts.map create mode 100644 types/providers/subscriber-connection.d.ts create mode 100644 types/providers/subscriber-connection.d.ts.map create mode 100644 types/providers/subscriber-filterid.d.ts create mode 100644 types/providers/subscriber-filterid.d.ts.map create mode 100644 types/providers/subscriber-hotswap.d.ts create mode 100644 types/providers/subscriber-hotswap.d.ts.map create mode 100644 types/providers/subscriber-polling.d.ts create mode 100644 types/providers/subscriber-polling.d.ts.map create mode 100644 types/providers/subscriber.d.ts create mode 100644 types/providers/subscriber.d.ts.map create mode 100644 types/providers/ws-browser.d.ts create mode 100644 types/providers/ws-browser.d.ts.map create mode 100644 types/providers/ws.d.ts create mode 100644 types/providers/ws.d.ts.map create mode 100644 types/transaction/accesslist.d.ts create mode 100644 types/transaction/accesslist.d.ts.map create mode 100644 types/transaction/address.d.ts create mode 100644 types/transaction/address.d.ts.map create mode 100644 types/transaction/index.d.ts create mode 100644 types/transaction/index.d.ts.map create mode 100644 types/transaction/transaction.d.ts create mode 100644 types/transaction/transaction.d.ts.map create mode 100644 types/utils/base58.d.ts create mode 100644 types/utils/base58.d.ts.map create mode 100644 types/utils/base64-browser.d.ts create mode 100644 types/utils/base64-browser.d.ts.map create mode 100644 types/utils/base64.d.ts create mode 100644 types/utils/base64.d.ts.map create mode 100644 types/utils/data.d.ts create mode 100644 types/utils/data.d.ts.map create mode 100644 types/utils/errors.d.ts create mode 100644 types/utils/errors.d.ts.map create mode 100644 types/utils/events.d.ts create mode 100644 types/utils/events.d.ts.map create mode 100644 types/utils/fetch.d.ts create mode 100644 types/utils/fetch.d.ts.map create mode 100644 types/utils/fixednumber.d.ts create mode 100644 types/utils/fixednumber.d.ts.map create mode 100644 types/utils/geturl-browser.d.ts create mode 100644 types/utils/geturl-browser.d.ts.map create mode 100644 types/utils/geturl.d.ts create mode 100644 types/utils/geturl.d.ts.map create mode 100644 types/utils/index.d.ts create mode 100644 types/utils/index.d.ts.map create mode 100644 types/utils/logger.d.ts create mode 100644 types/utils/logger.d.ts.map create mode 100644 types/utils/maths.d.ts create mode 100644 types/utils/maths.d.ts.map create mode 100644 types/utils/properties.d.ts create mode 100644 types/utils/properties.d.ts.map create mode 100644 types/utils/rlp-decode.d.ts create mode 100644 types/utils/rlp-decode.d.ts.map create mode 100644 types/utils/rlp-encode.d.ts create mode 100644 types/utils/rlp-encode.d.ts.map create mode 100644 types/utils/rlp.d.ts create mode 100644 types/utils/rlp.d.ts.map create mode 100644 types/utils/storage.d.ts create mode 100644 types/utils/storage.d.ts.map create mode 100644 types/utils/units.d.ts create mode 100644 types/utils/units.d.ts.map create mode 100644 types/utils/utf8.d.ts create mode 100644 types/utils/utf8.d.ts.map create mode 100644 types/wallet/base-wallet.d.ts create mode 100644 types/wallet/base-wallet.d.ts.map create mode 100644 types/wallet/hdwallet.d.ts create mode 100644 types/wallet/hdwallet.d.ts.map create mode 100644 types/wallet/index.d.ts create mode 100644 types/wallet/index.d.ts.map create mode 100644 types/wallet/json-crowdsale.d.ts create mode 100644 types/wallet/json-crowdsale.d.ts.map create mode 100644 types/wallet/json-keystore.d.ts create mode 100644 types/wallet/json-keystore.d.ts.map create mode 100644 types/wallet/mnemonic.d.ts create mode 100644 types/wallet/mnemonic.d.ts.map create mode 100644 types/wallet/utils.d.ts create mode 100644 types/wallet/utils.d.ts.map create mode 100644 types/wallet/wallet.d.ts create mode 100644 types/wallet/wallet.d.ts.map create mode 100644 types/wordlists/bit-reader.d.ts create mode 100644 types/wordlists/bit-reader.d.ts.map create mode 100644 types/wordlists/decode-owl.d.ts create mode 100644 types/wordlists/decode-owl.d.ts.map create mode 100644 types/wordlists/decode-owla.d.ts create mode 100644 types/wordlists/decode-owla.d.ts.map create mode 100644 types/wordlists/generation/encode-latin.d.ts create mode 100644 types/wordlists/generation/encode-latin.d.ts.map create mode 100644 types/wordlists/index.d.ts create mode 100644 types/wordlists/index.d.ts.map create mode 100644 types/wordlists/lang-cz.d.ts create mode 100644 types/wordlists/lang-cz.d.ts.map create mode 100644 types/wordlists/lang-en.d.ts create mode 100644 types/wordlists/lang-en.d.ts.map create mode 100644 types/wordlists/lang-es.d.ts create mode 100644 types/wordlists/lang-es.d.ts.map create mode 100644 types/wordlists/lang-fr.d.ts create mode 100644 types/wordlists/lang-fr.d.ts.map create mode 100644 types/wordlists/lang-it.d.ts create mode 100644 types/wordlists/lang-it.d.ts.map create mode 100644 types/wordlists/lang-ja.d.ts create mode 100644 types/wordlists/lang-ja.d.ts.map create mode 100644 types/wordlists/lang-ko.d.ts create mode 100644 types/wordlists/lang-ko.d.ts.map create mode 100644 types/wordlists/lang-pt.d.ts create mode 100644 types/wordlists/lang-pt.d.ts.map create mode 100644 types/wordlists/lang-zh.d.ts create mode 100644 types/wordlists/lang-zh.d.ts.map create mode 100644 types/wordlists/wordlist-owl.d.ts create mode 100644 types/wordlists/wordlist-owl.d.ts.map create mode 100644 types/wordlists/wordlist-owla.d.ts create mode 100644 types/wordlists/wordlist-owla.d.ts.map create mode 100644 types/wordlists/wordlist.d.ts create mode 100644 types/wordlists/wordlist.d.ts.map create mode 100644 types/wordlists/wordlists-browser.d.ts create mode 100644 types/wordlists/wordlists-browser.d.ts.map create mode 100644 types/wordlists/wordlists-extra.d.ts create mode 100644 types/wordlists/wordlists-extra.d.ts.map create mode 100644 types/wordlists/wordlists.d.ts create mode 100644 types/wordlists/wordlists.d.ts.map diff --git a/dist/ethers.js b/dist/ethers.js new file mode 100644 index 000000000..d3488e5ba --- /dev/null +++ b/dist/ethers.js @@ -0,0 +1,17096 @@ +const version = "6.0.0-beta-exports.0"; + +const LogLevels = ["debug", "info", "warning", "error", "off"]; +const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { + try { + // General test for normalize + /* c8 ignore start */ + if ("test".normalize(form) !== "test") { + throw new Error("bad"); + } + ; + /* c8 ignore stop */ + if (form === "NFD") { + const check = String.fromCharCode(0xe9).normalize("NFD"); + const expected = String.fromCharCode(0x65, 0x0301); + /* c8 ignore start */ + if (check !== expected) { + throw new Error("broken"); + } + /* c8 ignore stop */ + } + accum.push(form); + } + catch (error) { } + return accum; +}, []); +function defineReadOnly$1(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, writable: false, value, + }); +} +// IEEE 754 support 53-bits of mantissa +const maxValue = 0x1fffffffffffff; +// The type of error to use for various error codes +const ErrorConstructors = {}; +ErrorConstructors.INVALID_ARGUMENT = TypeError; +ErrorConstructors.NUMERIC_FAULT = RangeError; +ErrorConstructors.BUFFER_OVERRUN = RangeError; +class Logger { + version; + #logLevel; + constructor(version) { + defineReadOnly$1(this, "version", version || "_"); + this.#logLevel = 1; + } + get logLevel() { + return LogLevels[this.#logLevel]; + } + set logLevel(value) { + const logLevel = LogLevels.indexOf(value); + if (logLevel == null) { + this.throwArgumentError("invalid logLevel", "logLevel", value); + } + this.#logLevel = logLevel; + } + makeError(message, code, info) { + { + const details = []; + if (info) { + for (const key in info) { + const value = (info[key]); + try { + details.push(key + "=" + JSON.stringify(value)); + } + catch (error) { + details.push(key + "=[could not serialize object]"); + } + } + } + details.push(`code=${code}`); + details.push(`version=${this.version}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; + } + } + const create = ErrorConstructors[code] || Error; + const error = (new create(message)); + defineReadOnly$1(error, "code", code); + if (info) { + for (const key in info) { + defineReadOnly$1(error, key, (info[key])); + } + } + return error; + } + throwError(message, code, info) { + throw this.makeError(message, code, info); + } + throwArgumentError(message, name, value) { + return this.throwError(message, "INVALID_ARGUMENT", { + argument: name, + value: value + }); + } + assertNormalize(form) { + if (_normalizeForms.indexOf(form) === -1) { + this.throwError("platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", info: { form } + }); + } + } + assertPrivate(givenGuard, guard, className = "") { + if (givenGuard !== guard) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; + } + this.throwError(`private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation + }); + } + } + assertArgumentCount(count, expectedCount, message = "") { + if (message) { + message = ": " + message; + } + if (count < expectedCount) { + this.throwError("missing arguemnt" + message, "MISSING_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguemnts" + message, "UNEXPECTED_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + } + #getBytes(value, name, copy) { + if (value instanceof Uint8Array) { + if (copy) { + return new Uint8Array(value); + } + return value; + } + if (typeof (value) === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset = 2; + for (let i = 0; i < result.length; i++) { + result[i] = parseInt(value.substring(offset, offset + 2), 16); + offset += 2; + } + return result; + } + return this.throwArgumentError("invalid BytesLike value", name || "value", value); + } + getBytes(value, name) { + return this.#getBytes(value, name, false); + } + getBytesCopy(value, name) { + return this.#getBytes(value, name, true); + } + getNumber(value, name) { + switch (typeof (value)) { + case "bigint": + if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return Number(value); + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return value; + case "string": + try { + return this.getNumber(BigInt(value), name); + } + catch (e) { + this.throwArgumentError(`invalid numeric string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid numeric value", name || "value", value); + } + getBigInt(value, name) { + switch (typeof (value)) { + case "bigint": return value; + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return BigInt(value); + case "string": + try { + return BigInt(value); + } + catch (e) { + this.throwArgumentError(`invalid BigNumberish string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid BigNumberish value", name || "value", value); + } + #log(_logLevel, args) { + const logLevel = LogLevels.indexOf(_logLevel); + if (logLevel === -1) { + this.throwArgumentError("invalid log level name", "logLevel", _logLevel); + } + if (this.#logLevel > logLevel) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this.#log("debug", args); + } + info(...args) { + this.#log("info", args); + } + warn(...args) { + this.#log("warning", args); + } +} +const logger = new Logger(version); +function assertArgument(check, message, name, value) { + if (!check) { + logger.throwArgumentError(message, name, value); + } +} + +function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (typeof (length) === "number" && value.length !== 2 + 2 * length) { + return false; + } + if (length === true && (value.length % 2) !== 0) { + return false; + } + return true; +} +function isBytesLike(value) { + return (isHexString(value, true) || (value instanceof Uint8Array)); +} +const HexCharacters = "0123456789abcdef"; +function hexlify(data) { + const bytes = logger.getBytes(data); + let result = "0x"; + for (let i = 0; i < bytes.length; i++) { + const v = bytes[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; +} +function concat(datas) { + return "0x" + datas.map((d) => hexlify(d).substring(2)).join(""); +} +function dataLength(data) { + if (isHexString(data, true)) { + return (data.length - 2) / 2; + } + return logger.getBytes(data).length; +} +function dataSlice(data, start, end) { + const bytes = logger.getBytes(data); + if (end != null && end > bytes.length) { + logger.throwError("cannot slice beyond data bounds", "BUFFER_OVERRUN", { + buffer: bytes, length: bytes.length, offset: end + }); + } + return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end)); +} +function stripZerosLeft(data) { + let bytes = hexlify(data).substring(2); + while (bytes.substring(0, 2) == "00") { + bytes = bytes.substring(2); + } + return "0x" + bytes; +} +function zeroPad(data, length, left) { + const bytes = logger.getBytes(data); + if (length < bytes.length) { + logger.throwError("padding exceeds data length", "BUFFER_OVERRUN", { + buffer: new Uint8Array(bytes), + length: length, + offset: length + 1 + }); + } + const result = new Uint8Array(length); + result.fill(0); + if (left) { + result.set(bytes, length - bytes.length); + } + else { + result.set(bytes, 0); + } + return hexlify(result); +} +function zeroPadValue(data, length) { + return zeroPad(data, length, true); +} +function zeroPadBytes(data, length) { + return zeroPad(data, length, false); +} + +const BN_0$6 = BigInt(0); +const BN_1$5 = BigInt(1); +/** + * Convert %%value%% from a twos-compliment value of %%width%% bits. + */ +function fromTwos(_value, _width) { + const value = logger.getBigInt(_value, "value"); + const width = BigInt(logger.getNumber(_width, "width")); + // Top bit set; treat as a negative value + if (value >> (width - BN_1$5)) { + const mask = (BN_1$5 << width) - BN_1$5; + return -(((~value) & mask) + BN_1$5); + } + return value; +} +/** + * Convert %%value%% to a twos-compliment value of %%width%% bits. + */ +function toTwos(_value, _width) { + const value = logger.getBigInt(_value, "value"); + const width = BigInt(logger.getNumber(_width, "width")); + if (value < BN_0$6) { + const mask = (BN_1$5 << width) - BN_1$5; + return ((~(-value)) & mask) + BN_1$5; + } + return value; +} +/** + * Mask %%value%% with a bitmask of %%bits%% ones. + */ +function mask(_value, _bits) { + const value = logger.getBigInt(_value, "value"); + const bits = BigInt(logger.getNumber(_bits, "bits")); + return value & ((BN_1$5 << bits) - BN_1$5); +} +/* + * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. + */ +const Nibbles$1 = "0123456789abcdef"; +function toBigInt(value) { + if (value instanceof Uint8Array) { + let result = "0x0"; + for (const v of value) { + result += Nibbles$1[v >> 4]; + result += Nibbles$1[v & 0x0f]; + } + return BigInt(result); + } + return logger.getBigInt(value); +} +/* + * Converts %%value%% to a number. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. Throws if the value is not safe. + */ +function toNumber(value) { + return logger.getNumber(toBigInt(value)); +} +/** + * Converts %%value%% to a Big Endian hexstring, optionally padded to + * %%width%% bytes. + */ +// Converts value to hex, optionally padding on the left to width bytes +function toHex(_value, _width) { + const value = logger.getBigInt(_value, "value"); + if (value < 0) { + throw new Error("cannot convert negative value to hex"); + } + let result = value.toString(16); + if (_width == null) { + // Ensure the value is of even length + if (result.length % 2) { + result = "0" + result; + } + } + else { + const width = logger.getNumber(_width, "width"); + if (width * 2 < result.length) { + throw new Error(`value ${value} exceeds width ${width}`); + } + // Pad the value to the required width + while (result.length < (width * 2)) { + result = "0" + result; + } + } + return "0x" + result; +} +/** + * Converts %%value%% to a Big Endian Uint8Array. + */ +function toArray(_value) { + const value = logger.getBigInt(_value, "value"); + if (value < 0) { + throw new Error("cannot convert negative value to hex"); + } + if (value === BN_0$6) { + return new Uint8Array([]); + } + let hex = value.toString(16); + if (hex.length % 2) { + hex = "0" + hex; + } + const result = new Uint8Array(hex.length / 2); + for (let i = 0; i < result.length; i++) { + const offset = i * 2; + result[i] = parseInt(hex.substring(offset, offset + 2), 16); + } + return result; +} +function toQuantity(value) { + let result = hexlify(isBytesLike(value) ? value : toArray(value)).substring(2); + while (result.substring(0, 1) === "0") { + result = result.substring(1); + } + if (result === "") { + result = "0"; + } + return "0x" + result; +} + +async function resolveProperties(value) { + const keys = Object.keys(value); + const results = await Promise.all(keys.map((k) => Promise.resolve(value[k]))); + return results.reduce((accum, v, index) => { + accum[keys[index]] = v; + return accum; + }, {}); +} +function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + value: value, + writable: false, + }); +} +/* +export interface CancellablePromise extends Promise { + cancel(): Promise; +} +export type IsCancelled = () => Promise; + +export function createPromise(resolve: (isCancelled: IsCancelled, (result: T) => void) => void, reject: (error: Error) => void, isCancelled: IsCancelled): CancellablePromise { + let cancelled = false; + + const promise = new Promise((resolve, reject) => { + + }); + + (>promise).cancel = function() { + cancelled = true; + }; + + return (>promise); +} +*/ +/* +export class A implements Freezable { + foo: number; + constructor(foo: number) { + this.foo = foo; + } + freeze(): Frozen { + Object.freeze(this); + return this; + } + clone(): A { + return new A(this.foo); + } +} + +export class B implements Freezable { + a: A; + constructor(a: A) { + this.a = a; + } + freeze(): Frozen { + this.a.freeze(); + Object.freeze(this); + return this; + } + clone(): B { + return new B(this.a); + } +} + +export function test() { + const a = new A(123); + const b = new B(a); + b.a = new A(234); + const b2 = b.freeze(); + b2.a.foo = 123; // = a; +} +*/ +function checkType(value, type) { + const types = type.split("|").map(t => t.trim()); + for (let i = 0; i < types.length; i++) { + switch (type) { + case "any": + return; + case "boolean": + case "number": + case "string": + if (typeof (value) === type) { + return; + } + } + } + throw new Error("invalid value for type"); +} +function defineProperties(target, values, types, defaults) { + for (let key in values) { + let value = values[key]; + const fallback = (defaults ? defaults[key] : undefined); + if (fallback !== undefined) { + value = fallback; + } + else { + const type = (types ? types[key] : null); + if (type) { + checkType(value, type); + } + } + Object.defineProperty(target, key, { enumerable: true, value, writable: false }); + } +} + +const WordSize = 32; +const Padding = new Uint8Array(WordSize); +// Properties used to immediate pass through to the underlying object +// - `then` is used to detect if an object is a Promise for await +const passProperties$1 = ["then"]; +const _guard$4 = {}; +class Result extends Array { + #indices; + constructor(guard, items, keys) { + logger.assertPrivate(guard, _guard$4, "Result"); + super(...items); + // Name lookup table + this.#indices = new Map(); + if (keys) { + keys.forEach((key, index) => { + if (key == null) { + return; + } + if (this.#indices.has(key)) { + (this.#indices.get(key)).push(index); + } + else { + this.#indices.set(key, [index]); + } + }); + } + Object.freeze(this); + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "string") { + if (prop.match(/^[0-9]+$/)) { + const index = logger.getNumber(prop, "%index"); + if (index < 0 || index >= this.length) { + throw new RangeError("out of result range"); + } + const item = target[index]; + if (item instanceof Error) { + this.#throwError(`index ${index}`, item); + } + return item; + } + // Pass important checks (like `then` for Promise) through + if (prop in target || passProperties$1.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + // Something that could be a result keyword value + if (!(prop in target)) { + return target.getValue(prop); + } + } + return Reflect.get(target, prop, receiver); + } + }); + } + /* + toJSON(): any { + if (this.#indices.length === this.length) { + const result: Record = { }; + for (const key of this.#indices.keys()) { + result[key] = ths.getValue(key); + } + return result; + } + return this; + } + */ + slice(start, end) { + if (start == null) { + start = 0; + } + if (end == null) { + end = this.length; + } + const result = []; + for (let i = start; i < end; i++) { + let value; + try { + value = this[i]; + } + catch (error) { + value = error.error; + } + result.push(value); + } + return result; + } + #throwError(name, error) { + const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); + wrapped.error = error; + throw wrapped; + } + getValue(name) { + const index = this.#indices.get(name); + if (index != null && index.length === 1) { + const item = this[index[0]]; + if (item instanceof Error) { + this.#throwError(`property ${JSON.stringify(name)}`, item); + } + return item; + } + throw new Error(`no named parameter: ${JSON.stringify(name)}`); + } + static fromItems(items, keys) { + return new Result(_guard$4, items, keys); + } +} +function checkResultErrors(result) { + // Find the first error (if any) + const errors = []; + const checkErrors = function (path, object) { + if (!Array.isArray(object)) { + return; + } + for (let key in object) { + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object[key]); + } + catch (error) { + errors.push({ path: childPath, error: error }); + } + } + }; + checkErrors([], result); + return errors; +} +function getValue$1(value) { + let bytes = toArray(value); + if (bytes.length > WordSize) { + logger.throwError("value out-of-bounds", "BUFFER_OVERRUN", { + buffer: bytes, + length: WordSize, + offset: bytes.length + }); + } + if (bytes.length !== WordSize) { + bytes = logger.getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes])); + } + return bytes; +} +class Coder { + // The coder name: + // - address, uint256, tuple, array, etc. + name; + // The fully expanded type, including composite types: + // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. + type; + // The localName bound in the signature, in this example it is "baz": + // - tuple(address foo, uint bar) baz + localName; + // Whether this type is dynamic: + // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. + // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) + dynamic; + constructor(name, type, localName, dynamic) { + defineProperties(this, { name, type, localName, dynamic }, { + name: "string", type: "string", localName: "string", dynamic: "boolean" + }); + } + _throwError(message, value) { + return logger.throwArgumentError(message, this.localName, value); + } +} +class Writer { + // An array of WordSize lengthed objects to concatenation + #data; + #dataLength; + constructor() { + this.#data = []; + this.#dataLength = 0; + } + get data() { + return concat(this.#data); + } + get length() { return this.#dataLength; } + #writeData(data) { + this.#data.push(data); + this.#dataLength += data.length; + return data.length; + } + appendWriter(writer) { + return this.#writeData(logger.getBytesCopy(writer.data)); + } + // Arrayish item; pad on the right to *nearest* WordSize + writeBytes(value) { + let bytes = logger.getBytesCopy(value); + const paddingOffset = bytes.length % WordSize; + if (paddingOffset) { + bytes = logger.getBytesCopy(concat([bytes, Padding.slice(paddingOffset)])); + } + return this.#writeData(bytes); + } + // Numeric item; pad on the left *to* WordSize + writeValue(value) { + return this.#writeData(getValue$1(value)); + } + // Inserts a numeric place-holder, returning a callback that can + // be used to asjust the value later + writeUpdatableValue() { + const offset = this.#data.length; + this.#data.push(Padding); + this.#dataLength += WordSize; + return (value) => { + this.#data[offset] = getValue$1(value); + }; + } +} +class Reader { + // Allows incomplete unpadded data to be read; otherwise an error + // is raised if attempting to overrun the buffer. This is required + // to deal with an old Solidity bug, in which event data for + // external (not public thoguh) was tightly packed. + allowLoose; + #data; + #offset; + constructor(data, allowLoose) { + defineProperties(this, { allowLoose: !!allowLoose }); + this.#data = logger.getBytesCopy(data); + this.#offset = 0; + } + get data() { return hexlify(this.#data); } + get dataLength() { return this.#data.length; } + get consumed() { return this.#offset; } + get bytes() { return new Uint8Array(this.#data); } + #peekBytes(offset, length, loose) { + let alignedLength = Math.ceil(length / WordSize) * WordSize; + if (this.#offset + alignedLength > this.#data.length) { + if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { + alignedLength = length; + } + else { + logger.throwError("data out-of-bounds", "BUFFER_OVERRUN", { + buffer: logger.getBytesCopy(this.#data), + length: this.#data.length, + offset: this.#offset + alignedLength + }); + } + } + return this.#data.slice(this.#offset, this.#offset + alignedLength); + } + // Create a sub-reader with the same underlying data, but offset + subReader(offset) { + return new Reader(this.#data.slice(this.#offset + offset), this.allowLoose); + } + // Read bytes + readBytes(length, loose) { + let bytes = this.#peekBytes(0, length, !!loose); + this.#offset += bytes.length; + // @TODO: Make sure the length..end bytes are all 0? + return bytes.slice(0, length); + } + // Read a numeric values + readValue() { + return toBigInt(this.readBytes(WordSize)); + } + readIndex() { + return toNumber(this.readBytes(WordSize)); + } +} + +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new TypeError('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; + +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h, l) => l; +const rotr32L = (h, l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; + +const crypto$2 = { + node: undefined, + web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined, +}; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// Cast array to different type +const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// There is almost no big endian hardware, but js typed arrays uses platform specific endianness. +// So, just to be sure not to corrupt anything. +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +const hexes$1 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +/** + * @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) + */ +function bytesToHex$1(uint8a) { + // pre-caching improves the speed 6x + if (!(uint8a instanceof Uint8Array)) + throw new Error('Uint8Array expected'); + let hex = ''; + for (let i = 0; i < uint8a.length; i++) { + hex += hexes$1[uint8a[i]]; + } + return hex; +} +/** + * @example hexToBytes('deadbeef') + */ +function hexToBytes$1(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + typeof hex); + } + if (hex.length % 2) + throw new Error('hexToBytes: received invalid unpadded hex'); + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +// There is no setImmediate in browser and setTimeout is slow. However, call to async function will return Promise +// which will be fullfiled only on next scheduler queue processing step and this is exactly what we need. +const nextTick = async () => { }; +// Returns control to thread each 'tick' ms to avoid blocking +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +function utf8ToBytes(str) { + if (typeof str !== 'string') { + throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); + } + return new TextEncoder().encode(str); +} +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!(data instanceof Uint8Array)) + throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); + return data; +} +/** + * Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])` + * @example concatBytes(buf1, buf2) + */ +function concatBytes$1(...arrays) { + if (!arrays.every((a) => a instanceof Uint8Array)) + throw new Error('Uint8Array list expected'); + if (arrays.length === 1) + return arrays[0]; + const length = arrays.reduce((a, arr) => a + arr.length, 0); + const result = new Uint8Array(length); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } + return result; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +// Check if object doens't have custom constructor (like Uint8Array/Array) +const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; +function checkOpts(defaults, opts) { + if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) + throw new TypeError('Options should be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +function wrapConstructor(hashConstructor) { + const hashC = (message) => hashConstructor().update(toBytes(message)).digest(); + const tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashConstructor(); + return hashC; +} +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +/** + * Secure PRNG + */ +function randomBytes$2(bytesLength = 32) { + if (crypto$2.web) { + return crypto$2.web.getRandomValues(new Uint8Array(bytesLength)); + } + else if (crypto$2.node) { + return new Uint8Array(crypto$2.node.randomBytes(bytesLength).buffer); + } + else { + throw new Error("The environment doesn't have randomBytes function"); + } +} + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n$1 = BigInt(0); +const _1n$1 = BigInt(1); +const _2n$1 = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n$1, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n$1; + for (let j = 0; j < 7; j++) { + R = ((R << _1n$1) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n$1) + t ^= _1n$1 << ((_1n$1 << BigInt(j)) - _1n$1); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = u64.split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => s > 32 ? u64.rotlBH(h, l, s) : u64.rotlSH(h, l, s); +const rotlL = (h, l, s) => s > 32 ? u64.rotlBL(h, l, s) : u64.rotlSL(h, l, s); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + assert.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + assert.exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + assert.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +const sha3_224 = gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +const sha3_256 = gen(0x06, 136, 256 / 8); +const sha3_384 = gen(0x06, 104, 384 / 8); +const sha3_512 = gen(0x06, 72, 512 / 8); +const keccak_224 = gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +const keccak_256 = gen(0x01, 136, 256 / 8); +const keccak_384 = gen(0x01, 104, 384 / 8); +const keccak_512 = gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +const shake128 = genShake(0x1f, 168, 128 / 8); +const shake256 = genShake(0x1f, 136, 256 / 8); + +const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +let Lookup = null; +function getAlpha(letter) { + if (Lookup == null) { + Lookup = {}; + for (let i = 0; i < Alphabet.length; i++) { + Lookup[Alphabet[i]] = BigInt(i); + } + } + const result = Lookup[letter]; + if (result == null) { + logger.throwArgumentError(`invalid base58 value`, "letter", letter); + } + return result; +} +const BN_0$5 = BigInt(0); +const BN_58 = BigInt(58); +/** + * Encode %%value%% as Base58-encoded data. + */ +function encodeBase58(_value) { + let value = toBigInt(logger.getBytes(_value)); + let result = ""; + while (value) { + result = Alphabet[Number(value % BN_58)] + result; + value /= BN_58; + } + return result; +} +/** + * Decode the Base58-encoded %%value%%. + */ +function decodeBase58(value) { + let result = BN_0$5; + for (let i = 0; i < value.length; i++) { + result *= BN_58; + result += getAlpha(value[i]); + } + return toHex(result); +} + +// utils/base64-browser +function decodeBase64(textData) { + textData = atob(textData); + const data = new Uint8Array(textData.length); + for (let i = 0; i < textData.length; i++) { + data[i] = textData.charCodeAt(i); + } + return logger.getBytes(data); +} +function encodeBase64(_data) { + const data = logger.getBytes(_data); + let textData = ""; + for (let i = 0; i < data.length; i++) { + textData += String.fromCharCode(data[i]); + } + return btoa(textData); +} + +//export type TransactionReceipt { +//} +/** + * try { + * // code.... + * } catch (e) { + * if (isError(e, errors.CALL_EXCEPTION)) { + * console.log(e.data); + * } + * } + */ +function isError(error, code) { + return (error && error.code === code); +} +function isCallException(error) { + return isError(error, "CALL_EXCEPTION"); +} + +class EventPayload { + filter; + emitter; + #listener; + constructor(emitter, listener, filter) { + this.#listener = listener; + defineProperties(this, { emitter, filter }); + } + async removeListener() { + if (this.#listener == null) { + return; + } + await this.emitter.off(this.filter, this.#listener); + } +} + +function errorFunc(reason, offset, bytes, output, badCodepoint) { + return logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === "OVERRUN") { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === "OVERLONG") { + output.push((badCodepoint != null) ? badCodepoint : -1); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes, output, badCodepoint); +} +// Common error handing strategies +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + const bytes = logger.getBytes(_bytes, "bytes"); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result); + } + else { + i += onError("BAD_PREFIX", i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError("OVERRUN", i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError("MISSING_CONTINUE", i, bytes, result); + res = null; + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +function toUtf8Bytes(str, form) { + if (form != null) { + logger.assertNormalize(form); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return new Uint8Array(result); +} +; +function escapeChar(value) { + const hex = ("0000" + value.toString(16)); + return "\\u" + hex.substring(hex.length - 4); +} +function _toEscapedUtf8String(bytes, onError) { + return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => { + if (codePoint < 256) { + switch (codePoint) { + case 8: return "\\b"; + case 9: return "\\t"; + case 10: return "\\n"; + case 13: return "\\r"; + case 34: return "\\\""; + case 92: return "\\\\"; + } + if (codePoint >= 32 && codePoint < 127) { + return String.fromCharCode(codePoint); + } + } + if (codePoint <= 0xffff) { + return escapeChar(codePoint); + } + codePoint -= 0x10000; + return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00); + }).join("") + '"'; +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +function toUtf8CodePoints(str, form) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} + +// @TODO: timeout is completely ignored; start a Promise.any with a reject? +async function getUrl(req, _signal) { + const protocol = req.url.split(":")[0].toLowerCase(); + if (protocol !== "http" && protocol !== "https") { + logger.throwError(`unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" + }); + } + if (req.credentials && !req.allowInsecureAuthentication) { + logger.throwError("insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + } + let signal = undefined; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { controller.abort(); }); + } + const init = { + method: req.method, + headers: new Headers(Array.from(req)), + body: req.body || undefined, + signal + }; + const resp = await fetch(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = await resp.arrayBuffer(); + const body = (respBody == null) ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, body + }; +} + +const MAX_ATTEMPTS = 12; +const SLOT_INTERVAL = 250; +// The global FetchGetUrlFunc implementation. +let getUrlFunc = getUrl; +const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); +const reIpfs = new RegExp("^ipfs:/\/(ipfs/)?(.*)$", "i"); +// If locked, new Gateways cannot be added +let locked$5 = false; +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs +async function gatewayData(url, signal) { + try { + const match = url.match(reData); + if (!match) { + throw new Error("invalid data"); + } + return new FetchResponse(200, "OK", { + "content-type": (match[1] || "text/plain"), + }, (match[1] ? decodeBase64(match[3]) : unpercent(match[3]))); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); + } +} +function getIpfsGatewayFunc(base) { + async function gatewayIpfs(url, signal) { + try { + const match = url.match(reIpfs); + if (!match) { + throw new Error("invalid link"); + } + return new FetchRequest(`${base}${match[2]}`); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); + } + } + return gatewayIpfs; +} +const Gateways = { + "data": gatewayData, + "ipfs": getIpfsGatewayFunc("https:/\/gateway.ipfs.io/ipfs/") +}; +const fetchSignals = new WeakMap(); +class FetchCancelSignal { + #listeners; + #cancelled; + constructor(request) { + this.#listeners = []; + this.#cancelled = false; + fetchSignals.set(request, () => { + if (this.#cancelled) { + return; + } + this.#cancelled = true; + for (const listener of this.#listeners) { + setTimeout(() => { listener(); }, 0); + } + this.#listeners = []; + }); + } + addListener(listener) { + if (this.#cancelled) { + logger.throwError("singal already cancelled", "UNSUPPORTED_OPERATION", { + operation: "fetchCancelSignal.addCancelListener" + }); + } + this.#listeners.push(listener); + } + get cancelled() { return this.cancelled; } + checkSignal() { + if (!this.cancelled) { + return; + } + logger.throwError("cancelled", "CANCELLED", {}); + } +} +// Check the signal, throwing if it is cancelled +function checkSignal(signal) { + if (signal == null) { + throw new Error("missing signal; should not happen"); + } + signal.checkSignal(); + return signal; +} +class FetchRequest { + #allowInsecure; + #gzip; + #headers; + #method; + #timeout; + #url; + #body; + #bodyType; + #creds; + // Hooks + #preflight; + #process; + #retry; + #signal; + // URL + get url() { return this.#url; } + set url(url) { + this.#url = String(url); + } + // Body + get body() { + if (this.#body == null) { + return null; + } + return new Uint8Array(this.#body); + } + set body(body) { + if (body == null) { + this.#body = undefined; + this.#bodyType = undefined; + } + else if (typeof (body) === "string") { + this.#body = toUtf8Bytes(body); + this.#bodyType = "text/plain"; + } + else if (body instanceof Uint8Array) { + this.#body = body; + this.#bodyType = "application/octet-stream"; + } + else if (typeof (body) === "object") { + this.#body = toUtf8Bytes(JSON.stringify(body)); + this.#bodyType = "application/json"; + } + else { + throw new Error("invalid body"); + } + } + hasBody() { + return (this.#body != null); + } + // Method (default: GET with no body, POST with a body) + get method() { + if (this.#method) { + return this.#method; + } + if (this.hasBody()) { + return "POST"; + } + return "GET"; + } + set method(method) { + if (method == null) { + method = ""; + } + this.#method = String(method).toUpperCase(); + } + // Headers (automatically fills content-type if not explicitly set) + get headers() { + const headers = Object.assign({}, this.#headers); + if (this.#creds) { + headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`; + } + ; + if (this.allowGzip) { + headers["accept-encoding"] = "gzip"; + } + if (headers["content-type"] == null && this.#bodyType) { + headers["content-type"] = this.#bodyType; + } + if (this.body) { + headers["content-length"] = String(this.body.length); + } + return Object.freeze(headers); + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + setHeader(key, value) { + this.#headers[String(key).toLowerCase()] = String(value); + } + clearHeaders() { + this.#headers = {}; + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + // Configure an Authorization header + get credentials() { + return this.#creds || null; + } + setCredentials(username, password) { + if (username.match(/:/)) { + logger.throwArgumentError("invalid basic authentication username", "username", "[REDACTED]"); + } + this.#creds = `${username}:${password}`; + } + // Configure the request to allow gzipped responses + get allowGzip() { + return this.#gzip; + } + set allowGzip(value) { + this.#gzip = !!value; + } + // Allow credentials to be sent over an insecure (non-HTTPS) channel + get allowInsecureAuthentication() { + return !!this.#allowInsecure; + } + set allowInsecureAuthentication(value) { + this.#allowInsecure = !!value; + } + // Timeout (milliseconds) + get timeout() { return this.#timeout; } + set timeout(timeout) { + assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout); + this.#timeout = timeout; + } + // Preflight called before each request is sent + get preflightFunc() { + return this.#preflight || null; + } + set preflightFunc(preflight) { + this.#preflight = preflight; + } + // Preflight called before each request is sent + get processFunc() { + return this.#process || null; + } + set processFunc(process) { + this.#process = process; + } + // Preflight called before each request is sent + get retryFunc() { + return this.#retry || null; + } + set retryFunc(retry) { + this.#retry = retry; + } + constructor(url) { + this.#url = String(url); + this.#allowInsecure = false; + this.#gzip = false; + this.#headers = {}; + this.#method = ""; + this.#timeout = 300; + } + async #send(attempt, expires, delay, _request, _response) { + if (attempt >= MAX_ATTEMPTS) { + return _response.makeServerError("exceeded maximum retry limit"); + } + if (getTime$2() > expires) { + return logger.throwError("timeout", "TIMEOUT", { + operation: "request.send", reason: "timeout", request: _request + }); + } + if (delay > 0) { + await wait(delay); + } + let req = this.clone(); + const scheme = (req.url.split(":")[0] || "").toLowerCase(); + // Process any Gateways + if (scheme in Gateways) { + const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); + if (result instanceof FetchResponse) { + let response = result; + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Ignore throttling + } + } + return response; + } + req = result; + } + // We have a preflight function; update the request + if (this.preflightFunc) { + req = await this.preflightFunc(req); + } + const resp = await getUrlFunc(req, checkSignal(_request.#signal)); + let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); + if (response.statusCode === 301 || response.statusCode === 302) { + // Redirect + try { + const location = response.headers.location || ""; + return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); + } + catch (error) { } + // Things won't get any better on another attempt; abort + return response; + } + else if (response.statusCode === 429) { + // Throttle + if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) { + const retryAfter = response.headers["retry-after"]; + let delay = SLOT_INTERVAL * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + delay = parseInt(retryAfter); + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Throttle + let delay = SLOT_INTERVAL * Math.trunc(Math.random() * Math.pow(2, attempt)); + ; + if (error.stall >= 0) { + delay = error.stall; + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + return response; + } + send() { + if (this.#signal != null) { + return logger.throwError("request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); + } + this.#signal = new FetchCancelSignal(this); + return this.#send(0, getTime$2() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + } + cancel() { + if (this.#signal == null) { + return logger.throwError("request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); + } + const signal = fetchSignals.get(this); + if (!signal) { + throw new Error("missing signal; should not happen"); + } + signal(); + } + /** + * Returns a new [[FetchRequest]] that represents the redirection + * to %%location%%. + */ + redirect(location) { + // Redirection; for now we only support absolute locataions + const current = this.url.split(":")[0].toLowerCase(); + const target = location.split(":")[0].toLowerCase(); + // Don't allow redirecting: + // - non-GET requests + // - downgrading the security (e.g. https => http) + // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?] + if (this.method !== "GET" || (current === "https" && target === "http") || !location.match(/^https?:/)) { + return logger.throwError(`unsupported redirect`, "UNSUPPORTED_OPERATION", { + operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})` + }); + } + // Create a copy of this request, with a new URL + const req = new FetchRequest(location); + req.method = "GET"; + req.allowGzip = this.allowGzip; + req.timeout = this.timeout; + req.#headers = Object.assign({}, this.#headers); + if (this.#body) { + req.#body = new Uint8Array(this.#body); + } + req.#bodyType = this.#bodyType; + // Do not forward credentials unless on the same domain; only absolute + //req.allowInsecure = false; + // paths are currently supported; may want a way to specify to forward? + //setStore(req.#props, "creds", getStore(this.#pros, "creds")); + return req; + } + clone() { + const clone = new FetchRequest(this.url); + // Preserve "default method" (i.e. null) + clone.#method = this.#method; + // Preserve "default body" with type, copying the Uint8Array is present + if (this.#body) { + clone.#body = this.#body; + } + clone.#bodyType = this.#bodyType; + // Preserve "default headers" + clone.#headers = Object.assign({}, this.#headers); + // Credentials is readonly, so we copy internally + clone.#creds = this.#creds; + if (this.allowGzip) { + clone.allowGzip = true; + } + clone.timeout = this.timeout; + if (this.allowInsecureAuthentication) { + clone.allowInsecureAuthentication = true; + } + clone.#preflight = this.#preflight; + clone.#process = this.#process; + clone.#retry = this.#retry; + return clone; + } + static lockConfig() { + locked$5 = true; + } + static getGateway(scheme) { + return Gateways[scheme.toLowerCase()] || null; + } + static registerGateway(scheme, func) { + scheme = scheme.toLowerCase(); + if (scheme === "http" || scheme === "https") { + throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); + } + if (locked$5) { + throw new Error("gateways locked"); + } + Gateways[scheme] = func; + } + static registerGetUrl(getUrl) { + if (locked$5) { + throw new Error("gateways locked"); + } + getUrlFunc = getUrl; + } +} +; +class FetchResponse { + #statusCode; + #statusMessage; + #headers; + #body; + #request; + #error; + toString() { + return ``; + } + get statusCode() { return this.#statusCode; } + get statusMessage() { return this.#statusMessage; } + get headers() { return this.#headers; } + get body() { + return (this.#body == null) ? null : new Uint8Array(this.#body); + } + get bodyText() { + try { + return (this.#body == null) ? "" : toUtf8String(this.#body); + } + catch (error) { + return logger.throwError("response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { + operation: "bodyText", info: { response: this } + }); + } + } + get bodyJson() { + try { + return JSON.parse(this.bodyText); + } + catch (error) { + return logger.throwError("response body is not valid JSON", "UNSUPPORTED_OPERATION", { + operation: "bodyJson", info: { response: this } + }); + } + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + constructor(statusCode, statusMessage, headers, body, request) { + this.#statusCode = statusCode; + this.#statusMessage = statusMessage; + this.#headers = Object.freeze(Object.assign({}, Object.keys(headers).reduce((accum, k) => { + accum[k.toLowerCase()] = String(headers[k]); + return accum; + }, {}))); + this.#body = ((body == null) ? null : new Uint8Array(body)); + this.#request = (request || null); + this.#error = { message: "" }; + } + makeServerError(message, error) { + let statusMessage; + if (!message) { + message = `${this.statusCode} ${this.statusMessage}`; + statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; + } + else { + statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; + } + const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); + response.#error = { message, error }; + return response; + } + throwThrottleError(message, stall) { + if (stall == null) { + stall = -1; + } + else if (typeof (stall) !== "number" || !Number.isInteger(stall) || stall < 0) { + return logger.throwArgumentError("invalid stall timeout", "stall", stall); + } + const error = new Error(message || "throttling requests"); + defineProperties(error, { stall, throttle: true }); + throw error; + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + hasBody() { + return (this.#body != null); + } + get request() { return this.#request; } + ok() { + return (this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300); + } + assertOk() { + if (this.ok()) { + return; + } + let { message, error } = this.#error; + if (message === "") { + message = `server response ${this.statusCode} ${this.statusMessage}`; + } + logger.throwError(message, "SERVER_ERROR", { + request: (this.request || "unknown request"), response: this, error + }); + } +} +function getTime$2() { return (new Date()).getTime(); } +function unpercent(value) { + return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => { + return String.fromCharCode(parseInt(code, 16)); + })); +} +function wait(delay) { + return new Promise((resolve) => setTimeout(resolve, delay)); +} + +const _constructorGuard = {}; +const NegativeOne$1 = BigInt(-1); +function throwFault(message, fault, operation, value) { + const params = { fault: fault, operation: operation }; + if (value !== undefined) { + params.value = value; + } + return logger.throwError(message, "NUMERIC_FAULT", params); +} +// Constant to pull zeros from for multipliers +let zeros$1 = "0"; +while (zeros$1.length < 256) { + zeros$1 += zeros$1; +} +// Returns a string "1" followed by decimal "0"s +function getMultiplier(decimals) { + if (typeof (decimals) !== "number" || decimals < 0 || decimals > 256 || decimals % 1) { + logger.throwArgumentError("invalid decimal length", "decimals", decimals); + } + return BigInt("1" + zeros$1.substring(0, decimals)); +} +function formatFixed(_value, _decimals) { + if (_decimals == null) { + _decimals = 18; + } + let value = logger.getBigInt(_value, "value"); + const decimals = logger.getNumber(_decimals, "decimals"); + const multiplier = getMultiplier(decimals); + const multiplierStr = String(multiplier); + const negative = (value < 0); + if (negative) { + value *= NegativeOne$1; + } + let fraction = String(value % multiplier); + // Make sure there are enough place-holders + while (fraction.length < multiplierStr.length - 1) { + fraction = "0" + fraction; + } + // Strip training 0 + while (fraction.length > 1 && fraction.substring(fraction.length - 1) === "0") { + fraction = fraction.substring(0, fraction.length - 1); + } + let result = String(value / multiplier); + if (multiplierStr.length !== 1) { + result += "." + fraction; + } + if (negative) { + result = "-" + result; + } + return result; +} +function parseFixed(value, _decimals) { + if (_decimals == null) { + _decimals = 18; + } + const decimals = logger.getNumber(_decimals, "decimals"); + const multiplier = getMultiplier(decimals); + if (typeof (value) !== "string" || !value.match(/^-?[0-9.]+$/)) { + logger.throwArgumentError("invalid decimal value", "value", value); + } + // Is it negative? + const negative = (value.substring(0, 1) === "-"); + if (negative) { + value = value.substring(1); + } + if (value === ".") { + logger.throwArgumentError("missing value", "value", value); + } + // Split it into a whole and fractional part + const comps = value.split("."); + if (comps.length > 2) { + logger.throwArgumentError("too many decimal points", "value", value); + } + let whole = (comps[0] || "0"), fraction = (comps[1] || "0"); + // Trim trialing zeros + while (fraction[fraction.length - 1] === "0") { + fraction = fraction.substring(0, fraction.length - 1); + } + // Check the fraction doesn't exceed our decimals size + if (fraction.length > String(multiplier).length - 1) { + throwFault("fractional component exceeds decimals", "underflow", "parseFixed"); + } + // If decimals is 0, we have an empty string for fraction + if (fraction === "") { + fraction = "0"; + } + // Fully pad the string with zeros to get to wei + while (fraction.length < String(multiplier).length - 1) { + fraction += "0"; + } + const wholeValue = BigInt(whole); + const fractionValue = BigInt(fraction); + let wei = (wholeValue * multiplier) + fractionValue; + if (negative) { + wei *= NegativeOne$1; + } + return wei; +} +class FixedFormat { + signed; + width; + decimals; + name; + _multiplier; + constructor(constructorGuard, signed, width, decimals) { + if (constructorGuard !== _constructorGuard) { + logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", "UNSUPPORTED_OPERATION", { + operation: "new FixedFormat" + }); + } + this.signed = signed; + this.width = width; + this.decimals = decimals; + this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + this._multiplier = getMultiplier(decimals); + Object.freeze(this); + } + static from(value) { + if (value instanceof FixedFormat) { + return value; + } + if (typeof (value) === "number") { + value = `fixed128x${value}`; + } + let signed = true; + let width = 128; + let decimals = 18; + if (typeof (value) === "string") { + if (value === "fixed") { + // defaults... + } + else if (value === "ufixed") { + signed = false; + } + else { + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + if (!match) { + return logger.throwArgumentError("invalid fixed format", "format", value); + } + signed = (match[1] !== "u"); + width = parseInt(match[2]); + decimals = parseInt(match[3]); + } + } + else if (value) { + const check = (key, type, defaultValue) => { + if (value[key] == null) { + return defaultValue; + } + if (typeof (value[key]) !== type) { + logger.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]); + } + return value[key]; + }; + signed = check("signed", "boolean", signed); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); + } + if (width % 8) { + logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); + } + if (decimals > 80) { + logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); + } + return new FixedFormat(_constructorGuard, signed, width, decimals); + } +} +class FixedNumber { + format; + _isFixedNumber; + //#hex: string; + #value; + constructor(constructorGuard, hex, value, format) { + if (constructorGuard !== _constructorGuard) { + logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", "UNSUPPORTED_OPERATION", { + operation: "new FixedFormat" + }); + } + this.format = FixedFormat.from(format); + //this.#hex = hex; + this.#value = value; + this._isFixedNumber = true; + Object.freeze(this); + } + #checkFormat(other) { + if (this.format.name !== other.format.name) { + logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other); + } + } + addUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue(a + b, this.format.decimals, this.format); + } + subUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue(a - b, this.format.decimals, this.format); + } + mulUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue((a * b) / this.format._multiplier, this.format.decimals, this.format); + } + divUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue((a * this.format._multiplier) / b, this.format.decimals, this.format); + } + floor() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (this.isNegative() && hasFraction) { + result = result.subUnsafe(ONE.toFormat(result.format)); + } + return result; + } + ceiling() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (!this.isNegative() && hasFraction) { + result = result.addUnsafe(ONE.toFormat(result.format)); + } + return result; + } + // @TODO: Support other rounding algorithms + round(decimals) { + if (decimals == null) { + decimals = 0; + } + // If we are already in range, we're done + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + if (decimals < 0 || decimals > 80 || (decimals % 1)) { + logger.throwArgumentError("invalid decimal count", "decimals", decimals); + } + if (comps[1].length <= decimals) { + return this; + } + const factor = FixedNumber.from("1" + zeros$1.substring(0, decimals), this.format); + const bump = BUMP.toFormat(this.format); + return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor); + } + isZero() { + return (this.#value === "0.0" || this.#value === "0"); + } + isNegative() { + return (this.#value[0] === "-"); + } + toString() { return this.#value; } + toHexString(_width) { + throw new Error("TODO"); + /* + return toHex(); + if (width == null) { return this.#hex; } + + const width = logger.getNumeric(_width); + if (width % 8) { logger.throwArgumentError("invalid byte width", "width", width); } + + const hex = BigNumber.from(this.#hex).fromTwos(this.format.width).toTwos(width).toHexString(); + return zeroPadLeft(hex, width / 8); + */ + } + toUnsafeFloat() { return parseFloat(this.toString()); } + toFormat(format) { + return FixedNumber.fromString(this.#value, format); + } + static fromValue(value, decimals = 0, format = "fixed") { + return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format)); + } + static fromString(value, format = "fixed") { + const fixedFormat = FixedFormat.from(format); + const numeric = parseFixed(value, fixedFormat.decimals); + if (!fixedFormat.signed && numeric < 0) { + throwFault("unsigned value cannot be negative", "overflow", "value", value); + } + const hex = (function () { + if (fixedFormat.signed) { + return toHex(toTwos(numeric, fixedFormat.width)); + } + return toHex(numeric, fixedFormat.width / 8); + })(); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); + } + static fromBytes(_value, format = "fixed") { + const value = logger.getBytes(_value, "value"); + const fixedFormat = FixedFormat.from(format); + if (value.length > fixedFormat.width / 8) { + throw new Error("overflow"); + } + let numeric = toBigInt(value); + if (fixedFormat.signed) { + numeric = fromTwos(numeric, fixedFormat.width); + } + const hex = toHex(toTwos(numeric, (fixedFormat.signed ? 0 : 1) + fixedFormat.width)); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); + } + static from(value, format) { + if (typeof (value) === "string") { + return FixedNumber.fromString(value, format); + } + if (value instanceof Uint8Array) { + return FixedNumber.fromBytes(value, format); + } + try { + return FixedNumber.fromValue(value, 0, format); + } + catch (error) { + // Allow NUMERIC_FAULT to bubble up + if (error.code !== "INVALID_ARGUMENT") { + throw error; + } + } + return logger.throwArgumentError("invalid FixedNumber value", "value", value); + } + static isFixedNumber(value) { + return !!(value && value._isFixedNumber); + } +} +const ONE = FixedNumber.from(1); +const BUMP = FixedNumber.from("0.5"); + +//See: https://github.com/ethereum/wiki/wiki/RLP +function hexlifyByte(value) { + let result = value.toString(16); + while (result.length < 2) { + result = "0" + result; + } + return "0x" + result; +} +function unarrayifyInteger(data, offset, length) { + let result = 0; + for (let i = 0; i < length; i++) { + result = (result * 256) + data[offset + i]; + } + return result; +} +function _decodeChildren(data, offset, childOffset, length) { + const result = []; + while (childOffset < offset + 1 + length) { + const decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + if (childOffset > offset + 1 + length) { + logger.throwError("child data too short", "BUFFER_OVERRUN", { + buffer: data, length, offset + }); + } + } + return { consumed: (1 + length), result: result }; +} +// returns { consumed: number, result: Object } +function _decode(data, offset) { + if (data.length === 0) { + logger.throwError("data too short", "BUFFER_OVERRUN", { + buffer: data, length: 0, offset: 1 + }); + } + const checkOffset = (offset) => { + if (offset > data.length) { + logger.throwError("data short segment too short", "BUFFER_OVERRUN", { + buffer: data, length: data.length, offset + }); + } + }; + // Array with extra length prefix + if (data[offset] >= 0xf8) { + const lengthLength = data[offset] - 0xf7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } + else if (data[offset] >= 0xc0) { + const length = data[offset] - 0xc0; + checkOffset(offset + 1 + length); + return _decodeChildren(data, offset, offset + 1, length); + } + else if (data[offset] >= 0xb8) { + const lengthLength = data[offset] - 0xb7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { consumed: (1 + lengthLength + length), result: result }; + } + else if (data[offset] >= 0x80) { + const length = data[offset] - 0x80; + checkOffset(offset + 1 + length); + const result = hexlify(data.slice(offset + 1, offset + 1 + length)); + return { consumed: (1 + length), result: result }; + } + return { consumed: 1, result: hexlifyByte(data[offset]) }; +} +function decodeRlp(_data) { + const data = logger.getBytes(_data, "data"); + const decoded = _decode(data, 0); + if (decoded.consumed !== data.length) { + logger.throwArgumentError("unexpected junk after rlp payload", "data", _data); + } + return decoded.result; +} + +//See: https://github.com/ethereum/wiki/wiki/RLP +function arrayifyInteger(value) { + const result = []; + while (value) { + result.unshift(value & 0xff); + value >>= 8; + } + return result; +} +function _encode(object) { + if (Array.isArray(object)) { + let payload = []; + object.forEach(function (child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(0xc0 + payload.length); + return payload; + } + const length = arrayifyInteger(payload.length); + length.unshift(0xf7 + length.length); + return length.concat(payload); + } + const data = Array.prototype.slice.call(logger.getBytes(object, "object")); + if (data.length === 1 && data[0] <= 0x7f) { + return data; + } + else if (data.length <= 55) { + data.unshift(0x80 + data.length); + return data; + } + const length = arrayifyInteger(data.length); + length.unshift(0xb7 + length.length); + return length.concat(data); +} +const nibbles = "0123456789abcdef"; +function encodeRlp(object) { + let result = "0x"; + for (const v of _encode(object)) { + result += nibbles[v >> 4]; + result += nibbles[v & 0xf]; + } + return result; +} + +function getStore(store, key) { + return store[key]; +} +function setStore(store, key, value) { + if (Object.isFrozen(store)) { + throw new Error(`frozen object is immuatable; cannot set ${String(key)}`); + } + store[key] = value; +} + +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether", +]; +/** + * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal + * places. The %%unit%% may be the number of decimal places or the name of + * a unit (e.g. ``"gwei"`` for 9 decimal places). + * + */ +function formatUnits(value, unit) { + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + if (index === -1) { + logger.throwArgumentError("invalid unit", "unit", unit); + } + unit = 3 * index; + } + return formatFixed(value, (unit != null) ? unit : 18); +} +/** + * Converts the //decimal string// %%value%% to a [[BigInt]], assuming + * %%unit%% decimal places. The %%unit%% may the number of decimal places + * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places). + */ +function parseUnits(value, unit) { + if (typeof (value) !== "string") { + logger.throwArgumentError("value must be a string", "value", value); + } + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + if (index === -1) { + logger.throwArgumentError("invalid unit", "unit", unit); + } + unit = 3 * index; + } + return parseFixed(value, (unit != null) ? unit : 18); +} +/** + * Converts %%value%% into a //decimal string// using 18 decimal places. + */ +function formatEther(wei) { + return formatUnits(wei, 18); +} +/** + * Converts the //decimal string// %%ether%% to a [[BigInt]], using 18 + * decimal places. + */ +function parseEther(ether) { + return parseUnits(ether, 18); +} + +//// + +let locked$4 = false; +const _keccak256 = function (data) { + return keccak_256(data); +}; +let __keccak256 = _keccak256; +function keccak256(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__keccak256(data)); +} +keccak256._ = _keccak256; +keccak256.lock = function () { locked$4 = true; }; +keccak256.register = function (func) { + if (locked$4) { + throw new TypeError("keccak256 is locked"); + } + __keccak256 = func; +}; +Object.freeze(keccak256); + +const BN_0$4 = BigInt(0); +const BN_36 = BigInt(36); +function getChecksumAddress(address) { + // if (!isHexString(address, 20)) { + // logger.throwArgumentError("invalid address", "address", address); + // } + address = address.toLowerCase(); + const chars = address.substring(2).split(""); + const expanded = new Uint8Array(40); + for (let i = 0; i < 40; i++) { + expanded[i] = chars[i].charCodeAt(0); + } + const hashed = logger.getBytes(keccak256(expanded)); + for (let i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return "0x" + chars.join(""); +} +// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number +// Create lookup table +const ibanLookup = {}; +for (let i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); +} +for (let i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +} +// How many decimal digits can we process? (for 64-bit float, this is 15) +// i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER)); +const safeDigits = 15; +function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + "00"; + let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join(""); + // Javascript can handle integers safely up to 15 (decimal) digits + while (expanded.length >= safeDigits) { + let block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + let checksum = String(98 - (parseInt(expanded, 10) % 97)); + while (checksum.length < 2) { + checksum = "0" + checksum; + } + return checksum; +} +; +const Base36 = (function () { + ; + const result = {}; + for (let i = 0; i < 36; i++) { + const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; + result[key] = BigInt(i); + } + return result; +})(); +function fromBase36(value) { + value = value.toLowerCase(); + let result = BN_0$4; + for (let i = 0; i < value.length; i++) { + result = result * BN_36 + Base36[value[i]]; + } + return result; +} +function getAddress(address) { + if (typeof (address) !== "string") { + logger.throwArgumentError("invalid address", "address", address); + } + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + // Missing the 0x prefix + if (address.substring(0, 2) !== "0x") { + address = "0x" + address; + } + const result = getChecksumAddress(address); + // It is a checksummed address with a bad checksum + if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { + logger.throwArgumentError("bad address checksum", "address", address); + } + return result; + } + // Maybe ICAP? (we only support direct mode) + if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + // It is an ICAP address with a bad checksum + if (address.substring(2, 4) !== ibanChecksum(address)) { + logger.throwArgumentError("bad icap checksum", "address", address); + } + let result = fromBase36(address.substring(4)).toString(16); + while (result.length < 40) { + result = "0" + result; + } + return getChecksumAddress("0x" + result); + } + return logger.throwArgumentError("invalid address", "address", address); +} +function getIcapAddress(address) { + //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase(); + let base36 = BigInt(getAddress(address)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = "0" + base36; + } + return "XE" + ibanChecksum("XE00" + base36) + base36; +} + +// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed +function getCreateAddress(tx) { + const from = getAddress(tx.from); + const nonce = logger.getBigInt(tx.nonce, "tx.nonce"); + let nonceHex = nonce.toString(16); + if (nonceHex === "0") { + nonceHex = "0x"; + } + else if (nonceHex.length % 2) { + nonceHex = "0x0" + nonceHex; + } + else { + nonceHex = "0x" + nonceHex; + } + return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12)); +} +function getCreate2Address(_from, _salt, _initCodeHash) { + const from = getAddress(_from); + const salt = logger.getBytes(_salt, "salt"); + const initCodeHash = logger.getBytes(_initCodeHash, "initCodeHash"); + if (salt.length !== 32) { + logger.throwArgumentError("salt must be 32 bytes", "salt", _salt); + } + if (initCodeHash.length !== 32) { + logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); + } + return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12)); +} + +function isAddressable(value) { + return (value && typeof (value.getAddress) === "function"); +} +function isAddress(value) { + try { + getAddress(value); + return true; + } + catch (error) { } + return false; +} +async function checkAddress(target, promise) { + const result = await promise; + if (result == null || result === "0x0000000000000000000000000000000000000000") { + if (typeof (target) === "string") { + return logger.throwError("unconfigured name", "UNCONFIGURED_NAME", { value: target }); + } + return logger.throwArgumentError("invalid AddressLike value; did not resolve to a value address", "target", target); + } + return getAddress(result); +} +// Resolves an Ethereum address, ENS name or Addressable object, +// throwing if the result is null. +function resolveAddress(target, resolver) { + if (typeof (target) === "string") { + if (target.match(/^0x[0-9a-f]{40}$/i)) { + return getAddress(target); + } + if (resolver == null) { + return logger.throwError("ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + }); + } + return checkAddress(target, resolver.resolveName(target)); + } + else if (isAddressable(target)) { + return checkAddress(target, target.getAddress()); + } + else if (typeof (target.then) === "function") { + return checkAddress(target, target); + } + return logger.throwArgumentError("unsupported addressable value", "target", target); +} + +const _gaurd = {}; +function n(value, width) { + let signed = false; + if (width < 0) { + signed = true; + width *= -1; + } + // @TODO: Check range is valid for value + return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { signed, width }); +} +function b(value, size) { + // @TODO: Check range is valid for value + return new Typed(_gaurd, `bytes${(size) ? size : ""}`, value, { size }); +} +const _typedSymbol = Symbol.for("_ethers_typed"); +class Typed { + type; + value; + #options; + _typedSymbol; + constructor(gaurd, type, value, options = null) { + if (gaurd !== _gaurd) { + throw new Error("private constructor"); + } + defineProperties(this, { _typedSymbol, type, value }); + this.#options = options; + // Check the value is valid + this.format(); + } + format() { + if (this.type === "array") { + throw new Error(""); + } + else if (this.type === "dynamicArray") { + throw new Error(""); + } + else if (this.type === "tuple") { + return `tuple(${this.value.map((v) => v.format()).join(",")})`; + } + return this.type; + } + defaultValue() { + return 0; + } + minValue() { + return 0; + } + maxValue() { + return 0; + } + isBigInt() { + return !!(this.type.match(/^u?int[0-9]+$/)); + } + isData() { + return (this.type.substring(0, 5) === "bytes"); + } + isString() { + return (this.type === "string"); + } + get tupleName() { + if (this.type !== "tuple") { + throw TypeError("not a tuple"); + } + return this.#options; + } + // Returns the length of this type as an array + // - `null` indicates the length is unforced, it could be dynamic + // - `-1` indicates the length is dynamic + // - any other value indicates it is a static array and is its length + get arrayLength() { + if (this.type !== "array") { + throw TypeError("not an array"); + } + if (this.#options === true) { + return -1; + } + if (this.#options === false) { + return (this.value).length; + } + return null; + } + static from(type, value) { + return new Typed(_gaurd, type, value); + } + static uint8(v) { return n(v, 8); } + static uint16(v) { return n(v, 16); } + static uint24(v) { return n(v, 24); } + static uint32(v) { return n(v, 32); } + static uint40(v) { return n(v, 40); } + static uint48(v) { return n(v, 46); } + static uint56(v) { return n(v, 56); } + static uint64(v) { return n(v, 64); } + static uint72(v) { return n(v, 72); } + static uint80(v) { return n(v, 80); } + static uint88(v) { return n(v, 88); } + static uint96(v) { return n(v, 96); } + static uint104(v) { return n(v, 104); } + static uint112(v) { return n(v, 112); } + static uint120(v) { return n(v, 120); } + static uint128(v) { return n(v, 128); } + static uint136(v) { return n(v, 136); } + static uint144(v) { return n(v, 144); } + static uint152(v) { return n(v, 152); } + static uint160(v) { return n(v, 160); } + static uint168(v) { return n(v, 168); } + static uint176(v) { return n(v, 176); } + static uint184(v) { return n(v, 184); } + static uint192(v) { return n(v, 192); } + static uint200(v) { return n(v, 200); } + static uint208(v) { return n(v, 208); } + static uint216(v) { return n(v, 216); } + static uint224(v) { return n(v, 224); } + static uint232(v) { return n(v, 232); } + static uint240(v) { return n(v, 240); } + static uint248(v) { return n(v, 248); } + static uint256(v) { return n(v, 256); } + static uint(v) { return n(v, 256); } + static int8(v) { return n(v, -8); } + static int16(v) { return n(v, -16); } + static int24(v) { return n(v, -24); } + static int32(v) { return n(v, -32); } + static int40(v) { return n(v, -40); } + static int48(v) { return n(v, -46); } + static int56(v) { return n(v, -56); } + static int64(v) { return n(v, -64); } + static int72(v) { return n(v, -72); } + static int80(v) { return n(v, -80); } + static int88(v) { return n(v, -88); } + static int96(v) { return n(v, -96); } + static int104(v) { return n(v, -104); } + static int112(v) { return n(v, -112); } + static int120(v) { return n(v, -120); } + static int128(v) { return n(v, -128); } + static int136(v) { return n(v, -136); } + static int144(v) { return n(v, -144); } + static int152(v) { return n(v, -152); } + static int160(v) { return n(v, -160); } + static int168(v) { return n(v, -168); } + static int176(v) { return n(v, -176); } + static int184(v) { return n(v, -184); } + static int192(v) { return n(v, -192); } + static int200(v) { return n(v, -200); } + static int208(v) { return n(v, -208); } + static int216(v) { return n(v, -216); } + static int224(v) { return n(v, -224); } + static int232(v) { return n(v, -232); } + static int240(v) { return n(v, -240); } + static int248(v) { return n(v, -248); } + static int256(v) { return n(v, -256); } + static int(v) { return n(v, -256); } + static bytes(v) { return b(v); } + static bytes1(v) { return b(v, 1); } + static bytes2(v) { return b(v, 2); } + static bytes3(v) { return b(v, 3); } + static bytes4(v) { return b(v, 4); } + static bytes5(v) { return b(v, 5); } + static bytes6(v) { return b(v, 6); } + static bytes7(v) { return b(v, 7); } + static bytes8(v) { return b(v, 8); } + static bytes9(v) { return b(v, 9); } + static bytes10(v) { return b(v, 10); } + static bytes11(v) { return b(v, 11); } + static bytes12(v) { return b(v, 12); } + static bytes13(v) { return b(v, 13); } + static bytes14(v) { return b(v, 14); } + static bytes15(v) { return b(v, 15); } + static bytes16(v) { return b(v, 16); } + static bytes17(v) { return b(v, 17); } + static bytes18(v) { return b(v, 18); } + static bytes19(v) { return b(v, 19); } + static bytes20(v) { return b(v, 20); } + static bytes21(v) { return b(v, 21); } + static bytes22(v) { return b(v, 22); } + static bytes23(v) { return b(v, 23); } + static bytes24(v) { return b(v, 24); } + static bytes25(v) { return b(v, 25); } + static bytes26(v) { return b(v, 26); } + static bytes27(v) { return b(v, 27); } + static bytes28(v) { return b(v, 28); } + static bytes29(v) { return b(v, 29); } + static bytes30(v) { return b(v, 30); } + static bytes31(v) { return b(v, 31); } + static bytes32(v) { return b(v, 32); } + static address(v) { return new Typed(_gaurd, "address", v); } + static bool(v) { return new Typed(_gaurd, "bool", !!v); } + static string(v) { return new Typed(_gaurd, "string", v); } + static array(v, dynamic) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "array", v, dynamic); + } + static tuple(v, name) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "tuple", v, name); + } + static overrides(v) { + return new Typed(_gaurd, "overrides", Object.assign({}, v)); + } + static isTyped(value) { + return (value && value._typedSymbol === _typedSymbol); + } + static dereference(value, type) { + if (Typed.isTyped(value)) { + if (value.type !== type) { + throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); + } + return value.value; + } + return value; + } +} + +class AddressCoder extends Coder { + constructor(localName) { + super("address", "address", localName, false); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, _value) { + let value = Typed.dereference(_value, "string"); + try { + value = getAddress(value); + } + catch (error) { + return this._throwError(error.message, _value); + } + return writer.writeValue(value); + } + decode(reader) { + return getAddress(toHex(reader.readValue(), 20)); + } +} + +// Clones the functionality of an existing Coder, but without a localName +class AnonymousCoder extends Coder { + coder; + constructor(coder) { + super(coder.name, coder.type, "_", coder.dynamic); + this.coder = coder; + } + defaultValue() { + return this.coder.defaultValue(); + } + encode(writer, value) { + return this.coder.encode(writer, value); + } + decode(reader) { + return this.coder.decode(reader); + } +} + +function pack(writer, coders, values) { + let arrayValues = []; + if (Array.isArray(values)) { + arrayValues = values; + } + else if (values && typeof (values) === "object") { + let unique = {}; + arrayValues = coders.map((coder) => { + const name = coder.localName; + if (!name) { + logger.throwError("cannot encode object for signature with missing names", "INVALID_ARGUMENT", { + argument: "values", + info: { coder }, + value: values + }); + } + if (unique[name]) { + logger.throwError("cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { + argument: "values", + info: { coder }, + value: values + }); + } + unique[name] = true; + return values[name]; + }); + } + else { + logger.throwArgumentError("invalid tuple value", "tuple", values); + } + if (coders.length !== arrayValues.length) { + logger.throwArgumentError("types/value length mismatch", "tuple", values); + } + let staticWriter = new Writer(); + let dynamicWriter = new Writer(); + let updateFuncs = []; + coders.forEach((coder, index) => { + let value = arrayValues[index]; + if (coder.dynamic) { + // Get current dynamic offset (for the future pointer) + let dynamicOffset = dynamicWriter.length; + // Encode the dynamic value into the dynamicWriter + coder.encode(dynamicWriter, value); + // Prepare to populate the correct offset once we are done + let updateFunc = staticWriter.writeUpdatableValue(); + updateFuncs.push((baseOffset) => { + updateFunc(baseOffset + dynamicOffset); + }); + } + else { + coder.encode(staticWriter, value); + } + }); + // Backfill all the dynamic offsets, now that we know the static length + updateFuncs.forEach((func) => { func(staticWriter.length); }); + let length = writer.appendWriter(staticWriter); + length += writer.appendWriter(dynamicWriter); + return length; +} +function unpack(reader, coders) { + let values = []; + let keys = []; + // A reader anchored to this base + let baseReader = reader.subReader(0); + coders.forEach((coder) => { + let value = null; + if (coder.dynamic) { + let offset = reader.readIndex(); + let offsetReader = baseReader.subReader(offset); + try { + value = coder.decode(offsetReader); + } + catch (error) { + // Cannot recover from this + if (isError(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + else { + try { + value = coder.decode(reader); + } + catch (error) { + // Cannot recover from this + if (isError(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + if (value == undefined) { + throw new Error("investigate"); + } + values.push(value); + keys.push(coder.localName || null); + }); + return Result.fromItems(values, keys); +} +class ArrayCoder extends Coder { + coder; + length; + constructor(coder, length, localName) { + const type = (coder.type + "[" + (length >= 0 ? length : "") + "]"); + const dynamic = (length === -1 || coder.dynamic); + super("array", type, localName, dynamic); + defineProperties(this, { coder, length }); + } + defaultValue() { + // Verifies the child coder is valid (even if the array is dynamic or 0-length) + const defaultChild = this.coder.defaultValue(); + const result = []; + for (let i = 0; i < this.length; i++) { + result.push(defaultChild); + } + return result; + } + encode(writer, _value) { + const value = Typed.dereference(_value, "array"); + if (!Array.isArray(value)) { + this._throwError("expected array value", value); + } + let count = this.length; + if (count === -1) { + count = value.length; + writer.writeValue(value.length); + } + logger.assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : "")); + let coders = []; + for (let i = 0; i < value.length; i++) { + coders.push(this.coder); + } + return pack(writer, coders, value); + } + decode(reader) { + let count = this.length; + if (count === -1) { + count = reader.readIndex(); + // Check that there is *roughly* enough data to ensure + // stray random data is not being read as a length. Each + // slot requires at least 32 bytes for their value (or 32 + // bytes as a link to the data). This could use a much + // tighter bound, but we are erroring on the side of safety. + if (count * WordSize > reader.dataLength) { + logger.throwError("insufficient data length", "BUFFER_OVERRUN", { + buffer: reader.bytes, + offset: count * WordSize, + length: reader.dataLength + }); + } + } + let coders = []; + for (let i = 0; i < count; i++) { + coders.push(new AnonymousCoder(this.coder)); + } + return unpack(reader, coders); + } +} + +class BooleanCoder extends Coder { + constructor(localName) { + super("bool", "bool", localName, false); + } + defaultValue() { + return false; + } + encode(writer, _value) { + const value = Typed.dereference(_value, "bool"); + return writer.writeValue(value ? 1 : 0); + } + decode(reader) { + return !!reader.readValue(); + } +} + +class DynamicBytesCoder extends Coder { + constructor(type, localName) { + super(type, type, localName, true); + } + defaultValue() { + return "0x"; + } + encode(writer, value) { + value = logger.getBytesCopy(value); + let length = writer.writeValue(value.length); + length += writer.writeBytes(value); + return length; + } + decode(reader) { + return reader.readBytes(reader.readIndex(), true); + } +} +class BytesCoder extends DynamicBytesCoder { + constructor(localName) { + super("bytes", localName); + } + decode(reader) { + return hexlify(super.decode(reader)); + } +} + +class FixedBytesCoder extends Coder { + size; + constructor(size, localName) { + let name = "bytes" + String(size); + super(name, name, localName, false); + defineProperties(this, { size }, { size: "number" }); + } + defaultValue() { + return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2); + } + encode(writer, _value) { + let data = logger.getBytesCopy(Typed.dereference(_value, this.type)); + if (data.length !== this.size) { + this._throwError("incorrect data length", _value); + } + return writer.writeBytes(data); + } + decode(reader) { + return hexlify(reader.readBytes(this.size)); + } +} + +const Empty$1 = new Uint8Array([]); +class NullCoder extends Coder { + constructor(localName) { + super("null", "", localName, false); + } + defaultValue() { + return null; + } + encode(writer, value) { + if (value != null) { + this._throwError("not null", value); + } + return writer.writeBytes(Empty$1); + } + decode(reader) { + reader.readBytes(0); + return null; + } +} + +const BN_0$3 = BigInt(0); +const BN_1$4 = BigInt(1); +const BN_MAX_UINT256$2 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +class NumberCoder extends Coder { + size; + signed; + constructor(size, signed, localName) { + const name = ((signed ? "int" : "uint") + (size * 8)); + super(name, name, localName, false); + defineProperties(this, { size, signed }, { size: "number", signed: "boolean" }); + } + defaultValue() { + return 0; + } + encode(writer, _value) { + let value = logger.getBigInt(Typed.dereference(_value, this.type)); + // Check bounds are safe for encoding + let maxUintValue = mask(BN_MAX_UINT256$2, WordSize * 8); + if (this.signed) { + let bounds = mask(maxUintValue, (this.size * 8) - 1); + if (value > bounds || value < -(bounds + BN_1$4)) { + this._throwError("value out-of-bounds", _value); + } + } + else if (value < BN_0$3 || value > mask(maxUintValue, this.size * 8)) { + this._throwError("value out-of-bounds", _value); + } + value = mask(toTwos(value, this.size * 8), this.size * 8); + if (this.signed) { + value = toTwos(fromTwos(value, this.size * 8), 8 * WordSize); + } + return writer.writeValue(value); + } + decode(reader) { + let value = mask(reader.readValue(), this.size * 8); + if (this.signed) { + value = fromTwos(value, this.size * 8); + } + return value; + } +} + +class StringCoder extends DynamicBytesCoder { + constructor(localName) { + super("string", localName); + } + defaultValue() { + return ""; + } + encode(writer, _value) { + return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string"))); + } + decode(reader) { + return toUtf8String(super.decode(reader)); + } +} + +class TupleCoder extends Coder { + coders; + constructor(coders, localName) { + let dynamic = false; + const types = []; + coders.forEach((coder) => { + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + const type = ("tuple(" + types.join(",") + ")"); + super("tuple", type, localName, dynamic); + defineProperties(this, { coders: Object.freeze(coders.slice()) }); + } + defaultValue() { + const values = []; + this.coders.forEach((coder) => { + values.push(coder.defaultValue()); + }); + // We only output named properties for uniquely named coders + const uniqueNames = this.coders.reduce((accum, coder) => { + const name = coder.localName; + if (name) { + if (!accum[name]) { + accum[name] = 0; + } + accum[name]++; + } + return accum; + }, {}); + // Add named values + this.coders.forEach((coder, index) => { + let name = coder.localName; + if (!name || uniqueNames[name] !== 1) { + return; + } + if (name === "length") { + name = "_length"; + } + if (values[name] != null) { + return; + } + values[name] = values[index]; + }); + return Object.freeze(values); + } + encode(writer, _value) { + const value = Typed.dereference(_value, "tuple"); + return pack(writer, this.coders, value); + } + decode(reader) { + return unpack(reader, this.coders); + } +} + +; +var FormatType; +(function (FormatType) { + // Bare formatting, as is needed for computing a sighash of an event or function + FormatType["sighash"] = "sighash"; + // Human-Readable with Minimal spacing and without names (compact human-readable) + FormatType["minimal"] = "minimal"; + // Human-Readable with nice spacing, including all names + FormatType["full"] = "full"; + // JSON-format a la Solidity + FormatType["json"] = "json"; +})(FormatType || (FormatType = {})); +; +// [ "a", "b" ] => { "a": 1, "b": 1 } +function setify(items) { + const result = new Set(); + items.forEach((k) => result.add(k)); + return Object.freeze(result); +} +// Visibility Keywords +const _kwVisib = "constant external internal payable private public pure view"; +const KwVisib = setify(_kwVisib.split(" ")); +const _kwTypes = "constructor error event function struct"; +const KwTypes = setify(_kwTypes.split(" ")); +const _kwModifiers = "calldata memory storage payable indexed"; +const KwModifiers = setify(_kwModifiers.split(" ")); +const _kwOther = "tuple returns"; +// All Keywords +const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" "); +const Keywords = setify(_keywords.split(" ")); +// Single character tokens +const SimpleTokens = { + "(": "OPEN_PAREN", ")": "CLOSE_PAREN", + "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET", + ",": "COMMA", "@": "AT" +}; +// Parser regexes to consume the next token +const regexWhitespace = new RegExp("^(\\s*)"); +const regexNumber$1 = new RegExp("^([0-9]+)"); +const regexIdentifier = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); +const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))"); +class TokenString { + #offset; + #tokens; + get offset() { return this.#offset; } + get length() { return this.#tokens.length - this.#offset; } + constructor(tokens) { + this.#offset = 0; + this.#tokens = tokens.slice(); + } + clone() { return new TokenString(this.#tokens); } + reset() { this.#offset = 0; } + #subTokenString(from = 0, to = 0) { + return new TokenString(this.#tokens.slice(from, to).map((t) => { + return Object.freeze(Object.assign({}, t, { + match: (t.match - from), + linkBack: (t.linkBack - from), + linkNext: (t.linkNext - from), + })); + return t; + })); + } + // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens + popKeyword(allowed) { + const top = this.peek(); + if (top.type !== "KEYWORD" || !allowed.has(top.text)) { + throw new Error(`expected keyword ${top.text}`); + } + return this.pop().text; + } + // Pops and returns the value of the next token if it is `type`; throws if out of tokens + popType(type) { + if (this.peek().type !== type) { + throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`); + } + return this.pop().text; + } + // Pops and returns a "(" TOKENS ")" + popParen() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = this.#subTokenString(this.#offset + 1, top.match + 1); + this.#offset = top.match + 1; + return result; + } + // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" + popParams() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = []; + while (this.#offset < top.match - 1) { + const link = this.peek().linkNext; + result.push(this.#subTokenString(this.#offset + 1, link)); + this.#offset = link; + } + this.#offset = top.match + 1; + return result; + } + // Returns the top Token, throwing if out of tokens + peek() { + if (this.#offset >= this.#tokens.length) { + throw new Error("out-of-bounds"); + } + return this.#tokens[this.#offset]; + } + // Returns the next value, if it is a keyword in `allowed` + peekKeyword(allowed) { + const top = this.peekType("KEYWORD"); + return (top != null && allowed.has(top)) ? top : null; + } + // Returns the value of the next token if it is `type` + peekType(type) { + if (this.length === 0) { + return null; + } + const top = this.peek(); + return (top.type === type) ? top.text : null; + } + // Returns the next token; throws if out of tokens + pop() { + const result = this.peek(); + this.#offset++; + return result; + } + toString() { + const tokens = []; + for (let i = this.#offset; i < this.#tokens.length; i++) { + const token = this.#tokens[i]; + tokens.push(`${token.type}:${token.text}`); + } + return ``; + } +} +function lex(text) { + const tokens = []; + const throwError = (message) => { + const token = (offset < text.length) ? JSON.stringify(text[offset]) : "$EOI"; + throw new Error(`invalid token ${token} at ${offset}: ${message}`); + }; + let brackets = []; + let commas = []; + let offset = 0; + while (offset < text.length) { + // Strip off any leading whitespace + let cur = text.substring(offset); + let match = cur.match(regexWhitespace); + if (match) { + offset += match[1].length; + cur = text.substring(offset); + } + const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 }; + tokens.push(token); + let type = (SimpleTokens[cur[0]] || ""); + if (type) { + token.type = type; + token.text = cur[0]; + offset++; + if (type === "OPEN_PAREN") { + brackets.push(tokens.length - 1); + commas.push(tokens.length - 1); + } + else if (type == "CLOSE_PAREN") { + if (brackets.length === 0) { + throwError("no matching open bracket"); + } + token.match = brackets.pop(); + (tokens[token.match]).match = tokens.length - 1; + token.depth--; + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + } + else if (type === "COMMA") { + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + commas.push(tokens.length - 1); + } + else if (type === "OPEN_BRACKET") { + token.type = "BRACKET"; + } + else if (type === "CLOSE_BRACKET") { + // Remove the CLOSE_BRACKET + let suffix = tokens.pop().text; + if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { + const value = tokens.pop().text; + suffix = value + suffix; + (tokens[tokens.length - 1]).value = logger.getNumber(value); + } + if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { + throw new Error("missing opening bracket"); + } + (tokens[tokens.length - 1]).text += suffix; + } + continue; + } + match = cur.match(regexIdentifier); + if (match) { + token.text = match[1]; + offset += token.text.length; + if (Keywords.has(token.text)) { + token.type = "KEYWORD"; + continue; + } + if (token.text.match(regexType)) { + token.type = "TYPE"; + continue; + } + token.type = "ID"; + continue; + } + match = cur.match(regexNumber$1); + if (match) { + token.text = match[1]; + token.type = "NUMBER"; + offset += token.text.length; + continue; + } + throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); + } + return new TokenString(tokens.map((t) => Object.freeze(t))); +} +// Check only one of `allowed` is in `set` +function allowSingle(set, allowed) { + let included = []; + for (const key in allowed.keys()) { + if (set.has(key)) { + included.push(key); + } + } + if (included.length > 1) { + throw new Error(`conflicting types: ${included.join(", ")}`); + } +} +// Functions to process a Solidity Signature TokenString from left-to-right for... +// ...the name with an optional type, returning the name +function consumeName(type, tokens) { + if (tokens.peekKeyword(KwTypes)) { + const keyword = tokens.pop().text; + if (keyword !== type) { + throw new Error(`expected ${type}, got ${keyword}`); + } + } + return tokens.popType("ID"); +} +// ...all keywords matching allowed, returning the keywords +function consumeKeywords(tokens, allowed) { + const keywords = new Set(); + while (true) { + const keyword = tokens.peekType("KEYWORD"); + if (keyword == null || (allowed && !allowed.has(keyword))) { + break; + } + tokens.pop(); + if (keywords.has(keyword)) { + throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); + } + keywords.add(keyword); + } + return Object.freeze(keywords); +} +// ...all visibility keywords, returning the coalesced mutability +function consumeMutability(tokens) { + let modifiers = consumeKeywords(tokens, KwVisib); + // Detect conflicting modifiers + allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); + allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); + // Process mutability states + if (modifiers.has("view")) { + return "view"; + } + if (modifiers.has("pure")) { + return "pure"; + } + if (modifiers.has("payable")) { + return "payable"; + } + if (modifiers.has("nonpayable")) { + return "nonpayable"; + } + // Process legacy `constant` last + if (modifiers.has("constant")) { + return "view"; + } + return "nonpayable"; +} +// ...a parameter list, returning the ParamType list +function consumeParams(tokens, allowIndexed) { + return tokens.popParams().map((t) => ParamType.fromTokens(t, allowIndexed)); +} +// ...a gas limit, returning a BigNumber or null if none +function consumeGas(tokens) { + if (tokens.peekType("AT")) { + tokens.pop(); + if (tokens.peekType("NUMBER")) { + return logger.getBigInt(tokens.pop().text); + } + throw new Error("invalid gas"); + } + return null; +} +function consumeEoi(tokens) { + if (tokens.length) { + throw new Error(`unexpected tokens: ${tokens.toString()}`); + } +} +const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); +function verifyBasicType(type) { + const match = type.match(regexType); + if (!match) { + return logger.throwArgumentError("invalid type", "type", type); + } + if (type === "uint") { + return "uint256"; + } + if (type === "int") { + return "int256"; + } + if (match[2]) { + // bytesXX + const length = parseInt(match[2]); + if (length === 0 || length > 32) { + logger.throwArgumentError("invalid bytes length", "type", type); + } + } + else if (match[3]) { + // intXX or uintXX + const size = parseInt(match[3]); + if (size === 0 || size > 256 || size % 8) { + logger.throwArgumentError("invalid numeric width", "type", type); + } + } + return type; +} +// Make the Fragment constructors effectively private +const _guard$3 = {}; +const internal$1 = Symbol.for("_ethers_internal"); +const ParamTypeInternal = "_ParamTypeInternal"; +class ParamType { + // The local name of the parameter (of "" if unbound) + name; + // The fully qualified type (e.g. "address", "tuple(address)", "uint256[3][]" + type; + // The base type (e.g. "address", "tuple", "array") + baseType; + // Indexable Paramters ONLY (otherwise null) + indexed; + // Tuples ONLY: (otherwise null) + // - sub-components + components; + // Arrays ONLY: (otherwise null) + // - length of the array (-1 for dynamic length) + // - child type + arrayLength; + arrayChildren; + constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) { + logger.assertPrivate(guard, _guard$3, "ParamType"); + Object.defineProperty(this, internal$1, { value: ParamTypeInternal }); + if (components) { + components = Object.freeze(components.slice()); + } + if (baseType === "array") { + if (arrayLength == null || arrayChildren == null) { + throw new Error(""); + } + } + else if (arrayLength != null || arrayChildren != null) { + throw new Error(""); + } + if (baseType === "tuple") { + if (components == null) { + throw new Error(""); + } + } + else if (components != null) { + throw new Error(""); + } + defineProperties(this, { + name, type, baseType, indexed, components, arrayLength, arrayChildren + }); + } + // Format the parameter fragment + // - sighash: "(uint256,address)" + // - minimal: "tuple(uint256,address) indexed" + // - full: "tuple(uint256 foo, address bar) indexed baz" + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + let result = { + type: ((this.baseType === "tuple") ? "tuple" : this.type), + name: (this.name || undefined) + }; + if (typeof (this.indexed) === "boolean") { + result.indexed = this.indexed; + } + if (this.isTuple()) { + result.components = this.components.map((c) => JSON.parse(c.format(format))); + } + return JSON.stringify(result); + } + let result = ""; + // Array + if (this.isArray()) { + result += this.arrayChildren.format(format); + result += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`; + } + else { + if (this.isTuple()) { + if (format !== FormatType.sighash) { + result += this.type; + } + result += "(" + this.components.map((comp) => comp.format(format)).join((format === FormatType.full) ? ", " : ",") + ")"; + } + else { + result += this.type; + } + } + if (format !== FormatType.sighash) { + if (this.indexed === true) { + result += " indexed"; + } + if (format === FormatType.full && this.name) { + result += " " + this.name; + } + } + return result; + } + static isArray(value) { + return value && (value.baseType === "array"); + } + isArray() { + return (this.baseType === "array"); + } + isTuple() { + return (this.baseType === "tuple"); + } + isIndexable() { + return (this.indexed != null); + } + walk(value, process) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invlaid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + return value.map((v) => (this.arrayChildren.walk(v, process))); + } + if (this.isTuple()) { + if (!Array.isArray(value)) { + throw new Error("invlaid tuple value"); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + return value.map((v, i) => (this.components[i].walk(v, process))); + } + return process(this.type, value); + } + #walkAsync(promises, value, process, setValue) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invlaid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const childType = this.arrayChildren; + const result = value.slice(); + result.forEach((value, index) => { + childType.#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + if (this.isTuple()) { + const components = this.components; + // Convert the object into an array + let result; + if (Array.isArray(value)) { + result = value.slice(); + } + else { + if (value == null || typeof (value) !== "object") { + throw new Error("invlaid tuple value"); + } + result = components.map((param) => { + if (!param.name) { + throw new Error("cannot use object value with unnamed components"); + } + if (!(param.name in value)) { + throw new Error(`missing value for component ${param.name}`); + } + return value[param.name]; + }); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + result.forEach((value, index) => { + components[index].#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + const result = process(this.type, value); + if (result.then) { + promises.push((async function () { setValue(await result); })()); + } + else { + setValue(result); + } + } + async walkAsync(value, process) { + const promises = []; + const result = [value]; + this.#walkAsync(promises, value, process, (value) => { + result[0] = value; + }); + if (promises.length) { + await Promise.all(promises); + } + return result[0]; + } + static from(obj, allowIndexed) { + if (ParamType.isParamType(obj)) { + return obj; + } + if (typeof (obj) === "string") { + return ParamType.fromTokens(lex(obj), allowIndexed); + } + if (obj instanceof TokenString) { + return ParamType.fromTokens(obj, allowIndexed); + } + const name = obj.name; + if (name && (typeof (name) !== "string" || !name.match(regexIdentifier))) { + logger.throwArgumentError("invalid name", "obj.name", name); + } + let indexed = obj.indexed; + if (indexed != null) { + if (!allowIndexed) { + logger.throwArgumentError("parameter cannot be indexed", "obj.indexed", obj.indexed); + } + indexed = !!indexed; + } + let type = obj.type; + let arrayMatch = type.match(regexArrayType); + if (arrayMatch) { + const arrayLength = arrayMatch[2]; + const arrayChildren = ParamType.from({ + type: arrayMatch[1], + components: obj.components + }); + return new ParamType(_guard$3, name, type, "array", indexed, null, arrayLength, arrayChildren); + } + if (type.substring(0, 5) === "tuple(" || type[0] === "(") { + const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null; + const tuple = new ParamType(_guard$3, name, type, "tuple", indexed, comps, null, null); + // @TODO: use lexer to validate and normalize type + return tuple; + } + type = verifyBasicType(obj.type); + return new ParamType(_guard$3, name, type, type, indexed, null, null, null); + } + static fromObject(obj, allowIndexed) { + throw new Error("@TODO"); + } + static fromTokens(tokens, allowIndexed) { + let type = "", baseType = ""; + let comps = null; + if (consumeKeywords(tokens, setify(["tuple"])).has("tuple") || tokens.peekType("OPEN_PAREN")) { + // Tuple + baseType = "tuple"; + comps = tokens.popParams().map((t) => ParamType.from(t)); + type = `tuple(${comps.map((c) => c.format()).join(",")})`; + } + else { + // Normal + type = verifyBasicType(tokens.popType("TYPE")); + baseType = type; + } + // Check for Array + let arrayChildren = null; + let arrayLength = null; + while (tokens.length && tokens.peekType("BRACKET")) { + const bracket = tokens.pop(); //arrays[i]; + arrayChildren = new ParamType(_guard$3, "", type, baseType, null, comps, arrayLength, arrayChildren); + arrayLength = bracket.value; + type += bracket.text; + baseType = "array"; + comps = null; + } + let indexed = null; + const keywords = consumeKeywords(tokens, KwModifiers); + if (keywords.has("indexed")) { + if (!allowIndexed) { + throw new Error(""); + } + indexed = true; + } + const name = (tokens.peekType("ID") ? tokens.pop().text : ""); + if (tokens.length) { + throw new Error("leftover tokens"); + } + return new ParamType(_guard$3, name, type, baseType, indexed, comps, arrayLength, arrayChildren); + } + static isParamType(value) { + return (value && value[internal$1] === ParamTypeInternal); + } +} +var FragmentType; +(function (FragmentType) { + FragmentType["constructor"] = "constructor"; + FragmentType["error"] = "error"; + FragmentType["event"] = "event"; + FragmentType["function"] = "function"; + FragmentType["struct"] = "struct"; +})(FragmentType || (FragmentType = {})); +; +class Fragment { + type; + inputs; + constructor(guard, type, inputs) { + logger.assertPrivate(guard, _guard$3, "Fragment"); + inputs = Object.freeze(inputs.slice()); + defineProperties(this, { type, inputs }); + } + static from(obj) { + if (typeof (obj) === "string") { + return this.fromString(obj); + } + if (obj instanceof TokenString) { + return this.fromTokens(obj); + } + if (typeof (obj) === "object") { + return this.fromObject(obj); + } + throw new Error(`unsupported type: ${obj}`); + } + static fromObject(obj) { + switch (obj.type) { + case "constructor": return ConstructorFragment.fromObject(obj); + case "error": return ErrorFragment.fromObject(obj); + case "event": return EventFragment.fromObject(obj); + case "function": return FunctionFragment.fromObject(obj); + case "struct": return StructFragment.fromObject(obj); + } + throw new Error("not implemented yet"); + } + static fromString(text) { + try { + Fragment.from(JSON.parse(text)); + } + catch (e) { } + return Fragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const type = tokens.popKeyword(KwTypes); + switch (type) { + case "constructor": return ConstructorFragment.fromTokens(tokens); + case "error": return ErrorFragment.fromTokens(tokens); + case "event": return EventFragment.fromTokens(tokens); + case "function": return FunctionFragment.fromTokens(tokens); + case "struct": return StructFragment.fromTokens(tokens); + } + throw new Error(`unsupported type: ${type}`); + } + /* + static fromTokens(tokens: TokenString): Fragment { + const assertDone = () => { + if (tokens.length) { throw new Error(`unexpected tokens: ${ tokens.toString() }`); } + }); + + const type = (tokens.length && tokens.peek().type === "KEYWORD") ? tokens.peek().text: "unknown"; + + const name = consumeName("error", tokens); + const inputs = consumeParams(tokens, type === "event"); + + switch (type) { + case "event": case "struct": + assertDone(); + } + + } + */ + static isConstructor(value) { + return (value && value.type === "constructor"); + } + static isError(value) { + return (value && value.type === "error"); + } + static isEvent(value) { + return (value && value.type === "event"); + } + static isFunction(value) { + return (value && value.type === "function"); + } + static isStruct(value) { + return (value && value.type === "struct"); + } +} +class NamedFragment extends Fragment { + name; + constructor(guard, type, name, inputs) { + super(guard, type, inputs); + inputs = Object.freeze(inputs.slice()); + defineProperties(this, { name }); + } +} +function joinParams(format, params) { + return "(" + params.map((p) => p.format(format)).join((format === FormatType.full) ? ", " : ",") + ")"; +} +class ErrorFragment extends NamedFragment { + constructor(guard, name, inputs) { + super(guard, FragmentType.error, name, inputs); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input) => JSON.parse(input.format(format))), + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("error"); + } + result.push(this.name + joinParams(format, this.inputs)); + return result.join(" "); + } + static fromString(text) { + return ErrorFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("error", tokens); + const inputs = consumeParams(tokens); + consumeEoi(tokens); + return new ErrorFragment(_guard$3, name, inputs); + } +} +class EventFragment extends NamedFragment { + anonymous; + constructor(guard, name, inputs, anonymous) { + super(guard, FragmentType.event, name, inputs); + defineProperties(this, { anonymous }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("event"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== FormatType.sighash && this.anonymous) { + result.push("anonymous"); + } + return result.join(" "); + } + static fromString(text) { + return EventFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("event", tokens); + const inputs = consumeParams(tokens, true); + const anonymous = !!consumeKeywords(tokens, setify(["anonymous"])).has("anonymous"); + consumeEoi(tokens); + return new EventFragment(_guard$3, name, inputs, anonymous); + } +} +class ConstructorFragment extends Fragment { + payable; + gas; + constructor(guard, type, inputs, payable, gas) { + super(guard, type, inputs); + defineProperties(this, { payable, gas }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.sighash) { + logger.throwError("cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { + operation: "format(sighash)" + }); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "constructor", + stateMutability: (this.payable ? "payable" : "undefined"), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = [`constructor${joinParams(format, this.inputs)}`]; + result.push((this.payable) ? "payable" : "nonpayable"); + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + return result.join(" "); + } + static fromString(text) { + return ConstructorFragment.fromTokens(lex(text)); + } + static fromObject(obj) { + throw new Error("TODO"); + } + static fromTokens(tokens) { + consumeKeywords(tokens, setify(["constructor"])); + const inputs = consumeParams(tokens); + const payable = !!consumeKeywords(tokens, setify(["payable"])).has("payable"); + const gas = consumeGas(tokens); + consumeEoi(tokens); + return new ConstructorFragment(_guard$3, FragmentType.constructor, inputs, payable, gas); + } +} +class FunctionFragment extends NamedFragment { + constant; + outputs; + stateMutability; + payable; + gas; + constructor(guard, name, stateMutability, inputs, outputs, gas) { + super(guard, FragmentType.function, name, inputs); + outputs = Object.freeze(outputs.slice()); + const constant = (stateMutability === "view" || stateMutability === "pure"); + const payable = (stateMutability === "payable"); + defineProperties(this, { constant, gas, outputs, payable, stateMutability }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))), + outputs: this.outputs.map((o) => JSON.parse(o.format(format))), + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("function"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== FormatType.sighash) { + if (this.stateMutability !== "nonpayable") { + result.push(this.stateMutability); + } + if (this.outputs && this.outputs.length) { + result.push("returns"); + result.push(joinParams(format, this.outputs)); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + } + return result.join(" "); + } + static fromString(text) { + return FunctionFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("function", tokens); + const inputs = consumeParams(tokens); + const mutability = consumeMutability(tokens); + let outputs = []; + if (consumeKeywords(tokens, setify(["returns"])).has("returns")) { + outputs = consumeParams(tokens); + } + const gas = consumeGas(tokens); + consumeEoi(tokens); + return new FunctionFragment(_guard$3, name, mutability, inputs, outputs, gas); + } +} +class StructFragment extends NamedFragment { + format() { + throw new Error("@TODO"); + } + static fromString(text) { + return StructFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("struct", tokens); + const inputs = consumeParams(tokens); + consumeEoi(tokens); + return new StructFragment(_guard$3, FragmentType.struct, name, inputs); + } +} + +// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +class AbiCoder { + #getCoder(param) { + if (param.isArray()) { + return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); + } + if (param.isTuple()) { + return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name); + } + switch (param.baseType) { + case "address": + return new AddressCoder(param.name); + case "bool": + return new BooleanCoder(param.name); + case "string": + return new StringCoder(param.name); + case "bytes": + return new BytesCoder(param.name); + case "": + return new NullCoder(param.name); + } + // u?int[0-9]* + let match = param.type.match(paramTypeNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if (size === 0 || size > 256 || (size % 8) !== 0) { + logger.throwArgumentError("invalid " + match[1] + " bit length", "param", param); + } + return new NumberCoder(size / 8, (match[1] === "int"), param.name); + } + // bytes[0-9]+ + match = param.type.match(paramTypeBytes); + if (match) { + let size = parseInt(match[1]); + if (size === 0 || size > 32) { + logger.throwArgumentError("invalid bytes length", "param", param); + } + return new FixedBytesCoder(size, param.name); + } + return logger.throwArgumentError("invalid type", "type", param.type); + } + getDefaultValue(types) { + const coders = types.map((type) => this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.defaultValue(); + } + encode(types, values) { + logger.assertArgumentCount(values.length, types.length, "types/values length mismatch"); + const coders = types.map((type) => this.#getCoder(ParamType.from(type))); + const coder = (new TupleCoder(coders, "_")); + const writer = new Writer(); + coder.encode(writer, values); + return writer.data; + } + decode(types, data, loose) { + const coders = types.map((type) => this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.decode(new Reader(data, loose)); + } +} +const defaultAbiCoder = new AbiCoder(); + +function formatBytes32String(text) { + // Get the bytes + const bytes = toUtf8Bytes(text); + // Check we have room for null-termination + if (bytes.length > 31) { + throw new Error("bytes32 string must be less than 32 bytes"); + } + // Zero-pad (implicitly null-terminates) + return zeroPadBytes(bytes, 32); +} +function parseBytes32String(_bytes) { + const data = logger.getBytes(_bytes, "bytes"); + // Must be 32 bytes with a null-termination + if (data.length !== 32) { + throw new Error("invalid bytes32 - not 32 bytes long"); + } + if (data[31] !== 0) { + throw new Error("invalid bytes32 string - no null terminator"); + } + // Find the null termination + let length = 31; + while (data[length - 1] === 0) { + length--; + } + // Determine the string value + return toUtf8String(data.slice(0, length)); +} + +// HMAC (RFC 2104) +class HMAC extends Hash { + constructor(hash, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert.hash(hash); + const key = toBytes(_key); + this.iHash = hash.create(); + if (!(this.iHash instanceof Hash)) + throw new TypeError('Expected instance of class which extends utils.Hash'); + const blockLen = (this.blockLen = this.iHash.blockLen); + this.outputLen = this.iHash.outputLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > this.iHash.blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assert.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert.exists(this); + assert.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ +const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key) => new HMAC(hash, key); + +// Common prologue and epilogue for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + assert.hash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + assert.number(c); + assert.number(dkLen); + assert.number(asyncTick); + if (c < 1) + throw new Error('PBKDF2: iterations (c) should be >= 1'); + const password = toBytes(_password); + const salt = toBytes(_salt); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + u.fill(0); + return DK; +} +/** + * PBKDF2-HMAC: RFC 2898 key derivation function + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated + * @param salt - cryptographic salt + * @param opts - {c, dkLen} where c is work factor and dkLen is output message size + */ +function pbkdf2$1(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, (i) => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Base SHA2 class (RFC 6234) +class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + assert.exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + assert.exists(this); + assert.output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + this.get().forEach((v, i) => oview.setUint32(4 * i, v, isLE)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} + +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): +// prettier-ignore +const IV = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = new Uint32Array(64); +class SHA256 extends SHA2 { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +} +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256$1 = wrapConstructor(() => new SHA256()); + +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); +class SHA512 extends SHA2 { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +class SHA512_256 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x22312194 | 0; + this.Al = 0xfc2bf72c | 0; + this.Bh = 0x9f555fa3 | 0; + this.Bl = 0xc84c64c2 | 0; + this.Ch = 0x2393b86b | 0; + this.Cl = 0x6f53b151 | 0; + this.Dh = 0x96387719 | 0; + this.Dl = 0x5940eabd | 0; + this.Eh = 0x96283ee2 | 0; + this.El = 0xa88effe3 | 0; + this.Fh = 0xbe5e1e25 | 0; + this.Fl = 0x53863992 | 0; + this.Gh = 0x2b0199fc | 0; + this.Gl = 0x2c85b8aa | 0; + this.Hh = 0x0eb72ddc | 0; + this.Hl = 0x81c52ca2 | 0; + this.outputLen = 32; + } +} +class SHA384 extends SHA512 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +} +const sha512$1 = wrapConstructor(() => new SHA512()); +const sha512_256 = wrapConstructor(() => new SHA512_256()); +const sha384 = wrapConstructor(() => new SHA384()); + +/* Browser Crypto Shims */ +function getGlobal$1() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const anyGlobal = getGlobal$1(); +const crypto$1 = anyGlobal.crypto || anyGlobal.msCrypto; +function createHash(algo) { + switch (algo) { + case "sha256": return sha256$1.create(); + case "sha512": return sha512$1.create(); + } + return logger.throwArgumentError("invalid hashing algorithm name", "algorithm", algo); +} +function createHmac(_algo, key) { + const algo = ({ sha256: sha256$1, sha512: sha512$1 }[_algo]); + if (algo == null) { + return logger.throwArgumentError("invalid hmac algorithm", "algorithm", _algo); + } + return hmac.create(algo, key); +} +function pbkdf2Sync(password, salt, iterations, keylen, _algo) { + const algo = ({ sha256: sha256$1, sha512: sha512$1 }[_algo]); + if (algo == null) { + return logger.throwArgumentError("invalid pbkdf2 algorithm", "algorithm", _algo); + } + return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen }); +} +function randomBytes$1(length) { + if (crypto$1 == null) { + return logger.throwError("platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { + operation: "randomBytes" + }); + } + if (!Number.isInteger(length) || length <= 0 || length > 1024) { + logger.throwArgumentError("invalid length", "length", length); + } + const result = new Uint8Array(length); + crypto$1.getRandomValues(result); + return result; +} + +let locked$3 = false; +const _computeHmac = function (algorithm, key, data) { + return "0x" + createHmac(algorithm, key).update(data).digest("hex"); +}; +let __computeHmac = _computeHmac; +function computeHmac(algorithm, _key, _data) { + const key = logger.getBytes(_key, "key"); + const data = logger.getBytes(_data, "data"); + return hexlify(__computeHmac(algorithm, key, data)); +} +computeHmac._ = _computeHmac; +computeHmac.lock = function () { locked$3 = true; }; +computeHmac.register = function (func) { + if (locked$3) { + throw new Error("computeHmac is locked"); + } + __computeHmac = func; +}; +Object.freeze(computeHmac); + +// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html +// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf +const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +const Id = Uint8Array.from({ length: 16 }, (_, i) => i); +const Pi = Id.map((i) => (9 * i + 5) % 16); +let idxL = [Id]; +let idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +const shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => new Uint8Array(i)); +const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]); +const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]); +// The rotate left (circular left shift) operation for uint32 +const rotl$1 = (word, shift) => (word << shift) | (word >>> (32 - shift)); +// It's called f() in spec. +function f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + else if (group === 1) + return (x & y) | (~x & z); + else if (group === 2) + return (x | ~y) ^ z; + else if (group === 3) + return (x & z) | (y & ~z); + else + return x ^ (y | ~z); +} +// Temporary buffer, not used to store anything between runs +const BUF = new Uint32Array(16); +class RIPEMD160 extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl$1(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl$1(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl$1(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a hash function from 1990s. + * @param message - msg that would be hashed + */ +const ripemd160$1 = wrapConstructor(() => new RIPEMD160()); + +let locked$2 = false; +const _ripemd160 = function (data) { + return ripemd160$1(data); +}; +let __ripemd160 = _ripemd160; +function ripemd160(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__ripemd160(data)); +} +ripemd160._ = _ripemd160; +ripemd160.lock = function () { locked$2 = true; }; +ripemd160.register = function (func) { + if (locked$2) { + throw new TypeError("ripemd160 is locked"); + } + __ripemd160 = func; +}; +Object.freeze(ripemd160); + +let locked$1 = false; +const _pbkdf2 = function (password, salt, iterations, keylen, algo) { + return pbkdf2Sync(password, salt, iterations, keylen, algo); +}; +let __pbkdf2 = _pbkdf2; +function pbkdf2(_password, _salt, iterations, keylen, algo) { + const password = logger.getBytes(_password, "password"); + const salt = logger.getBytes(_salt, "salt"); + return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); +} +pbkdf2._ = _pbkdf2; +pbkdf2.lock = function () { locked$1 = true; }; +pbkdf2.register = function (func) { + if (locked$1) { + throw new Error("pbkdf2 is locked"); + } + __pbkdf2 = func; +}; +Object.freeze(pbkdf2); + +let locked = false; +const _randomBytes = function (length) { + return new Uint8Array(randomBytes$1(length)); +}; +let __randomBytes = _randomBytes; +function randomBytes(length) { + return __randomBytes(length); +} +randomBytes._ = _randomBytes; +randomBytes.lock = function () { locked = true; }; +randomBytes.register = function (func) { + if (locked) { + throw new Error("random is locked"); + } + __randomBytes = func; +}; +Object.freeze(randomBytes); + +// RFC 7914 Scrypt KDF +// Left rotate for uint32 +const rotl = (a, b) => (a << b) | (a >>> (32 - b)); +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + assert.number(N); + assert.number(r); + assert.number(p); + assert.number(dkLen); + assert.number(asyncTick); + assert.number(maxmem); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb should be function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function + // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. + throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2$1(sha256$1, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2$1(sha256$1, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; +} +/** + * Scrypt KDF from RFC 7914. + * @param password - pass + * @param salt - salt + * @param opts - parameters + * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + * @returns Derived key + */ +function scrypt$1(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. + */ +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, (i) => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, (i) => { + // First u32 of the last 64-byte block (u32 is LE) + const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); +} + +let lockedSync = false, lockedAsync = false; +const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) { + return await scryptAsync(passwd, salt, { N, r, p, dkLen, onProgress }); +}; +const _scryptSync = function (passwd, salt, N, r, p, dkLen) { + return scrypt$1(passwd, salt, { N, r, p, dkLen }); +}; +let __scryptAsync = _scryptAsync; +let __scryptSync = _scryptSync; +async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) { + const passwd = logger.getBytes(_passwd, "passwd"); + const salt = logger.getBytes(_salt, "salt"); + return hexlify(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); +} +scrypt._ = _scryptAsync; +scrypt.lock = function () { lockedAsync = true; }; +scrypt.register = function (func) { + if (lockedAsync) { + throw new Error("scrypt is locked"); + } + __scryptAsync = func; +}; +Object.freeze(scrypt); +function scryptSync(_passwd, _salt, N, r, p, dkLen) { + const passwd = logger.getBytes(_passwd, "passwd"); + const salt = logger.getBytes(_salt, "salt"); + return hexlify(__scryptSync(passwd, salt, N, r, p, dkLen)); +} +scryptSync._ = _scryptSync; +scryptSync.lock = function () { lockedSync = true; }; +scryptSync.register = function (func) { + if (lockedSync) { + throw new Error("scryptSync is locked"); + } + __scryptSync = func; +}; +Object.freeze(scryptSync); + +const _sha256 = function (data) { + return createHash("sha256").update(data).digest(); +}; +const _sha512 = function (data) { + return createHash("sha512").update(data).digest(); +}; +let __sha256 = _sha256; +let __sha512 = _sha512; +let locked256 = false, locked512 = false; +function sha256(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__sha256(data)); +} +sha256._ = _sha256; +sha256.lock = function () { locked256 = true; }; +sha256.register = function (func) { + if (locked256) { + throw new Error("sha256 is locked"); + } + __sha256 = func; +}; +Object.freeze(sha256); +function sha512(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__sha512(data)); +} +sha512._ = _sha512; +sha512.lock = function () { locked512 = true; }; +sha512.register = function (func) { + if (locked512) { + throw new Error("sha512 is locked"); + } + __sha512 = func; +}; +Object.freeze(sha256); + +var _nodeResolve_empty = {}; + +var nodeCrypto = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty +}); + +/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _3n = BigInt(3); +const _8n = BigInt(8); +const POW_2_256 = _2n ** BigInt(256); +const CURVE = { + a: _0n, + b: BigInt(7), + P: POW_2_256 - _2n ** BigInt(32) - BigInt(977), + n: POW_2_256 - BigInt('432420386565659656852420866394968145599'), + h: _1n, + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), +}; +function weistrass(x) { + const { a, b } = CURVE; + const x2 = mod(x * x); + const x3 = mod(x2 * x); + return mod(x3 + a * x + b); +} +const USE_ENDOMORPHISM = CURVE.a === _0n; +class JacobianPoint { + constructor(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + } + static fromAffine(p) { + if (!(p instanceof Point)) { + throw new TypeError('JacobianPoint#fromAffine: expected Point'); + } + return new JacobianPoint(p.x, p.y, _1n); + } + static toAffineBatch(points) { + const toInv = invertBatch(points.map((p) => p.z)); + return points.map((p, i) => p.toAffine(toInv[i])); + } + static normalizeZ(points) { + return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); + } + equals(other) { + if (!(other instanceof JacobianPoint)) + throw new TypeError('JacobianPoint expected'); + const { x: X1, y: Y1, z: Z1 } = this; + const { x: X2, y: Y2, z: Z2 } = other; + const Z1Z1 = mod(Z1 ** _2n); + const Z2Z2 = mod(Z2 ** _2n); + const U1 = mod(X1 * Z2Z2); + const U2 = mod(X2 * Z1Z1); + const S1 = mod(mod(Y1 * Z2) * Z2Z2); + const S2 = mod(mod(Y2 * Z1) * Z1Z1); + return U1 === U2 && S1 === S2; + } + negate() { + return new JacobianPoint(this.x, mod(-this.y), this.z); + } + double() { + const { x: X1, y: Y1, z: Z1 } = this; + const A = mod(X1 ** _2n); + const B = mod(Y1 ** _2n); + const C = mod(B ** _2n); + const D = mod(_2n * (mod((X1 + B) ** _2n) - A - C)); + const E = mod(_3n * A); + const F = mod(E ** _2n); + const X3 = mod(F - _2n * D); + const Y3 = mod(E * (D - X3) - _8n * C); + const Z3 = mod(_2n * Y1 * Z1); + return new JacobianPoint(X3, Y3, Z3); + } + add(other) { + if (!(other instanceof JacobianPoint)) + throw new TypeError('JacobianPoint expected'); + const { x: X1, y: Y1, z: Z1 } = this; + const { x: X2, y: Y2, z: Z2 } = other; + if (X2 === _0n || Y2 === _0n) + return this; + if (X1 === _0n || Y1 === _0n) + return other; + const Z1Z1 = mod(Z1 ** _2n); + const Z2Z2 = mod(Z2 ** _2n); + const U1 = mod(X1 * Z2Z2); + const U2 = mod(X2 * Z1Z1); + const S1 = mod(mod(Y1 * Z2) * Z2Z2); + const S2 = mod(mod(Y2 * Z1) * Z1Z1); + const H = mod(U2 - U1); + const r = mod(S2 - S1); + if (H === _0n) { + if (r === _0n) { + return this.double(); + } + else { + return JacobianPoint.ZERO; + } + } + const HH = mod(H ** _2n); + const HHH = mod(H * HH); + const V = mod(U1 * HH); + const X3 = mod(r ** _2n - HHH - _2n * V); + const Y3 = mod(r * (V - X3) - S1 * HHH); + const Z3 = mod(Z1 * Z2 * H); + return new JacobianPoint(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + multiplyUnsafe(scalar) { + const P0 = JacobianPoint.ZERO; + if (typeof scalar === 'bigint' && scalar === _0n) + return P0; + let n = normalizeScalar(scalar); + if (n === _1n) + return this; + if (!USE_ENDOMORPHISM) { + let p = P0; + let d = this; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + } + let { k1neg, k1, k2neg, k2 } = splitScalarEndo(n); + let k1p = P0; + let k2p = P0; + let d = this; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + k1p = k1p.add(d); + if (k2 & _1n) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n; + k2 >>= _1n; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z); + return k1p.add(k2p); + } + precomputeWindow(W) { + const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; + const points = []; + let p = this; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i = 1; i < 2 ** (W - 1); i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + } + wNAF(n, affinePoint) { + if (!affinePoint && this.equals(JacobianPoint.BASE)) + affinePoint = Point.BASE; + const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1; + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); + } + let precomputes = affinePoint && pointPrecomputes.get(affinePoint); + if (!precomputes) { + precomputes = this.precomputeWindow(W); + if (affinePoint && W !== 1) { + precomputes = JacobianPoint.normalizeZ(precomputes); + pointPrecomputes.set(affinePoint, precomputes); + } + } + let p = JacobianPoint.ZERO; + let f = JacobianPoint.ZERO; + const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W); + const windowSize = 2 ** (W - 1); + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + if (wbits === 0) { + let pr = precomputes[offset]; + if (window % 2) + pr = pr.negate(); + f = f.add(pr); + } + else { + let cached = precomputes[offset + Math.abs(wbits) - 1]; + if (wbits < 0) + cached = cached.negate(); + p = p.add(cached); + } + } + return { p, f }; + } + multiply(scalar, affinePoint) { + let n = normalizeScalar(scalar); + let point; + let fake; + if (USE_ENDOMORPHISM) { + const { k1neg, k1, k2neg, k2 } = splitScalarEndo(n); + let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint); + let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint); + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } + else { + const { p, f } = this.wNAF(n, affinePoint); + point = p; + fake = f; + } + return JacobianPoint.normalizeZ([point, fake])[0]; + } + toAffine(invZ = invert(this.z)) { + const { x, y, z } = this; + const iz1 = invZ; + const iz2 = mod(iz1 * iz1); + const iz3 = mod(iz2 * iz1); + const ax = mod(x * iz2); + const ay = mod(y * iz3); + const zz = mod(z * iz1); + if (zz !== _1n) + throw new Error('invZ was invalid'); + return new Point(ax, ay); + } +} +JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n); +JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n); +const pointPrecomputes = new WeakMap(); +class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + static fromCompressedHex(bytes) { + const isShort = bytes.length === 32; + const x = bytesToNumber(isShort ? bytes : bytes.subarray(1)); + if (!isValidFieldElement(x)) + throw new Error('Point is not on curve'); + const y2 = weistrass(x); + let y = sqrtMod(y2); + const isYOdd = (y & _1n) === _1n; + if (isShort) { + if (isYOdd) + y = mod(-y); + } + else { + const isFirstByteOdd = (bytes[0] & 1) === 1; + if (isFirstByteOdd !== isYOdd) + y = mod(-y); + } + const point = new Point(x, y); + point.assertValidity(); + return point; + } + static fromUncompressedHex(bytes) { + const x = bytesToNumber(bytes.subarray(1, 33)); + const y = bytesToNumber(bytes.subarray(33, 65)); + const point = new Point(x, y); + point.assertValidity(); + return point; + } + static fromHex(hex) { + const bytes = ensureBytes(hex); + const len = bytes.length; + const header = bytes[0]; + if (len === 32 || (len === 33 && (header === 0x02 || header === 0x03))) { + return this.fromCompressedHex(bytes); + } + if (len === 65 && header === 0x04) + return this.fromUncompressedHex(bytes); + throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`); + } + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normalizePrivateKey(privateKey)); + } + static fromSignature(msgHash, signature, recovery) { + msgHash = ensureBytes(msgHash); + const h = truncateHash(msgHash); + const { r, s } = normalizeSignature(signature); + if (recovery !== 0 && recovery !== 1) { + throw new Error('Cannot recover signature: invalid recovery bit'); + } + const prefix = recovery & 1 ? '03' : '02'; + const R = Point.fromHex(prefix + numTo32bStr(r)); + const { n } = CURVE; + const rinv = invert(r, n); + const u1 = mod(-h * rinv, n); + const u2 = mod(s * rinv, n); + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) + throw new Error('Cannot recover signature: point at infinify'); + Q.assertValidity(); + return Q; + } + toRawBytes(isCompressed = false) { + return hexToBytes(this.toHex(isCompressed)); + } + toHex(isCompressed = false) { + const x = numTo32bStr(this.x); + if (isCompressed) { + const prefix = this.y & _1n ? '03' : '02'; + return `${prefix}${x}`; + } + else { + return `04${x}${numTo32bStr(this.y)}`; + } + } + toHexX() { + return this.toHex(true).slice(2); + } + toRawX() { + return this.toRawBytes(true).slice(1); + } + assertValidity() { + const msg = 'Point is not on elliptic curve'; + const { x, y } = this; + if (!isValidFieldElement(x) || !isValidFieldElement(y)) + throw new Error(msg); + const left = mod(y * y); + const right = weistrass(x); + if (mod(left - right) !== _0n) + throw new Error(msg); + } + equals(other) { + return this.x === other.x && this.y === other.y; + } + negate() { + return new Point(this.x, mod(-this.y)); + } + double() { + return JacobianPoint.fromAffine(this).double().toAffine(); + } + add(other) { + return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); + } + subtract(other) { + return this.add(other.negate()); + } + multiply(scalar) { + return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } + multiplyAndAddUnsafe(Q, a, b) { + const P = JacobianPoint.fromAffine(this); + const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a); + const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b); + const sum = aP.add(bQ); + return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine(); + } +} +Point.BASE = new Point(CURVE.Gx, CURVE.Gy); +Point.ZERO = new Point(_0n, _0n); +function sliceDER(s) { + return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s; +} +function parseDERInt(data) { + if (data.length < 2 || data[0] !== 0x02) { + throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`); + } + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) { + throw new Error(`Invalid signature integer: wrong length`); + } + if (res[0] === 0x00 && res[1] <= 0x7f) { + throw new Error('Invalid signature integer: trailing length'); + } + return { data: bytesToNumber(res), left: data.subarray(len + 2) }; +} +function parseDERSignature(data) { + if (data.length < 2 || data[0] != 0x30) { + throw new Error(`Invalid signature tag: ${bytesToHex(data)}`); + } + if (data[1] !== data.length - 2) { + throw new Error('Invalid signature: incorrect length'); + } + const { data: r, left: sBytes } = parseDERInt(data.subarray(2)); + const { data: s, left: rBytesLeft } = parseDERInt(sBytes); + if (rBytesLeft.length) { + throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`); + } + return { r, s }; +} +class Signature$1 { + constructor(r, s) { + this.r = r; + this.s = s; + this.assertValidity(); + } + static fromCompact(hex) { + const arr = isUint8a(hex); + const name = 'Signature.fromCompact'; + if (typeof hex !== 'string' && !arr) + throw new TypeError(`${name}: Expected string or Uint8Array`); + const str = arr ? bytesToHex(hex) : hex; + if (str.length !== 128) + throw new Error(`${name}: Expected 64-byte hex`); + return new Signature$1(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128))); + } + static fromDER(hex) { + const arr = isUint8a(hex); + if (typeof hex !== 'string' && !arr) + throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`); + const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex)); + return new Signature$1(r, s); + } + static fromHex(hex) { + return this.fromDER(hex); + } + assertValidity() { + const { r, s } = this; + if (!isWithinCurveOrder(r)) + throw new Error('Invalid Signature: r must be 0 < r < n'); + if (!isWithinCurveOrder(s)) + throw new Error('Invalid Signature: s must be 0 < s < n'); + } + hasHighS() { + const HALF = CURVE.n >> _1n; + return this.s > HALF; + } + normalizeS() { + return this.hasHighS() ? new Signature$1(this.r, CURVE.n - this.s) : this; + } + toDERRawBytes(isCompressed = false) { + return hexToBytes(this.toDERHex(isCompressed)); + } + toDERHex(isCompressed = false) { + const sHex = sliceDER(numberToHexUnpadded(this.s)); + if (isCompressed) + return sHex; + const rHex = sliceDER(numberToHexUnpadded(this.r)); + const rLen = numberToHexUnpadded(rHex.length / 2); + const sLen = numberToHexUnpadded(sHex.length / 2); + const length = numberToHexUnpadded(rHex.length / 2 + sHex.length / 2 + 4); + return `30${length}02${rLen}${rHex}02${sLen}${sHex}`; + } + toRawBytes() { + return this.toDERRawBytes(); + } + toHex() { + return this.toDERHex(); + } + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numTo32bStr(this.r) + numTo32bStr(this.s); + } +} +function concatBytes(...arrays) { + if (!arrays.every(isUint8a)) + throw new Error('Uint8Array list expected'); + if (arrays.length === 1) + return arrays[0]; + const length = arrays.reduce((a, arr) => a + arr.length, 0); + const result = new Uint8Array(length); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } + return result; +} +function isUint8a(bytes) { + return bytes instanceof Uint8Array; +} +const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +function bytesToHex(uint8a) { + if (!(uint8a instanceof Uint8Array)) + throw new Error('Expected Uint8Array'); + let hex = ''; + for (let i = 0; i < uint8a.length; i++) { + hex += hexes[uint8a[i]]; + } + return hex; +} +function numTo32bStr(num) { + if (num > POW_2_256) + throw new Error('Expected number < 2^256'); + return num.toString(16).padStart(64, '0'); +} +function numTo32b(num) { + return hexToBytes(numTo32bStr(num)); +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToNumber: expected string, got ' + typeof hex); + } + return BigInt(`0x${hex}`); +} +function hexToBytes(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + typeof hex); + } + if (hex.length % 2) + throw new Error('hexToBytes: received invalid unpadded hex' + hex.length); + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error('Invalid byte sequence'); + array[i] = byte; + } + return array; +} +function bytesToNumber(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function ensureBytes(hex) { + return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex); +} +function normalizeScalar(num) { + if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0) + return BigInt(num); + if (typeof num === 'bigint' && isWithinCurveOrder(num)) + return num; + throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n'); +} +function mod(a, b = CURVE.P) { + const result = a % b; + return result >= _0n ? result : b + result; +} +function pow2(x, power) { + const { P } = CURVE; + let res = x; + while (power-- > _0n) { + res *= res; + res %= P; + } + return res; +} +function sqrtMod(x) { + const { P } = CURVE; + const _6n = BigInt(6); + const _11n = BigInt(11); + const _22n = BigInt(22); + const _23n = BigInt(23); + const _44n = BigInt(44); + const _88n = BigInt(88); + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n) * b3) % P; + const b9 = (pow2(b6, _3n) * b3) % P; + const b11 = (pow2(b9, _2n) * b2) % P; + const b22 = (pow2(b11, _11n) * b11) % P; + const b44 = (pow2(b22, _22n) * b22) % P; + const b88 = (pow2(b44, _44n) * b44) % P; + const b176 = (pow2(b88, _88n) * b88) % P; + const b220 = (pow2(b176, _44n) * b44) % P; + const b223 = (pow2(b220, _3n) * b3) % P; + const t1 = (pow2(b223, _23n) * b22) % P; + const t2 = (pow2(t1, _6n) * b2) % P; + return pow2(t2, _2n); +} +function invert(number, modulo = CURVE.P) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + let a = mod(number, modulo); + let b = modulo; + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +function invertBatch(nums, p = CURVE.P) { + const scratch = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i) => { + if (num === _0n) + return acc; + scratch[i] = acc; + return mod(acc * num, p); + }, _1n); + const inverted = invert(lastMultiplied, p); + nums.reduceRight((acc, num, i) => { + if (num === _0n) + return acc; + scratch[i] = mod(acc * scratch[i], p); + return mod(acc * num, p); + }, inverted); + return scratch; +} +const divNearest = (a, b) => (a + b / _2n) / b; +const POW_2_128 = _2n ** BigInt(128); +function splitScalarEndo(k) { + const { n } = CURVE; + const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + const b2 = a1; + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalarEndo: Endomorphism failed, k=' + k); + } + return { k1neg, k1, k2neg, k2 }; +} +function truncateHash(hash) { + const { n } = CURVE; + const byteLength = hash.length; + const delta = byteLength * 8 - 256; + let h = bytesToNumber(hash); + if (delta > 0) + h = h >> BigInt(delta); + if (h >= n) + h -= n; + return h; +} +class HmacDrbg { + constructor() { + this.v = new Uint8Array(32).fill(1); + this.k = new Uint8Array(32).fill(0); + this.counter = 0; + } + hmac(...values) { + return utils.hmacSha256(this.k, ...values); + } + hmacSync(...values) { + if (typeof utils.hmacSha256Sync !== 'function') + throw new Error('utils.hmacSha256Sync is undefined, you need to set it'); + const res = utils.hmacSha256Sync(this.k, ...values); + if (res instanceof Promise) + throw new Error('To use sync sign(), ensure utils.hmacSha256 is sync'); + return res; + } + incr() { + if (this.counter >= 1000) { + throw new Error('Tried 1,000 k values for sign(), all were invalid'); + } + this.counter += 1; + } + async reseed(seed = new Uint8Array()) { + this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed); + this.v = await this.hmac(this.v); + if (seed.length === 0) + return; + this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed); + this.v = await this.hmac(this.v); + } + reseedSync(seed = new Uint8Array()) { + this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed); + this.v = this.hmacSync(this.v); + if (seed.length === 0) + return; + this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed); + this.v = this.hmacSync(this.v); + } + async generate() { + this.incr(); + this.v = await this.hmac(this.v); + return this.v; + } + generateSync() { + this.incr(); + this.v = this.hmacSync(this.v); + return this.v; + } +} +function isWithinCurveOrder(num) { + return _0n < num && num < CURVE.n; +} +function isValidFieldElement(num) { + return _0n < num && num < CURVE.P; +} +function kmdToSig(kBytes, m, d) { + const k = bytesToNumber(kBytes); + if (!isWithinCurveOrder(k)) + return; + const { n } = CURVE; + const q = Point.BASE.multiply(k); + const r = mod(q.x, n); + if (r === _0n) + return; + const s = mod(invert(k, n) * mod(m + d * r, n), n); + if (s === _0n) + return; + const sig = new Signature$1(r, s); + const recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n); + return { sig, recovery }; +} +function normalizePrivateKey(key) { + let num; + if (typeof key === 'bigint') { + num = key; + } + else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) { + num = BigInt(key); + } + else if (typeof key === 'string') { + if (key.length !== 64) + throw new Error('Expected 32 bytes of private key'); + num = hexToNumber(key); + } + else if (isUint8a(key)) { + if (key.length !== 32) + throw new Error('Expected 32 bytes of private key'); + num = bytesToNumber(key); + } + else { + throw new TypeError('Expected valid private key'); + } + if (!isWithinCurveOrder(num)) + throw new Error('Expected private key: 0 < key < n'); + return num; +} +function normalizePublicKey(publicKey) { + if (publicKey instanceof Point) { + publicKey.assertValidity(); + return publicKey; + } + else { + return Point.fromHex(publicKey); + } +} +function normalizeSignature(signature) { + if (signature instanceof Signature$1) { + signature.assertValidity(); + return signature; + } + try { + return Signature$1.fromDER(signature); + } + catch (error) { + return Signature$1.fromCompact(signature); + } +} +function getPublicKey(privateKey, isCompressed = false) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); +} +function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) { + return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed); +} +function isPub(item) { + const arr = isUint8a(item); + const str = typeof item === 'string'; + const len = (arr || str) && item.length; + if (arr) + return len === 33 || len === 65; + if (str) + return len === 66 || len === 130; + if (item instanceof Point) + return true; + return false; +} +function getSharedSecret(privateA, publicB, isCompressed = false) { + if (isPub(privateA)) + throw new TypeError('getSharedSecret: first arg must be private key'); + if (!isPub(publicB)) + throw new TypeError('getSharedSecret: second arg must be public key'); + const b = normalizePublicKey(publicB); + b.assertValidity(); + return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed); +} +function bits2int(bytes) { + const slice = bytes.length > 32 ? bytes.slice(0, 32) : bytes; + return bytesToNumber(slice); +} +function bits2octets(bytes) { + const z1 = bits2int(bytes); + const z2 = mod(z1, CURVE.n); + return int2octets(z2 < _0n ? z1 : z2); +} +function int2octets(num) { + if (typeof num !== 'bigint') + throw new Error('Expected bigint'); + const hex = numTo32bStr(num); + return hexToBytes(hex); +} +function initSigArgs(msgHash, privateKey, extraEntropy) { + if (msgHash == null) + throw new Error(`sign: expected valid message hash, not "${msgHash}"`); + const h1 = ensureBytes(msgHash); + const d = normalizePrivateKey(privateKey); + const seedArgs = [int2octets(d), bits2octets(h1)]; + if (extraEntropy != null) { + if (extraEntropy === true) + extraEntropy = utils.randomBytes(32); + const e = ensureBytes(extraEntropy); + if (e.length !== 32) + throw new Error('sign: Expected 32 bytes of extra data'); + seedArgs.push(e); + } + const seed = concatBytes(...seedArgs); + const m = bits2int(h1); + return { seed, m, d }; +} +function finalizeSig(recSig, opts) { + let { sig, recovery } = recSig; + const { canonical, der, recovered } = Object.assign({ canonical: true, der: true }, opts); + if (canonical && sig.hasHighS()) { + sig = sig.normalizeS(); + recovery ^= 1; + } + const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes(); + return recovered ? [hashed, recovery] : hashed; +} +async function sign(msgHash, privKey, opts = {}) { + const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy); + let sig; + const drbg = new HmacDrbg(); + await drbg.reseed(seed); + while (!(sig = kmdToSig(await drbg.generate(), m, d))) + await drbg.reseed(); + return finalizeSig(sig, opts); +} +function signSync(msgHash, privKey, opts = {}) { + const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy); + let sig; + const drbg = new HmacDrbg(); + drbg.reseedSync(seed); + while (!(sig = kmdToSig(drbg.generateSync(), m, d))) + drbg.reseedSync(); + return finalizeSig(sig, opts); +} +const vopts = { strict: true }; +function verify(signature, msgHash, publicKey, opts = vopts) { + let sig; + try { + sig = normalizeSignature(signature); + msgHash = ensureBytes(msgHash); + } + catch (error) { + return false; + } + const { r, s } = sig; + if (opts.strict && sig.hasHighS()) + return false; + const h = truncateHash(msgHash); + let P; + try { + P = normalizePublicKey(publicKey); + } + catch (error) { + return false; + } + const { n } = CURVE; + const sinv = invert(s, n); + const u1 = mod(h * sinv, n); + const u2 = mod(r * sinv, n); + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2); + if (!R) + return false; + const v = mod(R.x, n); + return v === r; +} +function finalizeSchnorrChallenge(ch) { + return mod(bytesToNumber(ch), CURVE.n); +} +function hasEvenY(point) { + return (point.y & _1n) === _0n; +} +class SchnorrSignature { + constructor(r, s) { + this.r = r; + this.s = s; + this.assertValidity(); + } + static fromHex(hex) { + const bytes = ensureBytes(hex); + if (bytes.length !== 64) + throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`); + const r = bytesToNumber(bytes.subarray(0, 32)); + const s = bytesToNumber(bytes.subarray(32, 64)); + return new SchnorrSignature(r, s); + } + assertValidity() { + const { r, s } = this; + if (!isValidFieldElement(r) || !isWithinCurveOrder(s)) + throw new Error('Invalid signature'); + } + toHex() { + return numTo32bStr(this.r) + numTo32bStr(this.s); + } + toRawBytes() { + return hexToBytes(this.toHex()); + } +} +function schnorrGetPublicKey(privateKey) { + return Point.fromPrivateKey(privateKey).toRawX(); +} +function initSchnorrSigArgs(message, privateKey, auxRand) { + if (message == null) + throw new TypeError(`sign: Expected valid message, not "${message}"`); + const m = ensureBytes(message); + const d0 = normalizePrivateKey(privateKey); + const rand = ensureBytes(auxRand); + if (rand.length !== 32) + throw new TypeError('sign: Expected 32 bytes of aux randomness'); + const P = Point.fromPrivateKey(d0); + const px = P.toRawX(); + const d = hasEvenY(P) ? d0 : CURVE.n - d0; + return { m, P, px, d, rand }; +} +function initSchnorrNonce(d, t0h) { + return numTo32b(d ^ bytesToNumber(t0h)); +} +function finalizeSchnorrNonce(k0h) { + const k0 = mod(bytesToNumber(k0h), CURVE.n); + if (k0 === _0n) + throw new Error('sign: Creation of signature failed. k is zero'); + const R = Point.fromPrivateKey(k0); + const rx = R.toRawX(); + const k = hasEvenY(R) ? k0 : CURVE.n - k0; + return { R, rx, k }; +} +function finalizeSchnorrSig(R, k, e, d) { + return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes(); +} +async function schnorrSign(message, privateKey, auxRand = utils.randomBytes()) { + const { m, px, d, rand } = initSchnorrSigArgs(message, privateKey, auxRand); + const t = initSchnorrNonce(d, await utils.taggedHash(TAGS.aux, rand)); + const { R, rx, k } = finalizeSchnorrNonce(await utils.taggedHash(TAGS.nonce, t, px, m)); + const e = finalizeSchnorrChallenge(await utils.taggedHash(TAGS.challenge, rx, px, m)); + const sig = finalizeSchnorrSig(R, k, e, d); + const isValid = await schnorrVerify(sig, m, px); + if (!isValid) + throw new Error('sign: Invalid signature produced'); + return sig; +} +function schnorrSignSync(message, privateKey, auxRand = utils.randomBytes()) { + const { m, px, d, rand } = initSchnorrSigArgs(message, privateKey, auxRand); + const t = initSchnorrNonce(d, utils.taggedHashSync(TAGS.aux, rand)); + const { R, rx, k } = finalizeSchnorrNonce(utils.taggedHashSync(TAGS.nonce, t, px, m)); + const e = finalizeSchnorrChallenge(utils.taggedHashSync(TAGS.challenge, rx, px, m)); + const sig = finalizeSchnorrSig(R, k, e, d); + const isValid = schnorrVerifySync(sig, m, px); + if (!isValid) + throw new Error('sign: Invalid signature produced'); + return sig; +} +function initSchnorrVerify(signature, message, publicKey) { + const raw = signature instanceof SchnorrSignature; + const sig = raw ? signature : SchnorrSignature.fromHex(signature); + if (raw) + sig.assertValidity(); + return { + ...sig, + m: ensureBytes(message), + P: normalizePublicKey(publicKey), + }; +} +function finalizeSchnorrVerify(r, P, s, e) { + const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n)); + if (!R || !hasEvenY(R) || R.x !== r) + return false; + return true; +} +async function schnorrVerify(signature, message, publicKey) { + try { + const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey); + const e = finalizeSchnorrChallenge(await utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m)); + return finalizeSchnorrVerify(r, P, s, e); + } + catch (error) { + return false; + } +} +function schnorrVerifySync(signature, message, publicKey) { + try { + const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey); + const e = finalizeSchnorrChallenge(utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m)); + return finalizeSchnorrVerify(r, P, s, e); + } + catch (error) { + return false; + } +} +const schnorr = { + Signature: SchnorrSignature, + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + signSync: schnorrSignSync, + verifySync: schnorrVerifySync, +}; +Point.BASE._setWindowSize(8); +const crypto = { + node: nodeCrypto, + web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined, +}; +const TAGS = { + challenge: 'BIP0340/challenge', + aux: 'BIP0340/aux', + nonce: 'BIP0340/nonce', +}; +const TAGGED_HASH_PREFIXES = {}; +const utils = { + isValidPrivateKey(privateKey) { + try { + normalizePrivateKey(privateKey); + return true; + } + catch (error) { + return false; + } + }, + privateAdd: (privateKey, tweak) => { + const p = normalizePrivateKey(privateKey); + const t = normalizePrivateKey(tweak); + return numTo32b(mod(p + t, CURVE.n)); + }, + privateNegate: (privateKey) => { + const p = normalizePrivateKey(privateKey); + return numTo32b(CURVE.n - p); + }, + pointAddScalar: (p, tweak, isCompressed) => { + const P = Point.fromHex(p); + const t = normalizePrivateKey(tweak); + const Q = Point.BASE.multiplyAndAddUnsafe(P, t, _1n); + if (!Q) + throw new Error('Tweaked point at infinity'); + return Q.toRawBytes(isCompressed); + }, + pointMultiply: (p, tweak, isCompressed) => { + const P = Point.fromHex(p); + const t = bytesToNumber(ensureBytes(tweak)); + return P.multiply(t).toRawBytes(isCompressed); + }, + hashToPrivateKey: (hash) => { + hash = ensureBytes(hash); + if (hash.length < 40 || hash.length > 1024) + throw new Error('Expected 40-1024 bytes of private key as per FIPS 186'); + const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n; + return numTo32b(num); + }, + randomBytes: (bytesLength = 32) => { + if (crypto.web) { + return crypto.web.getRandomValues(new Uint8Array(bytesLength)); + } + else if (crypto.node) { + const { randomBytes } = crypto.node; + return Uint8Array.from(randomBytes(bytesLength)); + } + else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: () => { + return utils.hashToPrivateKey(utils.randomBytes(40)); + }, + bytesToHex, + hexToBytes, + concatBytes, + mod, + invert, + sha256: async (...messages) => { + if (crypto.web) { + const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages)); + return new Uint8Array(buffer); + } + else if (crypto.node) { + const { createHash } = crypto.node; + const hash = createHash('sha256'); + messages.forEach((m) => hash.update(m)); + return Uint8Array.from(hash.digest()); + } + else { + throw new Error("The environment doesn't have sha256 function"); + } + }, + hmacSha256: async (key, ...messages) => { + if (crypto.web) { + const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']); + const message = concatBytes(...messages); + const buffer = await crypto.web.subtle.sign('HMAC', ckey, message); + return new Uint8Array(buffer); + } + else if (crypto.node) { + const { createHmac } = crypto.node; + const hash = createHmac('sha256', key); + messages.forEach((m) => hash.update(m)); + return Uint8Array.from(hash.digest()); + } + else { + throw new Error("The environment doesn't have hmac-sha256 function"); + } + }, + sha256Sync: undefined, + hmacSha256Sync: undefined, + taggedHash: async (tag, ...messages) => { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return utils.sha256(tagP, ...messages); + }, + taggedHashSync: (tag, ...messages) => { + if (typeof utils.sha256Sync !== 'function') + throw new Error('utils.sha256Sync is undefined, you need to set it'); + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = utils.sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return utils.sha256Sync(tagP, ...messages); + }, + precompute(windowSize = 8, point = Point.BASE) { + const cached = point === Point.BASE ? point : new Point(point.x, point.y); + cached._setWindowSize(windowSize); + cached.multiply(_3n); + return cached; + }, +}; + +/** + * A constant for the zero address. + */ +const ZeroAddress = "0x0000000000000000000000000000000000000000"; + +/** + * A constant for the zero hash. + */ +const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; + +/** + * A constant for the BigInt of -1. + */ +const NegativeOne = BigInt(-1); +/** + * A constant for the BigInt of 0. + */ +const Zero = BigInt(0); +/** + * A constant for the BigInt of 1. + */ +const One = BigInt(1); +/** + * A constant for the BigInt of 2. + */ +const Two = BigInt(2); +/** + * A constant for the order N for the secp256k1 curve. + */ +const N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +/** + * A constant for the number of wei in a single ether. + */ +const WeiPerEther = BigInt("1000000000000000000"); +/** + * A constant for the maximum value for a ``uint256``. + */ +const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/** + * A constant for the minimum value for an ``int256``. + */ +const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * NegativeOne; +/** + * A constant for the maximum value for an ``int256``. + */ +const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + +// NFKC (composed) // (decomposed) +/** + * A constant for the ether symbol (normalized using NFKC). + */ +const EtherSymbol = "\u039e"; // "\uD835\uDF63"; +const MessagePrefix = "\x19Ethereum Signed Message:\n"; + +// Constants +const BN_0$2 = BigInt(0); +const BN_1$3 = BigInt(1); +const BN_2$3 = BigInt(2); +const BN_27$1 = BigInt(27); +const BN_28$1 = BigInt(28); +const BN_35$1 = BigInt(35); +const _guard$2 = {}; +class Signature { + #props; + get r() { return getStore(this.#props, "r"); } + set r(value) { + if (dataLength(value) !== 32) { + logger.throwArgumentError("invalid r", "value", value); + } + setStore(this.#props, "r", hexlify(value)); + } + get s() { return getStore(this.#props, "s"); } + set s(value) { + if (dataLength(value) !== 32) { + logger.throwArgumentError("invalid r", "value", value); + } + else if (logger.getBytes(value)[0] & 0x80) { + logger.throwArgumentError("non-canonical s", "value", value); + } + setStore(this.#props, "s", hexlify(value)); + } + get v() { return getStore(this.#props, "v"); } + set v(value) { + const v = logger.getNumber(value, "value"); + if (v !== 27 && v !== 28) { + throw new Error("@TODO"); + } + setStore(this.#props, "v", v); + } + get networkV() { return getStore(this.#props, "networkV"); } + get legacyChainId() { + const v = this.networkV; + if (v == null) { + return null; + } + return Signature.getChainId(v); + } + get yParity() { + if (this.v === 27) { + return 0; + } + return 1; + /* + // When v is 0 or 1 it is the recid directly + if (this.v.isZero()) { return 0; } + if (this.v.eq(1)) { return 1; } + + // Otherwise, odd (e.g. 27) is 0 and even (e.g. 28) is 1 + return this.v.and(1).isZero() ? 1: 0; + */ + } + get yParityAndS() { + // The EIP-2098 compact representation + const yParityAndS = logger.getBytes(this.s); + if (this.yParity) { + yParityAndS[0] |= 0x80; + } + return hexlify(yParityAndS); + } + get compactSerialized() { + return concat([this.r, this.yParityAndS]); + } + get serialized() { + return concat([this.r, this.s, (this.yParity ? "0x1c" : "0x1b")]); + } + constructor(guard, r, s, v) { + logger.assertPrivate(guard, _guard$2, "Signature"); + this.#props = { r, s, v, networkV: null }; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; + } + clone() { + const clone = new Signature(_guard$2, this.r, this.s, this.v); + if (this.networkV) { + setStore(clone.#props, "networkV", this.networkV); + } + return clone; + } + freeze() { + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + toJSON() { + const networkV = this.networkV; + return { + _type: "signature", + networkV: ((networkV != null) ? networkV.toString() : null), + r: this.r, s: this.s, v: this.v, + }; + } + static create() { + return new Signature(_guard$2, ZeroHash, ZeroHash, 27); + } + // Get the chain ID from an EIP-155 v + static getChainId(v) { + const bv = logger.getBigInt(v, "v"); + // The v is not an EIP-155 v, so it is the unspecified chain ID + if ((bv == BN_27$1) || (bv == BN_28$1)) { + return BN_0$2; + } + // Bad value for an EIP-155 v + if (bv < BN_35$1) { + logger.throwArgumentError("invalid EIP-155 v", "v", v); + } + return (bv - BN_35$1) / BN_2$3; + } + // Get the EIP-155 v transformed for a given chainId + static getChainIdV(chainId, v) { + return (logger.getBigInt(chainId) * BN_2$3) + BigInt(35 + v - 27); + } + // Convert an EIP-155 v into a normalized v + static getNormalizedV(v) { + const bv = logger.getBigInt(v); + if (bv == BN_0$2) { + return 27; + } + if (bv == BN_1$3) { + return 28; + } + // Otherwise, EIP-155 v means odd is 27 and even is 28 + return (bv & BN_1$3) ? 27 : 28; + } + static from(sig) { + const throwError = (message) => { + return logger.throwArgumentError(message, "signature", sig); + }; + if (typeof (sig) === "string") { + const bytes = logger.getBytes(sig, "signature"); + if (bytes.length === 64) { + const r = hexlify(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + const v = (s[0] & 0x80) ? 28 : 27; + s[0] &= 0x7f; + return new Signature(_guard$2, r, hexlify(s), v); + } + if (dataLength(sig) !== 65) { + const r = hexlify(sig.slice(0, 32)); + const s = bytes.slice(32, 64); + if (s[0] & 0x80) { + throwError("non-canonical s"); + } + const v = Signature.getNormalizedV(bytes[64]); + return new Signature(_guard$2, r, hexlify(s), v); + } + return throwError("invlaid raw signature length"); + } + if (sig instanceof Signature) { + return sig.clone(); + } + // Get r + const r = sig.r; + if (r == null) { + throwError("missing r"); + } + if (!isHexString(r, 32)) { + throwError("invalid r"); + } + // Get s; by any means necessary (we check consistency below) + const s = (function (s, yParityAndS) { + if (s != null) { + if (!isHexString(s, 32)) { + throwError("invalid s"); + } + return s; + } + if (yParityAndS != null) { + if (!isHexString(yParityAndS, 32)) { + throwError("invalid yParityAndS"); + } + const bytes = logger.getBytes(yParityAndS); + bytes[0] &= 0x7f; + return hexlify(bytes); + } + return throwError("missing s"); + })(sig.s, sig.yParityAndS); + if (logger.getBytes(s)[0] & 0x80) { + throwError("non-canonical s"); + } + // Get v; by any means necessary (we check consistency below) + const { networkV, v } = (function (_v, yParityAndS, yParity) { + if (_v != null) { + const v = logger.getBigInt(_v); + return { + networkV: ((v >= BN_35$1) ? v : undefined), + v: Signature.getNormalizedV(v) + }; + } + if (yParityAndS != null) { + if (!isHexString(yParityAndS, 32)) { + throwError("invalid yParityAndS"); + } + return { v: ((logger.getBytes(yParityAndS)[0] & 0x80) ? 28 : 27) }; + } + if (yParity != null) { + switch (yParity) { + case 0: return { v: 27 }; + case 1: return { v: 28 }; + } + return throwError("invalid yParity"); + } + return throwError("missing v"); + })(sig.v, sig.yParityAndS, sig.yParity); + const result = new Signature(_guard$2, r, s, v); + if (networkV) { + setStore(result.#props, "networkV", networkV); + } + // If multiple of v, yParity, yParityAndS we given, check they match + if ("yParity" in sig && sig.yParity !== result.yParity) { + throwError("yParity mismatch"); + } + else if ("yParityAndS" in sig && sig.yParityAndS !== result.yParityAndS) { + throwError("yParityAndS mismatch"); + } + return result; + } +} + +//const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +// Make noble-secp256k1 sync +utils.hmacSha256Sync = function (key, ...messages) { + return logger.getBytes(computeHmac("sha256", key, concat(messages))); +}; +class SigningKey { + #privateKey; + constructor(privateKey) { + /* @TODO + logger.assertArgument(() => { + if (dataLength(privateKey) !== 32) { throw new Error("bad length"); } + return toBigInt(privateKey) < N; + }, "invalid private key", "privateKey", "[REDACTED]"); + */ + this.#privateKey = hexlify(privateKey); + } + get privateKey() { return this.#privateKey; } + get publicKey() { return SigningKey.computePublicKey(this.#privateKey); } + get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); } + sign(digest) { + /* @TODO + logger.assertArgument(() => (dataLength(digest) === 32), "invalid digest length", "digest", digest); + */ + const [sigDer, recid] = signSync(logger.getBytesCopy(digest), logger.getBytesCopy(this.#privateKey), { + recovered: true, + canonical: true + }); + const sig = Signature$1.fromHex(sigDer); + return Signature.from({ + r: toHex("0x" + sig.r.toString(16), 32), + s: toHex("0x" + sig.s.toString(16), 32), + v: (recid ? 0x1c : 0x1b) + }).freeze(); + } + computeShardSecret(other) { + const pubKey = SigningKey.computePublicKey(other); + return hexlify(getSharedSecret(logger.getBytesCopy(this.#privateKey), pubKey)); + } + static computePublicKey(key, compressed) { + let bytes = logger.getBytes(key, "key"); + if (bytes.length === 32) { + const pubKey = getPublicKey(bytes, !!compressed); + return hexlify(pubKey); + } + if (bytes.length === 64) { + const pub = new Uint8Array(65); + pub[0] = 0x04; + pub.set(bytes, 1); + bytes = pub; + } + const point = Point.fromHex(bytes); + return hexlify(point.toRawBytes(compressed)); + } + static recoverPublicKey(digest, signature) { + const sig = Signature.from(signature); + const der = Signature$1.fromCompact(logger.getBytesCopy(concat([sig.r, sig.s]))).toDERRawBytes(); + const pubKey = recoverPublicKey(logger.getBytesCopy(digest), der, sig.yParity); + if (pubKey != null) { + return hexlify(pubKey); + } + return logger.throwArgumentError("invalid signautre for digest", "signature", signature); + } + static _addPoints(p0, p1, compressed) { + const pub0 = Point.fromHex(SigningKey.computePublicKey(p0).substring(2)); + const pub1 = Point.fromHex(SigningKey.computePublicKey(p1).substring(2)); + return "0x" + pub0.add(pub1).toHex(!!compressed); + } +} +/* +const key = new SigningKey("0x1234567890123456789012345678901234567890123456789012345678901234"); +console.log(key); +console.log(key.sign("0x1234567890123456789012345678901234567890123456789012345678901234")); +{ + const privKey = "0x1234567812345678123456781234567812345678123456781234567812345678"; + const signingKey = new SigningKey(privKey); + console.log("0", signingKey, signingKey.publicKey, signingKey.publicKeyCompressed); + + let pubKey = SigningKey.computePublicKey(privKey); + let pubKeyComp = SigningKey.computePublicKey(privKey, true); + let pubKeyRaw = "0x" + SigningKey.computePublicKey(privKey).substring(4); + console.log("A", pubKey, pubKeyComp); + + let a = SigningKey.computePublicKey(pubKey); + let b = SigningKey.computePublicKey(pubKey, true); + console.log("B", a, b); + + a = SigningKey.computePublicKey(pubKeyComp); + b = SigningKey.computePublicKey(pubKeyComp, true); + console.log("C", a, b); + + a = SigningKey.computePublicKey(pubKeyRaw); + b = SigningKey.computePublicKey(pubKeyRaw, true); + console.log("D", a, b); + + const digest = "0x1122334411223344112233441122334411223344112233441122334411223344"; + const sig = signingKey.sign(digest); + console.log("SS", sig, sig.r, sig.s, sig.yParity); + + console.log("R", SigningKey.recoverPublicKey(digest, sig)); +} +*/ + +// We import all these so we can export lock() +function lock() { + computeHmac.lock(); + keccak256.lock(); + pbkdf2.lock(); + randomBytes.lock(); + ripemd160.lock(); + scrypt.lock(); + scryptSync.lock(); + sha256.lock(); + sha512.lock(); +} + +function id(value) { + return keccak256(toUtf8Bytes(value)); +} + +//import { ens_normalize } from "./ens-normalize/lib"; +// @TOOD: +function ens_normalize(name) { + return name; +} +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + if (comp.length === 0) { + throw new Error("invalid ENS name; empty component"); + } + return comp; +} +function ensNameSplit(name) { + const bytes = toUtf8Bytes(ens_normalize(name)); + const comps = []; + if (name.length === 0) { + return comps; + } + let last = 0; + for (let i = 0; i < bytes.length; i++) { + const d = bytes[i]; + // A separator (i.e. "."); copy this component + if (d === 0x2e) { + comps.push(checkComponent(bytes.slice(last, i))); + last = i + 1; + } + } + // There was a stray separator at the end of the name + if (last >= bytes.length) { + throw new Error("invalid ENS name; empty component"); + } + comps.push(checkComponent(bytes.slice(last))); + return comps; +} +function ensNormalize(name) { + return ensNameSplit(name).map((comp) => toUtf8String(comp)).join("."); +} +function isValidName(name) { + try { + return (ensNameSplit(name).length !== 0); + } + catch (error) { } + return false; +} +function namehash(name) { + /* istanbul ignore if */ + if (typeof (name) !== "string") { + logger.throwArgumentError("invalid ENS name; not a string", "name", name); + } + let result = Zeros; + const comps = ensNameSplit(name); + while (comps.length) { + result = keccak256(concat([result, keccak256((comps.pop()))])); + } + return hexlify(result); +} +function dnsEncode(name) { + return hexlify(concat(ensNameSplit(name).map((comp) => { + // DNS does not allow components over 63 bytes in length + if (comp.length > 63) { + throw new Error("invalid DNS encoded entry; length exceeds 63 bytes"); + } + const bytes = new Uint8Array(comp.length + 1); + bytes.set(comp, 1); + bytes[0] = bytes.length - 1; + return bytes; + }))) + "00"; +} + +function hashMessage(message) { + if (typeof (message) === "string") { + message = toUtf8Bytes(message); + } + return keccak256(concat([ + toUtf8Bytes(MessagePrefix), + toUtf8Bytes(String(message.length)), + message + ])); +} + +const regexBytes = new RegExp("^bytes([0-9]+)$"); +const regexNumber = new RegExp("^(u?int)([0-9]*)$"); +const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); +function _pack(type, value, isArray) { + switch (type) { + case "address": + if (isArray) { + return logger.getBytes(zeroPadValue(value, 32)); + } + return logger.getBytes(value); + case "string": + return toUtf8Bytes(value); + case "bytes": + return logger.getBytes(value); + case "bool": + value = (!!value ? "0x01" : "0x00"); + if (isArray) { + return logger.getBytes(zeroPadValue(value, 32)); + } + return logger.getBytes(value); + } + let match = type.match(regexNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) { + return logger.throwArgumentError("invalid number type", "type", type); + } + if (isArray) { + size = 256; + } + value = toTwos(value, size); + return logger.getBytes(zeroPadValue(toArray(value), size / 8)); + } + match = type.match(regexBytes); + if (match) { + const size = parseInt(match[1]); + if (String(size) !== match[1] || size === 0 || size > 32) { + return logger.throwArgumentError("invalid bytes type", "type", type); + } + if (dataLength(value) !== size) { + return logger.throwArgumentError(`invalid value for ${type}`, "value", value); + } + if (isArray) { + return logger.getBytes(zeroPadBytes(value, 32)); + } + return value; + } + match = type.match(regexArray); + if (match && Array.isArray(value)) { + const baseType = match[1]; + const count = parseInt(match[2] || String(value.length)); + if (count != value.length) { + logger.throwArgumentError(`invalid array length for ${type}`, "value", value); + } + const result = []; + value.forEach(function (value) { + result.push(_pack(baseType, value, true)); + }); + return logger.getBytes(concat(result)); + } + return logger.throwArgumentError("invalid type", "type", type); +} +// @TODO: Array Enum +function solidityPacked(types, values) { + if (types.length != values.length) { + logger.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values); + } + const tight = []; + types.forEach(function (type, index) { + tight.push(_pack(type, values[index])); + }); + return hexlify(concat(tight)); +} +/** + * Computes the non-standard packed (tightly packed) keccak256 hash of + * the values given the types. + * + * @param {Array} types - The Solidity types to interpret each value as [default: bar] + * @param {Array} values - The values to pack + * + * @returns: {HexString} the hexstring of the hash + * @example: + * solidityPackedKeccak256([ "address", "uint" ], [ "0x1234", 45 ]); + * //_result: + * + * @see https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode + */ +function solidityPackedKeccak256(types, values) { + return keccak256(solidityPacked(types, values)); +} +/** + * Test Function, for fun + * + * @param foo - something fun + */ +function test(foo) { +} +function solidityPackedSha256(types, values) { + return sha256(solidityPacked(types, values)); +} + +//import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer"; +const padding = new Uint8Array(32); +padding.fill(0); +const BN__1 = BigInt(-1); +const BN_0$1 = BigInt(0); +const BN_1$2 = BigInt(1); +const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +; +; +function hexPadRight(value) { + const bytes = logger.getBytes(value); + const padOffset = bytes.length % 32; + if (padOffset) { + return concat([bytes, padding.slice(padOffset)]); + } + return hexlify(bytes); +} +const hexTrue = toHex(BN_1$2, 32); +const hexFalse = toHex(BN_0$1, 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" +}; +const domainFieldNames = [ + "name", "version", "chainId", "verifyingContract", "salt" +]; +function checkString(key) { + return function (value) { + if (typeof (value) !== "string") { + logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + } + return value; + }; +} +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function (value) { + return logger.getBigInt(value, "domain.chainId"); + }, + verifyingContract: function (value) { + try { + return getAddress(value).toLowerCase(); + } + catch (error) { } + return logger.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function (value) { + const bytes = logger.getBytes(value, "domain.salt"); + if (bytes.length !== 32) { + logger.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); + } + return hexlify(bytes); + } +}; +function getBaseEncoder(type) { + // intXX and uintXX + { + const match = type.match(/^(u?)int(\d*)$/); + if (match) { + const signed = (match[1] === ""); + const width = parseInt(match[2] || "256"); + if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) { + logger.throwArgumentError("invalid numeric width", "type", type); + } + const boundsUpper = mask(BN_MAX_UINT256$1, signed ? (width - 1) : width); + const boundsLower = signed ? ((boundsUpper + BN_1$2) * BN__1) : BN_0$1; + return function (_value) { + const value = logger.getBigInt(_value, "value"); + if (value < boundsLower || value > boundsUpper) { + logger.throwArgumentError(`value out-of-bounds for ${type}`, "value", value); + } + return toHex(toTwos(value, 256), 32); + }; + } + } + // bytesXX + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + if (width === 0 || width > 32 || match[1] !== String(width)) { + logger.throwArgumentError("invalid bytes width", "type", type); + } + return function (value) { + const bytes = logger.getBytes(value); + if (bytes.length !== width) { + logger.throwArgumentError(`invalid length for ${type}`, "value", value); + } + return hexPadRight(value); + }; + } + } + switch (type) { + case "address": return function (value) { + return zeroPadValue(getAddress(value), 32); + }; + case "bool": return function (value) { + return ((!value) ? hexFalse : hexTrue); + }; + case "bytes": return function (value) { + return keccak256(value); + }; + case "string": return function (value) { + return id(value); + }; + } + return null; +} +function encodeType(name, fields) { + return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`; +} +class TypedDataEncoder { + primaryType; + #types; + get types() { + return JSON.parse(this.#types); + } + #fullTypes; + #encoderCache; + constructor(types) { + this.#types = JSON.stringify(types); + this.#fullTypes = new Map(); + this.#encoderCache = new Map(); + // Link struct types to their direct child structs + const links = new Map(); + // Link structs to structs which contain them as a child + const parents = new Map(); + // Link all subtypes within a given struct + const subtypes = new Map(); + Object.keys(types).forEach((type) => { + links.set(type, new Set()); + parents.set(type, []); + subtypes.set(type, new Set()); + }); + for (const name in types) { + const uniqueNames = new Set(); + for (const field of types[name]) { + // Check each field has a unique name + if (uniqueNames.has(field.name)) { + logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types); + } + uniqueNames.add(field.name); + // Get the base type (drop any array specifiers) + const baseType = (field.type.match(/^([^\x5b]*)(\x5b|$)/))[1] || null; + if (baseType === name) { + logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types); + } + // Is this a base encoding type? + const encoder = getBaseEncoder(baseType); + if (encoder) { + continue; + } + if (!parents.has(baseType)) { + logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types); + } + // Add linkage + parents.get(baseType).push(name); + links.get(name).add(baseType); + } + } + // Deduce the primary type + const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0)); + if (primaryTypes.length === 0) { + logger.throwArgumentError("missing primary type", "types", types); + } + else if (primaryTypes.length > 1) { + logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", types); + } + defineProperties(this, { primaryType: primaryTypes[0] }); + // Check for circular type references + function checkCircular(type, found) { + if (found.has(type)) { + logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types); + } + found.add(type); + for (const child of links.get(type)) { + if (!parents.has(child)) { + continue; + } + // Recursively check children + checkCircular(child, found); + // Mark all ancestors as having this decendant + for (const subtype of found) { + subtypes.get(subtype).add(child); + } + } + found.delete(type); + } + checkCircular(this.primaryType, new Set()); + // Compute each fully describe type + for (const [name, set] of subtypes) { + const st = Array.from(set); + st.sort(); + this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join("")); + } + } + getEncoder(type) { + let encoder = this.#encoderCache.get(type); + if (!encoder) { + encoder = this.#getEncoder(type); + this.#encoderCache.set(type, encoder); + } + return encoder; + } + #getEncoder(type) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return encoder; + } + } + // Array + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const subEncoder = this.getEncoder(subtype); + const length = parseInt(match[3]); + return (value) => { + if (length >= 0 && value.length !== length) { + logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + let result = value.map(subEncoder); + if (this.#fullTypes.has(subtype)) { + result = result.map(keccak256); + } + return keccak256(concat(result)); + }; + } + // Struct + const fields = this.types[type]; + if (fields) { + const encodedType = id(this.#fullTypes.get(type)); + return (value) => { + const values = fields.map(({ name, type }) => { + const result = this.getEncoder(type)(value[name]); + if (this.#fullTypes.has(type)) { + return keccak256(result); + } + return result; + }); + values.unshift(encodedType); + return concat(values); + }; + } + return logger.throwArgumentError(`unknown type: ${type}`, "type", type); + } + encodeType(name) { + const result = this.#fullTypes.get(name); + if (!result) { + return logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name); + } + return result; + } + encodeData(type, value) { + return this.getEncoder(type)(value); + } + hashStruct(name, value) { + return keccak256(this.encodeData(name, value)); + } + encode(value) { + return this.encodeData(this.primaryType, value); + } + hash(value) { + return this.hashStruct(this.primaryType, value); + } + _visit(type, value, callback) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return callback(type, value); + } + } + // Array + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const length = parseInt(match[3]); + if (length >= 0 && value.length !== length) { + logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + return value.map((v) => this._visit(subtype, v, callback)); + } + // Struct + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name, type }) => { + accum[name] = this._visit(type, value[name], callback); + return accum; + }, {}); + } + return logger.throwArgumentError(`unknown type: ${type}`, "type", type); + } + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + static from(types) { + return new TypedDataEncoder(types); + } + static getPrimaryType(types) { + return TypedDataEncoder.from(types).primaryType; + } + static hashStruct(name, types, value) { + return TypedDataEncoder.from(types).hashStruct(name, value); + } + static hashDomain(domain) { + const domainFields = []; + for (const name in domain) { + const type = domainFieldTypes[name]; + if (!type) { + logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); + } + domainFields.push({ name, type }); + } + domainFields.sort((a, b) => { + return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); + }); + return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain); + } + static encode(domain, types, value) { + return concat([ + "0x1901", + TypedDataEncoder.hashDomain(domain), + TypedDataEncoder.from(types).hash(value) + ]); + } + static hash(domain, types, value) { + return keccak256(TypedDataEncoder.encode(domain, types, value)); + } + // Replaces all address types with ENS names with their looked up address + static async resolveNames(domain, types, value, resolveName) { + // Make a copy to isolate it from the object passed in + domain = Object.assign({}, domain); + // Look up all ENS names + const ensCache = {}; + // Do we need to look up the domain's verifyingContract? + if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) { + ensCache[domain.verifyingContract] = "0x"; + } + // We are going to use the encoder to visit all the base values + const encoder = TypedDataEncoder.from(types); + // Get a list of all the addresses + encoder.visit(value, (type, value) => { + if (type === "address" && !isHexString(value, 20)) { + ensCache[value] = "0x"; + } + return value; + }); + // Lookup each name + for (const name in ensCache) { + ensCache[name] = await resolveName(name); + } + // Replace the domain verifyingContract if needed + if (domain.verifyingContract && ensCache[domain.verifyingContract]) { + domain.verifyingContract = ensCache[domain.verifyingContract]; + } + // Replace all ENS names with their address + value = encoder.visit(value, (type, value) => { + if (type === "address" && ensCache[value]) { + return ensCache[value]; + } + return value; + }); + return { domain, value }; + } + static getPayload(domain, types, value) { + // Validate the domain fields + TypedDataEncoder.hashDomain(domain); + // Derive the EIP712Domain Struct reference type + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name) => { + const value = domain[name]; + if (value == null) { + return; + } + domainValues[name] = domainChecks[name](value); + domainTypes.push({ name, type: domainFieldTypes[name] }); + }); + const encoder = TypedDataEncoder.from(types); + const typesWithDomain = Object.assign({}, types); + if (typesWithDomain.EIP712Domain) { + logger.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types); + } + else { + typesWithDomain.EIP712Domain = domainTypes; + } + // Validate the data structures and types + encoder.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder.primaryType, + message: encoder.visit(value, (type, value) => { + // bytes + if (type.match(/^bytes(\d*)/)) { + return hexlify(logger.getBytes(value)); + } + // uint or int + if (type.match(/^u?int/)) { + return logger.getBigInt(value).toString(); + } + switch (type) { + case "address": + return value.toLowerCase(); + case "bool": + return !!value; + case "string": + if (typeof (value) !== "string") { + logger.throwArgumentError(`invalid string`, "value", value); + } + return value; + } + return logger.throwArgumentError("unsupported type", "type", type); + }) + }; + } +} + +class LogDescription { + fragment; + name; + signature; + topic; + args; + constructor(fragment, topic, args) { + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment, name, signature, topic, args + }); + } +} +class TransactionDescription { + fragment; + name; + args; + signature; + selector; + value; + constructor(fragment, selector, args, value) { + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment, name, args, signature, selector, value + }); + } +} +class ErrorDescription { + fragment; + name; + args; + signature; + selector; + constructor(fragment, selector, args) { + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment, name, args, signature, selector + }); + } +} +class Indexed { + hash; + _isIndexed; + static isIndexed(value) { + return !!(value && value._isIndexed); + } + constructor(hash) { + defineProperties(this, { hash, _isIndexed: true }); + } +} +// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require +const PanicReasons = { + "0": "generic panic", + "1": "assert(false)", + "17": "arithmetic overflow", + "18": "division or modulo by zero", + "33": "enum overflow", + "34": "invalid encoded storage byte array accessed", + "49": "out-of-bounds array access; popping on an empty array", + "50": "out-of-bounds access of an array or bytesN", + "65": "out of memory", + "81": "uninitialized function", +}; +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: ["string"], + reason: (message) => { + return `reverted with reason string ${JSON.stringify(message)}`; + } + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: ["uint256"], + reason: (code) => { + let reason = "unknown panic code"; + if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) { + reason = PanicReasons[code.toString()]; + } + return `reverted with panic code 0x${code.toString(16)} (${reason})`; + } + } +}; +class Interface { + fragments; + deploy; + #errors; + #events; + #functions; + // #structs: Map; + #abiCoder; + constructor(fragments) { + let abi = []; + if (typeof (fragments) === "string") { + abi = JSON.parse(fragments); + } + else { + abi = fragments; + } + this.#functions = new Map(); + this.#errors = new Map(); + this.#events = new Map(); + // this.#structs = new Map(); + defineProperties(this, { + fragments: Object.freeze(abi.map((f) => Fragment.from(f)).filter((f) => (f != null))), + }); + this.#abiCoder = this.getAbiCoder(); + // Add all fragments by their signature + this.fragments.forEach((fragment) => { + let bucket; + switch (fragment.type) { + case "constructor": + if (this.deploy) { + logger.warn("duplicate definition - constructor"); + return; + } + //checkNames(fragment, "input", fragment.inputs); + defineProperties(this, { deploy: fragment }); + return; + case "function": + //checkNames(fragment, "input", fragment.inputs); + //checkNames(fragment, "output", (fragment).outputs); + bucket = this.#functions; + break; + case "event": + //checkNames(fragment, "input", fragment.inputs); + bucket = this.#events; + break; + case "error": + bucket = this.#errors; + break; + default: + return; + } + const signature = fragment.format(); + if (bucket.has(signature)) { + logger.warn("duplicate definition - " + signature); + return; + } + bucket.set(signature, fragment); + }); + // If we do not have a constructor add a default + if (!this.deploy) { + defineProperties(this, { + deploy: ConstructorFragment.fromString("constructor()") + }); + } + } + // @TODO: multi sig? + format(format) { + if (!format) { + format = FormatType.full; + } + if (format === FormatType.sighash) { + logger.throwArgumentError("interface does not support formatting sighash", "format", format); + } + const abi = this.fragments.map((f) => f.format(format)); + // We need to re-bundle the JSON fragments a bit + if (format === FormatType.json) { + return JSON.stringify(abi.map((j) => JSON.parse(j))); + } + return abi; + } + getAbiCoder() { + return defaultAbiCoder; + } + //static getAddress(address: string): string { + // return getAddress(address); + //} + //static getSelector(fragment: ErrorFragment | FunctionFragment): string { + // return dataSlice(id(fragment.format()), 0, 4); + //} + //static getEventTopic(eventFragment: EventFragment): string { + // return id(eventFragment.format()); + //} + // Find a function definition by any means necessary (unless it is ambiguous) + #getFunction(key, values, forceUnique) { + // Selector + if (isHexString(key)) { + const selector = key.toLowerCase(); + for (const fragment of this.#functions.values()) { + if (selector === this.getSelector(fragment)) { + return fragment; + } + } + logger.throwArgumentError("no matching function", "selector", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#functions) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + const lastValue = (values.length > 0) ? values[values.length - 1] : null; + let valueLength = values.length; + let allowOptions = true; + if (Typed.isTyped(lastValue) && lastValue.type === "overrides") { + allowOptions = false; + valueLength--; + } + // Remove all matches that don't have a compatible length. The args + // may contain an overrides, so the match may have n or n - 1 parameters + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs.length; + if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!Typed.isTyped(values[j])) { + continue; + } + // We are past the inputs + if (j >= inputs.length) { + if (values[j].type === "overrides") { + continue; + } + matching.splice(i, 1); + break; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + // We found a single matching signature with an overrides, but the + // last value is something that cannot possibly be an options + if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { + const lastArg = values[values.length - 1]; + if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== "object") { + matching.splice(0, 1); + } + } + if (matching.length === 0) { + logger.throwArgumentError("no matching function", "name", key); + } + else if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", "); + logger.throwArgumentError(`multiple matching functions (i.e. ${matchStr})`, "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#functions.get(FunctionFragment.fromString(key).format()); + if (result) { + return result; + } + return logger.throwArgumentError("no matching function", "signature", key); + } + getFunctionName(key) { + return (this.#getFunction(key, null, false)).name; + } + getFunction(key, values) { + return this.#getFunction(key, values || null, true); + } + // Find an event definition by any means necessary (unless it is ambiguous) + #getEvent(key, values, forceUnique) { + // EventTopic + if (isHexString(key)) { + const eventTopic = key.toLowerCase(); + for (const fragment of this.#events.values()) { + if (eventTopic === this.getEventTopic(fragment)) { + return fragment; + } + } + logger.throwArgumentError("no matching event", "eventTopic", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#events) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + // Remove all matches that don't have a compatible length. + for (let i = matching.length - 1; i >= 0; i--) { + if (matching[i].inputs.length < values.length) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!Typed.isTyped(values[j])) { + continue; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 0) { + logger.throwArgumentError("no matching event", "name", key); + } + else if (matching.length > 1 && forceUnique) { + // @TODO: refine by Typed + logger.throwArgumentError("multiple matching events", "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#events.get(EventFragment.fromString(key).format()); + if (result) { + return result; + } + return logger.throwArgumentError("no matching event", "signature", key); + } + getEventName(key) { + return (this.#getEvent(key, null, false)).name; + } + getEvent(key, values) { + return this.#getEvent(key, values || null, true); + } + // Find a function definition by any means necessary (unless it is ambiguous) + getError(key, values) { + if (isHexString(key)) { + const selector = key.toLowerCase(); + if (BuiltinErrors[selector]) { + return ErrorFragment.fromString(BuiltinErrors[selector].signature); + } + for (const fragment of this.#errors.values()) { + if (selector === this.getSelector(fragment)) { + return fragment; + } + } + logger.throwArgumentError("no matching error", "selector", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#errors) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (matching.length === 0) { + if (key === "Error") { + return ErrorFragment.fromString("error Error(string)"); + } + if (key === "Panic") { + return ErrorFragment.fromString("error Panic(uint256)"); + } + logger.throwArgumentError("no matching error", "name", key); + } + else if (matching.length > 1) { + // @TODO: refine by Typed + logger.throwArgumentError("multiple matching errors", "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + key = ErrorFragment.fromString(key).format(); + if (key === "Error(string)") { + return ErrorFragment.fromString("error Error(string)"); + } + if (key === "Panic(uint256)") { + return ErrorFragment.fromString("error Panic(uint256)"); + } + const result = this.#errors.get(key); + if (result) { + return result; + } + return logger.throwArgumentError("no matching error", "signature", key); + } + // Get the 4-byte selector used by Solidity to identify a function + getSelector(fragment) { + /* + if (typeof(fragment) === "string") { + const matches: Array = [ ]; + + try { matches.push(this.getFunction(fragment)); } catch (error) { } + try { matches.push(this.getError(fragment)); } catch (_) { } + + if (matches.length === 0) { + logger.throwArgumentError("unknown fragment", "key", fragment); + } else if (matches.length > 1) { + logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment); + } + + fragment = matches[0]; + } + */ + return dataSlice(id(fragment.format()), 0, 4); + } + // Get the 32-byte topic hash used by Solidity to identify an event + getEventTopic(fragment) { + //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); } + return id(fragment.format()); + } + _decodeParams(params, data) { + return this.#abiCoder.decode(params, data); + } + _encodeParams(params, values) { + return this.#abiCoder.encode(params, values); + } + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); + } + decodeErrorResult(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getError(fragment); + } + if (dataSlice(data, 0, 4) !== this.getSelector(fragment)) { + logger.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", data); + } + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + } + encodeErrorResult(fragment, values) { + if (typeof (fragment) === "string") { + fragment = this.getError(fragment); + } + return concat([ + this.getSelector(fragment), + this._encodeParams(fragment.inputs, values || []) + ]); + } + // Decode the data for a function call (e.g. tx.data) + decodeFunctionData(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + if (dataSlice(data, 0, 4) !== this.getSelector(fragment)) { + logger.throwArgumentError(`data signature does not match function ${fragment.name}.`, "data", data); + } + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + } + // Encode the data for a function call (e.g. tx.data) + encodeFunctionData(fragment, values) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + return concat([ + this.getSelector(fragment), + this._encodeParams(fragment.inputs, values || []) + ]); + } + // Decode the result from a function call (e.g. from eth_call) + decodeFunctionResult(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + let message = "invalid length for result data"; + const bytes = logger.getBytesCopy(data); + if ((bytes.length % 32) === 0) { + try { + return this.#abiCoder.decode(fragment.outputs, bytes); + } + catch (error) { + message = "could not decode result data"; + } + } + // Call returned data with no error, but the data is junk + return logger.throwError(message, "BAD_DATA", { + value: hexlify(bytes), + info: { method: fragment.name, signature: fragment.format() } + }); + } + makeError(fragment, _data, tx) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + const data = logger.getBytes(_data); + let args = undefined; + if (tx) { + try { + args = this.#abiCoder.decode(fragment.inputs, tx.data || "0x"); + } + catch (error) { + console.log(error); + } + } + let errorArgs = undefined; + let errorName = undefined; + let errorSignature = undefined; + let reason = "unknown reason"; + if (data.length === 0) { + reason = "missing error reason"; + } + else if ((data.length % 32) === 4) { + const selector = hexlify(data.slice(0, 4)); + const builtin = BuiltinErrors[selector]; + if (builtin) { + try { + errorName = builtin.name; + errorSignature = builtin.signature; + errorArgs = this.#abiCoder.decode(builtin.inputs, data.slice(4)); + reason = builtin.reason(...errorArgs); + } + catch (error) { + console.log(error); // @TODO: remove + } + } + else { + reason = "unknown custom error"; + try { + const error = this.getError(selector); + errorName = error.name; + errorSignature = error.format(); + reason = `custom error: ${errorSignature}`; + try { + errorArgs = this.#abiCoder.decode(error.inputs, data.slice(4)); + } + catch (error) { + reason = `custom error: ${errorSignature} (coult not decode error data)`; + } + } + catch (error) { + console.log(error); // @TODO: remove + } + } + } + return logger.makeError("call revert exception", "CALL_EXCEPTION", { + data: hexlify(data), transaction: null, + method: fragment.name, signature: fragment.format(), args, + errorArgs, errorName, errorSignature, reason + }); + } + // Encode the result for a function call (e.g. for eth_call) + encodeFunctionResult(functionFragment, values) { + if (typeof (functionFragment) === "string") { + functionFragment = this.getFunction(functionFragment); + } + return hexlify(this.#abiCoder.encode(functionFragment.outputs, values || [])); + } + /* + spelunk(inputs: Array, values: ReadonlyArray, processfunc: (type: string, value: any) => Promise): Promise> { + const promises: Array> = [ ]; + const process = function(type: ParamType, value: any): any { + if (type.baseType === "array") { + return descend(type.child + } + if (type. === "address") { + } + }; + + const descend = function (inputs: Array, values: ReadonlyArray) { + if (inputs.length !== values.length) { throw new Error("length mismatch"); } + + }; + + const result: Array = [ ]; + values.forEach((value, index) => { + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + } + */ + // Create the filter for the event with search criteria (e.g. for eth_filterLog) + encodeFilterTopics(eventFragment, values) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (values.length > eventFragment.inputs.length) { + logger.throwError("too many arguments for " + eventFragment.format(), "UNEXPECTED_ARGUMENT", { + count: values.length, + expectedCount: eventFragment.inputs.length + }); + } + const topics = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + // @TODO: Use the coders for this; to properly support tuples, etc. + const encodeTopic = (param, value) => { + if (param.type === "string") { + return id(value); + } + else if (param.type === "bytes") { + return keccak256(hexlify(value)); + } + if (param.type === "bool" && typeof (value) === "boolean") { + value = (value ? "0x01" : "0x00"); + } + if (param.type.match(/^u?int/)) { + value = toHex(value); + } + // Check addresses are valid + if (param.type === "address") { + this.#abiCoder.encode(["address"], [value]); + } + return zeroPadValue(hexlify(value), 32); + //@TOOD should probably be return toHex(value, 32) + }; + values.forEach((value, index) => { + const param = eventFragment.inputs[index]; + if (!param.indexed) { + if (value != null) { + logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value); + } + return; + } + if (value == null) { + topics.push(null); + } + else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } + else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } + else { + topics.push(encodeTopic(param, value)); + } + }); + // Trim off trailing nulls + while (topics.length && topics[topics.length - 1] === null) { + topics.pop(); + } + return topics; + } + encodeEventLog(eventFragment, values) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + if (values.length !== eventFragment.inputs.length) { + logger.throwArgumentError("event arguments/values mismatch", "values", values); + } + eventFragment.inputs.forEach((param, index) => { + const value = values[index]; + if (param.indexed) { + if (param.type === "string") { + topics.push(id(value)); + } + else if (param.type === "bytes") { + topics.push(keccak256(value)); + } + else if (param.baseType === "tuple" || param.baseType === "array") { + // @TODO + throw new Error("not implemented"); + } + else { + topics.push(this.#abiCoder.encode([param.type], [value])); + } + } + else { + dataTypes.push(param); + dataValues.push(value); + } + }); + return { + data: this.#abiCoder.encode(dataTypes, dataValues), + topics: topics + }; + } + // Decode a filter for the event and the search criteria + decodeEventLog(eventFragment, data, topics) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (topics != null && !eventFragment.anonymous) { + const eventTopic = this.getEventTopic(eventFragment); + if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== eventTopic) { + logger.throwArgumentError("fragment/topic mismatch", "topics[0]", topics[0]); + } + topics = topics.slice(1); + } + const indexed = []; + const nonIndexed = []; + const dynamic = []; + eventFragment.inputs.forEach((param, index) => { + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(ParamType.fromObject({ type: "bytes32", name: param.name })); + dynamic.push(true); + } + else { + indexed.push(param); + dynamic.push(false); + } + } + else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)) : null; + const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); + //const result: (Array & { [ key: string ]: any }) = [ ]; + const values = []; + const keys = []; + let nonIndexedIndex = 0, indexedIndex = 0; + eventFragment.inputs.forEach((param, index) => { + let value = null; + if (param.indexed) { + if (resultIndexed == null) { + value = new Indexed(null); + } + else if (dynamic[index]) { + value = new Indexed(resultIndexed[indexedIndex++]); + } + else { + try { + value = resultIndexed[indexedIndex++]; + } + catch (error) { + value = error; + } + } + } + else { + try { + value = resultNonIndexed[nonIndexedIndex++]; + } + catch (error) { + value = error; + } + } + values.push(value); + keys.push(param.name || null); + }); + return Result.fromItems(values, keys); + } + // Given a transaction, find the matching function fragment (if any) and + // determine all its properties and call parameters + parseTransaction(tx) { + const data = logger.getBytes(tx.data, "tx.data"); + const value = logger.getBigInt((tx.value != null) ? tx.value : 0, "tx.value"); + const fragment = this.getFunction(hexlify(data.slice(0, 4))); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); + return new TransactionDescription(fragment, this.getSelector(fragment), args, value); + } + // @TODO + //parseCallResult(data: BytesLike): ?? + // Given an event log, find the matching event fragment (if any) and + // determine all its properties and values + parseLog(log) { + const fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; + } + // @TODO: If anonymous, and the only method, and the input count matches, should we parse? + // Probably not, because just because it is the only event in the ABI does + // not mean we have the full ABI; maybe just a fragment? + return new LogDescription(fragment, this.getEventTopic(fragment), this.decodeEventLog(fragment, log.data, log.topics)); + } + parseError(data) { + const hexData = hexlify(data); + const fragment = this.getError(dataSlice(hexData, 0, 4)); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4)); + return new ErrorDescription(fragment, this.getSelector(fragment), args); + } + static from(value) { + // Already an Interface, which is immutable + if (value instanceof Interface) { + return value; + } + // JSON + if (typeof (value) === "string") { + return new Interface(JSON.parse(value)); + } + // Maybe an interface from an older version, or from a symlinked copy + if (typeof (value.format) === "function") { + return new Interface(value.format(FormatType.json)); + } + // Array of fragments + return new Interface(value); + } +} + +function accessSetify(addr, storageKeys) { + return { + address: getAddress(addr), + storageKeys: (storageKeys || []).map((storageKey, index) => { + if (dataLength(storageKey) !== 32) { + //logger.throwArgumentError("invalid access list storageKey", `accessList[${ addr }> + throw new Error(""); + } + return storageKey.toLowerCase(); + }) + }; +} +function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index) => { + if (Array.isArray(set)) { + if (set.length > 2) { + //logger.throwArgumentError("access list expected to be [ address, storageKeys[> + throw new Error(""); + } + return accessSetify(set[0], set[1]); + } + return accessSetify(set.address, set.storageKeys); + }); + } + const result = Object.keys(value).map((addr) => { + const storageKeys = value[addr].reduce((accum, storageKey) => { + accum[storageKey] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); + }); + result.sort((a, b) => (a.address.localeCompare(b.address))); + return result; +} + +function computeAddress(key) { + const publicKey = SigningKey.computePublicKey(key, false); + return getAddress(keccak256("0x" + publicKey.substring(4)).substring(26)); +} +function recoverAddress(digest, signature) { + return computeAddress(SigningKey.recoverPublicKey(digest, signature)); +} + +const BN_0 = BigInt(0); +const BN_2$2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +function handleAddress(value) { + if (value === "0x") { + return null; + } + return getAddress(value); +} +function handleData(value, param) { + try { + return hexlify(value); + } + catch (error) { + return logger.throwArgumentError("invalid data", param, value); + } +} +function handleAccessList(value, param) { + try { + return accessListify(value); + } + catch (error) { + return logger.throwArgumentError("invalid accessList", param, value); + } +} +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; + } + return logger.getNumber(_value, param); +} +function handleUint(_value, param) { + if (_value === "0x") { + return BN_0; + } + const value = logger.getBigInt(_value, param); + if (value > BN_MAX_UINT) { + logger.throwArgumentError("value exceeds uint size", param, value); + } + return value; +} +function formatNumber(_value, name) { + const value = logger.getBigInt(_value, "value"); + const result = toArray(value); + if (result.length > 32) { + logger.throwArgumentError(`value too large`, `tx.${name}`, value); + } + return result; +} +function formatAccessList(value) { + return accessListify(value).map((set) => [set.address, set.storageKeys]); +} +function _parseLegacy(data) { + const fields = decodeRlp(data); + if (!Array.isArray(fields) || (fields.length !== 9 && fields.length !== 6)) { + return logger.throwArgumentError("invalid field count for legacy transaction", "data", data); + } + const tx = { + type: 0, + nonce: handleNumber(fields[0], "nonce"), + gasPrice: handleUint(fields[1], "gasPrice"), + gasLimit: handleUint(fields[2], "gasLimit"), + to: handleAddress(fields[3]), + value: handleUint(fields[4], "value"), + data: handleData(fields[5], "dta"), + chainId: BN_0 + }; + // Legacy unsigned transaction + if (fields.length === 6) { + return tx; + } + const v = handleUint(fields[6], "v"); + const r = handleUint(fields[7], "r"); + const s = handleUint(fields[8], "s"); + if (r === BN_0 && s === BN_0) { + // EIP-155 unsigned transaction + tx.chainId = v; + } + else { + // Compute the EIP-155 chain ID (or 0 for legacy) + let chainId = (v - BN_35) / BN_2$2; + if (chainId < BN_0) { + chainId = BN_0; + } + tx.chainId = chainId; + // Signed Legacy Transaction + if (chainId === BN_0 && (v < BN_27 || v > BN_28)) { + logger.throwArgumentError("non-canonical legacy v", "v", fields[6]); + } + tx.signature = Signature.from({ + r: zeroPadValue(fields[7], 32), + s: zeroPadValue(fields[8], 32), + v + }); + tx.hash = keccak256(data); + } + return tx; +} +function _serializeLegacy(tx, sig) { + const fields = [ + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? getAddress(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + ]; + let chainId = BN_0; + if (tx.chainId != null) { + // A chainId was provided; if non-zero we'll use EIP-155 + chainId = logger.getBigInt(tx.chainId, "tx.chainId"); + // We have a chainId in the tx and an EIP-155 v in the signature, + // make sure they agree with each other + if (sig && sig.networkV != null && sig.legacyChainId !== chainId) { + logger.throwArgumentError("tx.chainId/sig.v mismatch", "sig", sig); + } + } + else if (sig) { + // No chainId provided, but the signature is signing with EIP-155; derive chainId + const legacy = sig.legacyChainId; + if (legacy != null) { + chainId = legacy; + } + } + // Requesting an unsigned transaction + if (!sig) { + // We have an EIP-155 transaction (chainId was specified and non-zero) + if (chainId !== BN_0) { + fields.push(toArray(chainId)); + fields.push("0x"); + fields.push("0x"); + } + return encodeRlp(fields); + } + // We pushed a chainId and null r, s on for hashing only; remove those + let v = BigInt(27 + sig.yParity); + if (chainId !== BN_0) { + v = Signature.getChainIdV(chainId, sig.v); + } + else if (BigInt(sig.v) !== v) { + logger.throwArgumentError("tx.chainId/sig.v mismatch", "sig", sig); + } + fields.push(toArray(v)); + fields.push(toArray(sig.r)); + fields.push(toArray(sig.s)); + return encodeRlp(fields); +} +function _parseEipSignature(tx, fields, serialize) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } + catch (error) { + return logger.throwArgumentError("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 _parseEip1559(data) { + const fields = decodeRlp(logger.getBytes(data).slice(1)); + if (!Array.isArray(fields) || (fields.length !== 9 && fields.length !== 12)) { + logger.throwArgumentError("invalid field count for transaction type: 2", "data", hexlify(data)); + } + const maxPriorityFeePerGas = handleUint(fields[2], "maxPriorityFeePerGas"); + const maxFeePerGas = handleUint(fields[3], "maxFeePerGas"); + const tx = { + type: 2, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: maxPriorityFeePerGas, + maxFeePerGas: maxFeePerGas, + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: handleData(fields[7], "data"), + accessList: handleAccessList(fields[8], "accessList"), + }; + // Unsigned EIP-1559 Transaction + if (fields.length === 9) { + return tx; + } + tx.hash = keccak256(data); + _parseEipSignature(tx, fields.slice(9), _serializeEip1559); + return tx; +} +function _serializeEip1559(tx, sig) { + const fields = [ + formatNumber(tx.chainId || 0, "chainId"), + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? getAddress(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + (formatAccessList(tx.accessList || [])) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push(toArray(sig.r)); + fields.push(toArray(sig.s)); + } + return concat(["0x02", encodeRlp(fields)]); +} +function _parseEip2930(data) { + const fields = decodeRlp(logger.getBytes(data).slice(1)); + if (!Array.isArray(fields) || (fields.length !== 8 && fields.length !== 11)) { + logger.throwArgumentError("invalid field count for transaction type: 1", "data", hexlify(data)); + } + const tx = { + type: 1, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + gasPrice: handleUint(fields[2], "gasPrice"), + gasLimit: handleUint(fields[3], "gasLimit"), + to: handleAddress(fields[4]), + value: handleUint(fields[5], "value"), + data: handleData(fields[6], "data"), + accessList: handleAccessList(fields[7], "accessList") + }; + // Unsigned EIP-2930 Transaction + if (fields.length === 8) { + return tx; + } + tx.hash = keccak256(data); + _parseEipSignature(tx, fields.slice(8), _serializeEip2930); + return tx; +} +function _serializeEip2930(tx, sig) { + const fields = [ + formatNumber(tx.chainId || 0, "chainId"), + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? getAddress(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + (formatAccessList(tx.accessList || [])) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "recoveryParam")); + fields.push(toArray(sig.r)); + fields.push(toArray(sig.s)); + } + return concat(["0x01", encodeRlp(fields)]); +} +class Transaction { + #props; + // A type of null indicates the type will be populated automatically + get type() { return getStore(this.#props, "type"); } + get typeName() { + switch (this.type) { + case 0: return "legacy"; + case 1: return "eip-2930"; + case 2: return "eip-1559"; + } + return null; + } + set type(value) { + switch (value) { + case null: + setStore(this.#props, "type", null); + break; + case 0: + case "legacy": + setStore(this.#props, "type", 0); + break; + case 1: + case "berlin": + case "eip-2930": + setStore(this.#props, "type", 1); + break; + case 2: + case "london": + case "eip-1559": + setStore(this.#props, "type", 2); + break; + default: + throw new Error(`unsupported transaction type`); + } + } + get to() { return getStore(this.#props, "to"); } + set to(value) { + setStore(this.#props, "to", (value == null) ? null : getAddress(value)); + } + get nonce() { return getStore(this.#props, "nonce"); } + set nonce(value) { setStore(this.#props, "nonce", logger.getNumber(value, "value")); } + get gasLimit() { return getStore(this.#props, "gasLimit"); } + set gasLimit(value) { setStore(this.#props, "gasLimit", logger.getBigInt(value)); } + get gasPrice() { + const value = getStore(this.#props, "gasPrice"); + if (value == null && (this.type === 0 || this.type === 1)) { + return BN_0; + } + return value; + } + set gasPrice(value) { + setStore(this.#props, "gasPrice", (value == null) ? null : logger.getBigInt(value, "gasPrice")); + } + get maxPriorityFeePerGas() { + const value = getStore(this.#props, "maxPriorityFeePerGas"); + if (value == null && this.type === 2) { + return BN_0; + } + return value; + } + set maxPriorityFeePerGas(value) { + setStore(this.#props, "maxPriorityFeePerGas", (value == null) ? null : logger.getBigInt(value, "maxPriorityFeePerGas")); + } + get maxFeePerGas() { + const value = getStore(this.#props, "maxFeePerGas"); + if (value == null && this.type === 2) { + return BN_0; + } + return value; + } + set maxFeePerGas(value) { + setStore(this.#props, "maxFeePerGas", (value == null) ? null : logger.getBigInt(value, "maxFeePerGas")); + } + get data() { return getStore(this.#props, "data"); } + set data(value) { setStore(this.#props, "data", hexlify(value)); } + get value() { return getStore(this.#props, "value"); } + set value(value) { + setStore(this.#props, "value", logger.getBigInt(value, "value")); + } + get chainId() { return getStore(this.#props, "chainId"); } + set chainId(value) { setStore(this.#props, "chainId", logger.getBigInt(value)); } + get signature() { return getStore(this.#props, "sig") || null; } + set signature(value) { + setStore(this.#props, "sig", (value == null) ? null : Signature.from(value)); + } + get accessList() { + const value = getStore(this.#props, "accessList") || null; + if (value == null && (this.type === 1 || this.type === 2)) { + return []; + } + return value; + } + set accessList(value) { + setStore(this.#props, "accessList", (value == null) ? null : accessListify(value)); + } + constructor() { + this.#props = { + type: null, + to: null, + nonce: 0, + gasLimit: BigInt(0), + gasPrice: null, + maxPriorityFeePerGas: null, + maxFeePerGas: null, + data: "0x", + value: BigInt(0), + chainId: BigInt(0), + sig: null, + accessList: null + }; + } + get hash() { + if (this.signature == null) { + throw new Error("cannot hash unsigned transaction; maybe you meant .unsignedHash"); + } + return keccak256(this.serialized); + } + get unsignedHash() { + return keccak256(this.unsignedSerialized); + } + get from() { + if (this.signature == null) { + return null; + } + return recoverAddress(this.unsignedSerialized, this.signature); + } + get fromPublicKey() { + if (this.signature == null) { + return null; + } + // use ecrecover + return ""; + } + isSigned() { + return this.signature != null; + } + get serialized() { + if (this.signature == null) { + throw new Error("cannot serialize unsigned transaction; maybe you meant .unsignedSerialized"); + } + const types = this.inferTypes(); + if (types.length !== 1) { + throw new Error("cannot determine transaction type; specify type manually"); + } + switch (types[0]) { + case 0: + return _serializeLegacy(this, this.signature); + case 1: + return _serializeEip2930(this, this.signature); + case 2: + return _serializeEip1559(this, this.signature); + } + throw new Error("unsupported type"); + } + get unsignedSerialized() { + const types = this.inferTypes(); + if (types.length !== 1) { + throw new Error("cannot determine transaction type; specify type manually"); + } + switch (types[0]) { + case 0: + return _serializeLegacy(this); + case 1: + return _serializeEip2930(this); + case 2: + return _serializeEip1559(this); + } + throw new Error("unsupported type"); + } + // Validates properties and lists possible types this transaction adheres to + inferTypes() { + // Checks that there are no conflicting properties set + const hasGasPrice = this.gasPrice != null; + const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != 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) { + if (this.maxFeePerGas < this.maxPriorityFeePerGas) { + throw new Error("priorityFee cannot be more than maxFee"); + } + } + //if (this.type === 2 && hasGasPrice) { + // throw new Error("eip-1559 transaction cannot have gasPrice"); + //} + if ((this.type === 0 || this.type === 1) && hasFee) { + throw new Error("transaction type cannot have maxFeePerGas or maxPriorityFeePerGas"); + } + if (this.type === 0 && hasAccessList) { + throw new Error("legacy transaction cannot have accessList"); + } + const types = []; + // Explicit type + if (this.type != null) { + types.push(this.type); + } + else { + if (hasFee) { + types.push(2); + } + else if (hasGasPrice) { + types.push(1); + if (!hasAccessList) { + types.push(0); + } + } + else if (hasAccessList) { + types.push(1); + types.push(2); + } + else { + types.push(0); + types.push(1); + types.push(2); + } + } + types.sort(); + return types; + } + isLegacy() { return (this.type === 0); } + isBerlin() { return (this.type === 1); } + isLondon() { return (this.type === 2); } + clone() { + return Transaction.from(this); + } + freeze() { + if (this.#props.sig) { + this.#props.sig = (this.#props.sig.clone().freeze()); + } + if (this.#props.accessList) { + this.#props.accessList = Object.freeze(this.#props.accessList.map((set) => { + Object.freeze(set.storageKeys); + return Object.freeze(set); + })); + } + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + static from(tx) { + if (typeof (tx) === "string") { + const payload = logger.getBytes(tx); + if (payload[0] >= 0x7f) { // @TODO: > vs >= ?? + return Transaction.from(_parseLegacy(payload)); + } + switch (payload[0]) { + case 1: return Transaction.from(_parseEip2930(payload)); + case 2: return Transaction.from(_parseEip1559(payload)); + } + throw new Error("unsupported transaction type"); + } + const result = new Transaction(); + 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.gasPrice != null) { + result.gasPrice = tx.gasPrice; + } + 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.hash != null) { + if (result.isSigned()) { + if (result.hash !== tx.hash) { + throw new Error("hash mismatch"); + } + } + else { + throw new Error("unsigned transaction cannot have a hashs"); + } + } + if (tx.from != null) { + if (result.isSigned()) { + if (result.from.toLowerCase() !== (tx.from || "").toLowerCase()) { + throw new Error("from mismatch"); + } + } + else { + throw new Error("unsigned transaction cannot have a from"); + } + } + return result; + } +} + +class AbstractSigner { + provider; + constructor(provider) { + defineProperties(this, { provider: (provider || null) }); + } + #checkProvider(operation) { + if (this.provider) { + return this.provider; + } + return logger.throwError("missing provider", "UNSUPPORTED_OPERATION", { operation }); + } + async getNonce(blockTag) { + return this.#checkProvider("getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async #populate(op, tx) { + const provider = this.#checkProvider(op); + //let pop: Deferrable = Object.assign({ }, tx); + let pop = Object.assign({}, tx); + if (pop.to != null) { + pop.to = provider.resolveName(pop.to).then((to) => { + if (to == null) { + return logger.throwArgumentError("transaction to ENS name not configured", "tx.to", pop.to); + } + return to; + }); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + this.getAddress(), + this.resolveName(from) + ]).then(([address, from]) => { + if (!from || address.toLowerCase() !== from.toLowerCase()) { + return logger.throwArgumentError("transaction from mismatch", "tx.from", from); + } + return address; + }); + } + return pop; + } + async populateCall(tx) { + const pop = await this.#populate("populateCall", tx); + return pop; + } + async populateTransaction(tx) { + const pop = await this.#populate("populateTransaction", tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.gasLimit == null) { + pop.gasLimit = await this.estimateGas(pop); + } + //@TODO: Copy type logic from AbstractSigner in v5 + return await resolveProperties(pop); + } + async estimateGas(tx) { + return this.#checkProvider("estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return this.#checkProvider("call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = this.#checkProvider("resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = this.#checkProvider("sendTransaction"); + const txObj = Transaction.from(await this.populateTransaction(tx)); + return await provider.broadcastTransaction(await this.signTransaction(txObj)); + } +} +class VoidSigner extends AbstractSigner { + address; + constructor(address, provider) { + super(provider); + defineProperties(this, { address }); + } + async getAddress() { return this.address; } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + return logger.throwError(`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"); + } +} +class WrappedSigner extends AbstractSigner { + #signer; + constructor(signer) { + super(signer.provider); + this.#signer = signer; + } + async getAddress() { + return await this.#signer.getAddress(); + } + connect(provider) { + return new WrappedSigner(this.#signer.connect(provider)); + } + async getNonce(blockTag) { + return await this.#signer.getNonce(blockTag); + } + async populateCall(tx) { + return await this.#signer.populateCall(tx); + } + async populateTransaction(tx) { + return await this.#signer.populateTransaction(tx); + } + async estimateGas(tx) { + return await this.#signer.estimateGas(tx); + } + async call(tx) { + return await this.#signer.call(tx); + } + async resolveName(name) { + return this.#signer.resolveName(name); + } + async signTransaction(tx) { + return await this.#signer.signTransaction(tx); + } + async sendTransaction(tx) { + return await this.#signer.sendTransaction(tx); + } + async signMessage(message) { + return await this.#signer.signMessage(message); + } + async signTypedData(domain, types, value) { + return await this.#signer.signTypedData(domain, types, value); + } +} + +//import { resolveAddress } from "@ethersproject/address"; +// ----------------------- +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +// @TODO? implements Required +class FeeData { + gasPrice; + maxFeePerGas; + maxPriorityFeePerGas; + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + defineProperties(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), + }; + } +} +; +function copyRequest$1(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 in bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = logger.getBigInt(req[key], `request.${key}`); + } + const numberKeys = "type,nonce".split(/,/); + for (const key in numberKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = logger.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.enableCcipReadEnabled = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + return result; +} +; +class Block { + provider; + number; + hash; + timestamp; + parentHash; + nonce; + difficulty; + gasLimit; + gasUsed; + miner; + extraData; + baseFeePerGas; + #transactions; + constructor(block, provider) { + if (provider == null) { + provider = dummyProvider; + } + this.#transactions = Object.freeze(block.transactions.map((tx) => { + if (typeof (tx) !== "string" && tx.provider !== provider) { + throw new Error("provider mismatch"); + } + return tx; + })); + ; + 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) + }); + } + get transactions() { return this.#transactions; } + //connect(provider: Provider): Block { + // return new Block(this, provider); + //} + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, nonce, number, parentHash, timestamp, transactions } = this; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + hash, miner, nonce, number, parentHash, timestamp, + transactions, + }; + } + [Symbol.iterator]() { + let index = 0; + return { + next: () => { + if (index < this.length) { + return { + value: this.transactions[index++], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + get length() { return this.transactions.length; } + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1000); + } + async getTransaction(index) { + const tx = this.transactions[index]; + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + isMined() { return !!this.hash; } + isLondon() { return !!this.baseFeePerGas; } + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +class Log { + provider; + transactionHash; + blockHash; + blockNumber; + removed; + address; + data; + topics; + index; + transactionIndex; + constructor(log, provider) { + if (provider == null) { + provider = dummyProvider; + } + 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, + }); + } + //connect(provider: Provider): Log { + // return new Log(this, provider); + //} + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, blockHash, blockNumber, data, index, + removed, topics, transactionHash, transactionIndex + }; + } + async getBlock() { + return (await this.provider.getBlock(this.blockHash)); + } + async getTransaction() { + return (await this.provider.getTransaction(this.transactionHash)); + } + async getTransactionReceipt() { + return (await this.provider.getTransactionReceipt(this.transactionHash)); + } + removedEvent() { + return createRemovedLogFilter(this); + } +} +class TransactionReceipt { + provider; + to; + from; + contractAddress; + hash; + index; + blockHash; + blockNumber; + logsBloom; + gasUsed; + cumulativeGasUsed; + gasPrice; + byzantium; + status; + root; + #logs; + constructor(tx, provider) { + if (provider == null) { + provider = dummyProvider; + } + this.#logs = Object.freeze(tx.logs.map((log) => { + if (provider !== log.provider) { + //return log.connect(provider); + throw new Error("provider mismatch"); + } + return log; + })); + 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: (tx.effectiveGasPrice || tx.gasPrice), + byzantium: tx.byzantium, + status: tx.status, + root: tx.root + }); + } + get logs() { return this.#logs; } + //connect(provider: Provider): TransactionReceipt { + // return new TransactionReceipt(this, provider); + //} + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, byzantium, status, root } = 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, root, status, to + }; + } + 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 }; + } + }; + } + get fee() { + return this.gasUsed * this.gasPrice; + } + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + async confirmations() { + return (await this.provider.getBlockNumber()) - this.blockNumber + 1; + } + removedEvent() { + return createRemovedTransactionFilter(this); + } + reorderedEvent(other) { + if (other && !other.isMined()) { + return logger.throwError("unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "reorderedEvent(other)" + }); + } + return createReorderedTransactionFilter(this, other); + } +} +; +class TransactionResponse { + provider; + blockNumber; + blockHash; + index; + hash; + type; + to; + from; + nonce; + gasLimit; + gasPrice; + maxPriorityFeePerGas; + maxFeePerGas; + data; + value; + chainId; + signature; + accessList; + constructor(tx, provider) { + if (provider == null) { + provider = dummyProvider; + } + 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.gasPrice = tx.gasPrice; + 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; + } + //connect(provider: Provider): TransactionResponse { + // return new TransactionResponse(this, provider); + //} + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList } = this; + return { + _type: "TransactionReceipt", + accessList, blockNumber, blockHash, + chainId: toJson(this.chainId), + data, from, + gasLimit: toJson(this.gasLimit), + gasPrice: toJson(this.gasPrice), + hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + nonce, signature, to, index, type, + value: toJson(this.value), + }; + } + async getBlock() { + 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); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + async getTransaction() { + return this.provider.getTransaction(this.hash); + } + async wait(confirms) { + return this.provider.waitForTransaction(this.hash, confirms); + } + isMined() { + return (this.blockHash != null); + } + isLegacy() { + return (this.type === 0); + } + isBerlin() { + return (this.type === 1); + } + isLondon() { + return (this.type === 2); + } + removedEvent() { + if (!this.isMined()) { + return logger.throwError("unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + return createRemovedTransactionFilter(this); + } + reorderedEvent(other) { + if (!this.isMined()) { + return logger.throwError("unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + if (other && !other.isMined()) { + return logger.throwError("unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + return createReorderedTransactionFilter(this, other); + } +} +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 + } }; +} +function fail() { + throw new Error("this provider should not be used"); +} +class DummyProvider { + get provider() { return this; } + async getNetwork() { return fail(); } + async getFeeData() { return fail(); } + async estimateGas(tx) { return fail(); } + async call(tx) { return fail(); } + async resolveName(name) { return fail(); } + // State + async getBlockNumber() { return fail(); } + // Account + async getBalance(address, blockTag) { + return fail(); + } + async getTransactionCount(address, blockTag) { + return fail(); + } + async getCode(address, blockTag) { + return fail(); + } + async getStorageAt(address, position, blockTag) { + return fail(); + } + // Write + async broadcastTransaction(signedTx) { return fail(); } + // Queries + async getBlock(blockHashOrBlockTag) { + return fail(); + } + async getBlockWithTransactions(blockHashOrBlockTag) { + return fail(); + } + async getTransaction(hash) { + return fail(); + } + async getTransactionReceipt(hash) { + return fail(); + } + // Bloom-filter Queries + async getLogs(filter) { + return fail(); + } + // ENS + async lookupAddress(address) { + return fail(); + } + async waitForTransaction(hash, confirms, timeout) { + return fail(); + } + async waitForBlock(blockTag) { + return fail(); + } + // EventEmitterable + async on(event, listener) { return fail(); } + async once(event, listener) { return fail(); } + async emit(event, ...args) { return fail(); } + async listenerCount(event) { return fail(); } + async listeners(event) { return fail(); } + async off(event, listener) { return fail(); } + async removeAllListeners(event) { return fail(); } + async addListener(event, listener) { return fail(); } + async removeListener(event, listener) { return fail(); } +} +/** + * A singleton [[Provider]] instance that can be used as a placeholder. This + * allows API that have a Provider added later to not require a null check. + * + * All operations performed on this [[Provider]] will throw. + */ +const dummyProvider = new DummyProvider(); + +// Belongs to Networks; requires abstract-provider +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +//export type AccessListSet = { address: string, storageKeys: Array }; +//export type AccessList = Array; +//export type AccessListish = AccessList | +// Array<[ string, Array ]> | +// Record>; +function stringify(value) { + if (typeof (value) !== "string") { + throw new Error("invalid string"); + } + return value; +} +class Formatter { + #format; + #baseBlock; + constructor() { + const address = this.address.bind(this); + const bigNumber = this.bigNumber.bind(this); + const blockTag = this.blockTag.bind(this); + const data = this.data.bind(this); + const hash = this.hash.bind(this); + const number = this.number.bind(this); + const uint256 = this.uint256.bind(this); + const topics = this.arrayOf(hash); + this.#format = { + address, + bigNumber, + blockTag, + data, + hash, + number, + uint256, + topics, + filter: this.object({ + fromBlock: this.allowNull(blockTag, undefined), + toBlock: this.allowNull(blockTag, undefined), + blockHash: this.allowNull(hash, undefined), + address: this.allowNull(address, undefined), + topics: this.allowNull(topics, undefined) + }), + transactionRequest: this.object({ + from: this.allowNull(address), + type: this.allowNull(number), + to: this.allowNull(address), + nonce: this.allowNull(number), + gasLimit: this.allowNull(uint256), + gasPrice: this.allowNull(uint256), + maxFeePerGas: this.allowNull(uint256), + maxPriorityFeePerGas: this.allowNull(uint256), + data: this.allowNull(data), + value: this.allowNull(uint256), + }), + transactionResponse: this.object({ + hash: hash, + index: number, + type: this.allowNull(number, 0), + // These can be null for pending blocks + blockHash: this.allowNull(hash), + blockNumber: this.allowNull(number), + // For Legacy transactions, this comes from the v + chainId: this.allowNull(number), + from: address, + to: this.address, + gasLimit: bigNumber, + gasPrice: this.allowNull(bigNumber), + maxFeePerGas: this.allowNull(bigNumber), + maxPriorityFeePerGas: this.allowNull(bigNumber), + value: bigNumber, + data: data, + nonce: number, + r: hash, + s: hash, + v: number, + accessList: this.allowNull(this.accessList) + }, { + index: ["transactionIndex"] + }), + }; + this.#baseBlock = this.object({ + number: number, + hash: this.allowNull(hash, null), + timestamp: number, + parentHash: hash, + nonce: this.allowNull(stringify, "0x0000000000000000"), + difficulty: bigNumber, + gasLimit: bigNumber, + gasUsed: bigNumber, + miner: this.allowNull(address, "0x0000000000000000000000000000000000000000"), + extraData: stringify, + baseFeePerGas: this.allowNull(bigNumber), + }); + } + // An address + address(value) { + return getAddress(value); + } + // An address from a call result; may be zero-padded + callAddress(value) { + if (dataLength(value) !== 32 || dataSlice(value, 0, 12) !== "0x000000000000000000000000") { + logger.throwArgumentError("invalid call address", "value", value); + } + return this.address(dataSlice(value, 12)); + } + // An address from a transaction (e.g. { from: string, nonce: number }) + contractAddress(value) { + return getCreateAddress({ + from: this.address(value.from), + nonce: logger.getNumber(value.nonce, "value.nonce") + }); + } + // Block Tag + blockTag(value) { + if (value == null) { + return "latest"; + } + switch (value) { + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return value; + } + if (typeof (value) === "number" || (isHexString(value) && dataLength(value) < 32)) { + return toQuantity(value); + } + return logger.throwArgumentError("invalid blockTag", "value", value); + } + // Block objects + block(value, provider) { + const params = this.#baseBlock(value); + params.transactions = value.transactions.map((t) => this.hash(t)); + return new Block(params, provider); + } + blockWithTransactions(value, provider) { + throw new Error(); + } + // Transactions + transactionRequest(value, provider) { + return this.#format.transactionRequest(value); + } + transactionResponse(value, provider) { + value = Object.assign({}, value); + // @TODO: Use the remap feature + if (value.data == null && value.input != null) { + value.data = value.input; + } + if (value.gasLimit == null && value.gas) { + value.gasLimit = value.gas; + } + value = this.#format.transactionResponse(value); + const sig = Signature.from({ r: value.r, s: value.s, v: value.v }); + value.signature = sig; + if (value.chainId == null) { + value.chainId = sig.legacyChainId; + } + return new TransactionResponse(value, provider); + } + // Receipts + log(value, provider) { + const log = this.object({ + address: this.address, + blockHash: this.hash, + blockNumber: this.number, + data: this.data, + index: this.number, + removed: this.boolean, + topics: this.topics, + transactionHash: this.hash, + transactionIndex: this.number, + }, { + index: ["logIndex"] + })(value); + return new Log(log, provider); + } + receipt(value, provider) { + const receipt = this.object({ + blockHash: this.hash, + blockNumber: this.number, + contractAddress: this.allowNull(this.address), + cumulativeGasUsed: this.bigNumber, + from: this.address, + gasUsed: this.bigNumber, + logs: this.arrayOf((v) => (this.log(v, provider))), + logsBloom: this.data, + root: this.allowNull(this.data), + status: this.allowNull(this.number), + to: this.address, + gasPrice: this.allowNull(this.bigNumber), + hash: this.hash, + index: this.number, + type: this.allowNull(this.number, 0), + }, { + hash: ["transactionHash"], + gasPrice: ["effectiveGasPrice"], + index: ["transactionIndex"] + })(value); + // RSK incorrectly implemented EIP-658, so we munge things a bit here for it + if (receipt.root != null) { + if (receipt.root.length <= 4) { + // Could be 0x00, 0x0, 0x01 or 0x1 + const value = parseInt(receipt.root); + if (value === 0 || value === 1) { + // Make sure if both are specified, they match + if (receipt.status != null && receipt.status !== value) { + return logger.throwError("alt-root-status/status mismatch", "BAD_DATA", { + value: { root: receipt.root, status: receipt.status } + }); + } + receipt.status = value; + delete receipt.root; + } + else { + return logger.throwError("invalid alt-root-status", "BAD_DATA", { + value: receipt.root + }); + } + } + else if (!isHexString(receipt.root, 32)) { + // Must be a valid bytes32 + return logger.throwError("invalid receipt root hash", "BAD_DATA", { + value: receipt.root + }); + } + } + //receipt.byzantium = (receipt.root == null); + return new TransactionReceipt(receipt, provider); + } + // Fitlers + topics(value) { + return this.#format.topics(value); + } + filter(value) { + return this.#format.filter(value); + } + filterLog(value) { + console.log("ME", value); + return null; + } + // Converts a serialized transaction to a TransactionResponse + transaction(value) { + throw new Error(); + } + // Useful utility formatters functions, which if need be use the + // methods within the formatter to ensure internal compatibility + // Access List; converts an AccessListish to an AccessList + accessList(value) { + return accessListify(value); + } + // Converts falsish values to a specific value, otherwise use the formatter. Calls preserve `this`. + allowFalsish(format, ifFalse) { + return ((value) => { + if (!value) { + return ifFalse; + } + return format.call(this, value); + }); + } + // Allows null, optionally replacing it with a default value. Calls preserve `this`. + allowNull(format, ifNull) { + return ((value) => { + if (value == null) { + return ifNull; + } + return format.call(this, value); + }); + } + // Requires an Array satisfying the formatter. Calls preserves `this`. + arrayOf(format) { + return ((array) => { + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + return array.map((i) => format.call(this, i)); + }); + } + // Requires a value which is a value BigNumber + bigNumber(value) { + return logger.getBigInt(value, "value"); + } + uint256(value) { + const result = this.bigNumber(value); + if (result < 0 || result > BN_MAX_UINT256) { + logger.throwArgumentError("invalid uint256", "value", value); + } + return result; + } + // Requires a value which is a value boolean or string equivalent + boolean(value) { + switch (value) { + case true: + case "true": + return true; + case false: + case "false": + return false; + } + return logger.throwArgumentError(`invalid boolean; ${JSON.stringify(value)}`, "value", value); + } + // Requires a value which is a valid hexstring. If dataOrLength is true, + // the length must be even (i.e. a datahexstring) or if it is a number, + // specifies teh number of bytes value must represent + _hexstring(dataOrLength) { + if (dataOrLength == null) { + dataOrLength = false; + } + return (function (value) { + if (isHexString(value, dataOrLength)) { + return value.toLowerCase(); + } + throw new Error("bad hexstring"); + }); + } + data(value) { + if (dataLength(value) == null) { + logger.throwArgumentError("", "value", value); + } + return value; + } + // Requires a network-native hash + hash(value) { + if (dataLength(value) !== 32) { + logger.throwArgumentError("", "value", value); + } + return this.#format.data(value); + } + // Requires a valid number, within the IEEE 754 safe range + number(value) { + return logger.getNumber(value); + } + // Requires an object which matches a fleet of other formatters + // Any FormatFunc may return `undefined` to have the value omitted + // from the result object. Calls preserve `this`. + object(format, altNames) { + return ((value) => { + const result = {}; + for (const key in format) { + let srcKey = key; + if (altNames && key in altNames && !(srcKey in value)) { + for (const altKey of altNames[key]) { + if (altKey in value) { + srcKey = altKey; + break; + } + } + } + try { + const nv = format[key].call(this, value[srcKey]); + if (nv !== undefined) { + result[key] = nv; + } + } + catch (error) { + const message = (error instanceof Error) ? error.message : "not-an-error"; + logger.throwError(`invalid value for value.${key} (${message})`, "BAD_DATA", { value }); + } + } + return result; + }); + } +} + +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +class NetworkPlugin { + name; + constructor(name) { + defineProperties(this, { name }); + } + clone() { + return new NetworkPlugin(this.name); + } + validate(network) { + return this; + } +} +class GasCostPlugin extends NetworkPlugin { + effectiveBlock; + txBase; + txCreate; + txDataZero; + txDataNonzero; + txAccessListStorageKey; + txAccessListAddress; + constructor(effectiveBlock = 0, costs) { + super(`org.ethers.network-plugins.gas-cost#${(effectiveBlock || 0)}`); + const props = { effectiveBlock }; + function set(name, nullish) { + let value = (costs || {})[name]; + if (value == null) { + value = nullish; + } + if (typeof (value) !== "number") { + logger.throwArgumentError(`invalud value for ${name}`, "costs", costs); + } + props[name] = value; + } + set("txBase", 21000); + set("txCreate", 32000); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + defineProperties(this, props); + } + clone() { + return new GasCostPlugin(this.effectiveBlock, this); + } +} +// Networks shoudl use this plugin to specify the contract address +// and network necessary to resolve ENS names. +class EnsPlugin extends NetworkPlugin { + // The ENS contract address + address; + // The network ID that the ENS contract lives on + targetNetwork; + constructor(address, targetNetwork) { + super("org.ethers.network-plugins.ens"); + defineProperties(this, { + address: (address || EnsAddress), + targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork) + }); + } + clone() { + return new EnsPlugin(this.address, this.targetNetwork); + } + validate(network) { + network.formatter.address(this.address); + return this; + } +} +/* +export class MaxPriorityFeePlugin extends NetworkPlugin { + readonly priorityFee!: bigint; + + constructor(priorityFee: BigNumberish) { + super("org.ethers.plugins.max-priority-fee"); + defineProperties(this, { + priorityFee: logger.getBigInt(priorityFee) + }); + } + + async getPriorityFee(provider: Provider): Promise { + return this.priorityFee; + } + + clone(): MaxPriorityFeePlugin { + return new MaxPriorityFeePlugin(this.priorityFee); + } +} +*/ +class FeeDataNetworkPlugin extends NetworkPlugin { + #feeDataFunc; + get feeDataFunc() { return this.#feeDataFunc; } + constructor(feeDataFunc) { + super("org.ethers.network-plugins.fee-data"); + this.#feeDataFunc = feeDataFunc; + } + async getFeeData(provider) { + return await this.#feeDataFunc(provider); + } + clone() { + return new FeeDataNetworkPlugin(this.#feeDataFunc); + } +} + +const BN_1$1 = BigInt(1); +const Empty = new Uint8Array([]); +function parseBytes(result, start) { + if (result === "0x") { + return null; + } + const offset = toNumber(dataSlice(result, start, start + 32)); + const length = toNumber(dataSlice(result, offset, offset + 32)); + return dataSlice(result, offset + 32, offset + 32 + length); +} +function parseString(result, start) { + try { + const bytes = parseBytes(result, start); + if (bytes != null) { + return toUtf8String(bytes); + } + } + catch (error) { } + return null; +} +function numPad$1(value) { + const result = toArray(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$1(value) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes$1(datas) { + const result = []; + 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 = logger.getBytes(datas[i]); + // Update the bytes offset + result[i] = numPad$1(byteCount); + // The length and padded value of data + result.push(numPad$1(data.length)); + result.push(bytesPad$1(data)); + byteCount += 32 + Math.ceil(data.length / 32) * 32; + } + return concat(result); +} +// @TODO: This should use the fetch-data:ipfs gateway +// Trim off the ipfs:// prefix and return the default gateway URL +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } + else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } + else { + logger.throwArgumentError("unsupported IPFS format", "link", link); + } + return `https:/\/gateway.ipfs.io/ipfs/${link}`; +} +; +; +class MulticoinProviderPlugin { + name; + constructor(name) { + defineProperties(this, { name }); + } + validate(proivder) { + return this; + } + supportsCoinType(coinType) { + return false; + } + async encodeAddress(coinType, address) { + throw new Error("unsupported coin"); + } + async decodeAddress(coinType, data) { + throw new Error("unsupported coin"); + } +} +const BasicMulticoinPluginId = "org.ethers.provider-prugins.basicmulticoin"; +class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin { + constructor() { + super(BasicMulticoinPluginId); + } +} +const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i"); +const matchers = [ + new RegExp("^(https):/\/(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"), +]; +class EnsResolver { + provider; + address; + name; + // For EIP-2544 names, the ancestor that provided the resolver + #supports2544; + constructor(provider, address, name) { + defineProperties(this, { provider, address, name }); + this.#supports2544 = null; + } + async supportsWildcard() { + if (!this.#supports2544) { + // supportsInterface(bytes4 = selector("resolve(bytes,bytes)")) + this.#supports2544 = this.provider.call({ + to: this.address, + data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000" + }).then((result) => { + return (logger.getBigInt(result) === BN_1$1); + }).catch((error) => { + if (error.code === "CALL_EXCEPTION") { + return false; + } + // Rethrow the error: link is down, etc. Let future attempts retry. + this.#supports2544 = null; + throw error; + }); + } + return await this.#supports2544; + } + async _fetch(selector, parameters = "0x") { + // e.g. keccak256("addr(bytes32,uint256)") + const addrData = concat([selector, namehash(this.name), parameters]); + const tx = { + to: this.address, + enableCcipRead: true, + data: addrData + }; + // Wildcard support; use EIP-2544 to resolve the request + let wrapped = false; + if (await this.supportsWildcard()) { + wrapped = true; + // selector("resolve(bytes,bytes)") + tx.data = concat(["0x9061b923", encodeBytes$1([dnsEncode(this.name), addrData])]); + } + try { + let data = await this.provider.call(tx); + if ((logger.getBytes(data).length % 32) === 4) { + return logger.throwError("resolver threw error", "CALL_EXCEPTION", { + transaction: tx, data + }); + } + if (wrapped) { + return parseBytes(data, 0); + } + return data; + } + catch (error) { + if (error.code !== "CALL_EXCEPTION") { + throw error; + } + } + return null; + } + async getAddress(coinType = 60) { + if (coinType === 60) { + try { + // keccak256("addr(bytes32)") + const result = await this._fetch("0x3b3b57de"); + // No address + if (result === "0x" || result === ZeroHash) { + return null; + } + const network = await this.provider.getNetwork(); + return network.formatter.callAddress(result); + } + catch (error) { + if (error.code === "CALL_EXCEPTION") { + return null; + } + throw error; + } + } + let coinPlugin = null; + for (const plugin of this.provider.plugins) { + if (!(plugin instanceof MulticoinProviderPlugin)) { + continue; + } + if (plugin.supportsCoinType(coinType)) { + coinPlugin = plugin; + break; + } + } + if (coinPlugin == null) { + return null; + } + // keccak256("addr(bytes32,uint256") + const data = parseBytes((await this._fetch("0xf1cb7e06", numPad$1(coinType))) || "0x", 0); + // No address + if (data == null || data === "0x") { + return null; + } + // Compute the address + const address = await coinPlugin.encodeAddress(coinType, data); + if (address != null) { + return address; + } + return logger.throwError(`invalid coin data`, "UNSUPPORTED_OPERATION", { + operation: `getAddress(${coinType})`, + info: { coinType, data } + }); + } + async getText(key) { + // The key encoded as parameter to fetchBytes + let keyBytes = toUtf8Bytes(key); + // The nodehash consumes the first slot, so the string pointer targets + // offset 64, with the length at offset 64 and data starting at offset 96 + const calldata = logger.getBytes(concat([numPad$1(64), numPad$1(keyBytes.length), keyBytes])); + const hexBytes = parseBytes((await this._fetch("0x59d1d43c", bytesPad$1(calldata))) || "0x", 0); + if (hexBytes == null || hexBytes === "0x") { + return null; + } + return toUtf8String(hexBytes); + } + async getContentHash() { + // keccak256("contenthash()") + const hexBytes = parseBytes((await this._fetch("0xbc1c58d1")) || "0x", 0); + // No contenthash + if (hexBytes == null || hexBytes === "0x") { + return null; + } + // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key) + const ipfs = hexBytes.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const scheme = (ipfs[1] === "e3010170") ? "ipfs" : "ipns"; + const length = parseInt(ipfs[4], 16); + if (ipfs[5].length === length * 2) { + return `${scheme}:/\/${encodeBase58("0x" + ipfs[2])}`; + } + } + // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32) + const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm && swarm[1].length === 64) { + return `bzz:/\/${swarm[1]}`; + } + return logger.throwError(`invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { + operation: "getContentHash()", + info: { data: hexBytes } + }); + } + async getAvatar() { + return (await this._getAvatar()).url; + } + async _getAvatar() { + const linkage = [{ type: "name", value: this.name }]; + try { + // test data for ricmoo.eth + //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233"; + const avatar = await this.getText("avatar"); + if (avatar == null) { + linkage.push({ type: "!avatar", value: "" }); + throw new Error("!avatar"); + } + linkage.push({ type: "avatar", value: avatar }); + for (let i = 0; i < matchers.length; i++) { + const match = avatar.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch (scheme) { + case "https": + case "data": + linkage.push({ type: "url", value: avatar }); + return { linkage, url: avatar }; + case "ipfs": { + const url = getIpfsLink(avatar); + linkage.push({ type: "ipfs", value: avatar }); + linkage.push({ type: "url", value: url }); + return { linkage, url }; + } + case "erc721": + case "erc1155": { + // Depending on the ERC type, use tokenURI(uint256) or url(uint256) + const selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c"; + linkage.push({ type: scheme, value: avatar }); + // The owner of this name + const owner = await this.getAddress(); + if (owner == null) { + linkage.push({ type: "!owner", value: "" }); + throw new Error("!owner"); + } + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + linkage.push({ type: `!${scheme}caip`, value: (match[2] || "") }); + throw new Error("!caip"); + } + const formatter = (await this.provider.getNetwork()).formatter; + const addr = formatter.address(comps[0]); + const tokenId = numPad$1(comps[1]); + // Check that this account owns the token + if (scheme === "erc721") { + // ownerOf(uint256 tokenId) + const tokenOwner = formatter.callAddress(await this.provider.call({ + to: addr, data: concat(["0x6352211e", tokenId]) + })); + if (owner !== tokenOwner) { + linkage.push({ type: "!owner", value: tokenOwner }); + throw new Error("!owner"); + } + linkage.push({ type: "owner", value: tokenOwner }); + } + else if (scheme === "erc1155") { + // balanceOf(address owner, uint256 tokenId) + const balance = logger.getBigInt(await this.provider.call({ + to: addr, data: concat(["0x00fdd58e", zeroPadValue(owner, 32), tokenId]) + })); + if (!balance) { + linkage.push({ type: "!balance", value: "0" }); + throw new Error("!balance"); + } + linkage.push({ type: "balance", value: balance.toString() }); + } + // Call the token contract for the metadata URL + const tx = { + to: comps[0], + data: concat([selector, tokenId]) + }; + let metadataUrl = parseString(await this.provider.call(tx), 0); + if (metadataUrl == null) { + linkage.push({ type: "!metadata-url", value: "" }); + throw new Error("!metadata-url"); + } + linkage.push({ type: "metadata-url-base", value: metadataUrl }); + // ERC-1155 allows a generic {id} in the URL + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", hexlify(tokenId).substring(2)); + linkage.push({ type: "metadata-url-expanded", value: metadataUrl }); + } + // Transform IPFS metadata links + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ type: "metadata-url", value: metadataUrl }); + // Get the token metadata + let metadata = {}; + const response = await (new FetchRequest(metadataUrl)).send(); + response.assertOk(); + try { + metadata = response.bodyJson; + } + catch (error) { + try { + linkage.push({ type: "!metadata", value: response.bodyText }); + } + catch (error) { + const bytes = response.body; + if (bytes) { + linkage.push({ type: "!metadata", value: hexlify(bytes) }); + } + throw error; + } + throw error; + } + if (!metadata) { + linkage.push({ type: "!metadata", value: "" }); + throw new Error("!metadata"); + } + linkage.push({ type: "metadata", value: JSON.stringify(metadata) }); + // Pull the image URL out + let imageUrl = metadata.image; + if (typeof (imageUrl) !== "string") { + linkage.push({ type: "!imageUrl", value: "" }); + throw new Error("!imageUrl"); + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) { + // Allow + } + else { + // Transform IPFS link to gateway + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + linkage.push({ type: "!imageUrl-ipfs", value: imageUrl }); + throw new Error("!imageUrl-ipfs"); + } + linkage.push({ type: "imageUrl-ipfs", value: imageUrl }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ type: "url", value: imageUrl }); + return { linkage, url: imageUrl }; + } + } + } + } + catch (error) { + console.log("EE", error); + } + return { linkage, url: null }; + } + static async #getResolver(provider, name) { + const network = await provider.getNetwork(); + const ensPlugin = network.getPlugin("org.ethers.network-plugins.ens"); + // No ENS... + if (!ensPlugin) { + return logger.throwError("network does not support ENS", "UNSUPPORTED_OPERATION", { + operation: "getResolver", info: { network: network.name } + }); + } + try { + // keccak256("resolver(bytes32)") + const addrData = await provider.call({ + to: ensPlugin.address, + data: concat(["0x0178b8bf", namehash(name)]), + enableCcipRead: true + }); + const addr = network.formatter.callAddress(addrData); + if (addr === dataSlice(ZeroHash, 0, 20)) { + return null; + } + return addr; + } + catch (error) { + // ENS registry cannot throw errors on resolver(bytes32), + // so probably a link error + throw error; + } + return null; + } + static async fromName(provider, name) { + let currentName = name; + while (true) { + if (currentName === "" || currentName === ".") { + return null; + } + // Optimization since the eth node cannot change and does + // not have a wildcar resolver + if (name !== "eth" && currentName === "eth") { + return null; + } + // Check the current node for a resolver + const addr = await EnsResolver.#getResolver(provider, currentName); + // Found a resolver! + if (addr != null) { + const resolver = new EnsResolver(provider, addr, name); + // Legacy resolver found, using EIP-2544 so it isn't safe to use + if (currentName !== name && !(await resolver.supportsWildcard())) { + return null; + } + return resolver; + } + // Get the parent node + currentName = currentName.split(".").slice(1).join("."); + } + } +} + +/* * * * +// Networks which operation against an L2 can use this plugin to +// specify how to access L1, for the purpose of resolving ENS, +// for example. +export class LayerOneConnectionPlugin extends NetworkPlugin { + readonly provider!: Provider; +// @TODO: Rename to ChainAccess and allow for connecting to any chain + constructor(provider: Provider) { + super("org.ethers.plugins.layer-one-connection"); + defineProperties(this, { provider }); + } + + clone(): LayerOneConnectionPlugin { + return new LayerOneConnectionPlugin(this.provider); + } +} +*/ +/* * * * +export class PriceOraclePlugin extends NetworkPlugin { + readonly address!: string; + + constructor(address: string) { + super("org.ethers.plugins.price-oracle"); + defineProperties(this, { address }); + } + + clone(): PriceOraclePlugin { + return new PriceOraclePlugin(this.address); + } +} +*/ +// Networks or clients with a higher need for security (such as clients +// that may automatically make CCIP requests without user interaction) +// can use this plugin to anonymize requests or intercept CCIP requests +// to notify and/or receive authorization from the user +/* * * * +export type FetchDataFunc = (req: Frozen) => Promise; +export class CcipPreflightPlugin extends NetworkPlugin { + readonly fetchData!: FetchDataFunc; + + constructor(fetchData: FetchDataFunc) { + super("org.ethers.plugins.ccip-preflight"); + defineProperties(this, { fetchData }); + } + + clone(): CcipPreflightPlugin { + return new CcipPreflightPlugin(this.fetchData); + } +} +*/ +const Networks = new Map(); +const defaultFormatter = new Formatter(); +class Network { + #props; + constructor(name, _chainId, formatter) { + const chainId = logger.getBigInt(_chainId); + if (formatter == null) { + formatter = defaultFormatter; + } + const plugins = new Map(); + this.#props = { name, chainId, formatter, plugins }; + } + toJSON() { + return { name: this.name, chainId: this.chainId }; + } + get name() { return getStore(this.#props, "name"); } + set name(value) { setStore(this.#props, "name", value); } + get chainId() { return getStore(this.#props, "chainId"); } + set chainId(value) { setStore(this.#props, "chainId", logger.getBigInt(value, "chainId")); } + get formatter() { return getStore(this.#props, "formatter"); } + set formatter(value) { setStore(this.#props, "formatter", value); } + get plugins() { + return Array.from(this.#props.plugins.values()); + } + attachPlugin(plugin) { + if (this.isFrozen()) { + throw new Error("frozen"); + } + if (this.#props.plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#props.plugins.set(plugin.name, plugin.validate(this)); + return this; + } + getPlugin(name) { + return (this.#props.plugins.get(name)) || null; + } + // Gets a list of Plugins which match basename, ignoring any fragment + getPlugins(basename) { + return (this.plugins.filter((p) => (p.name.split("#")[0] === basename))); + } + clone() { + const clone = new Network(this.name, this.chainId, this.formatter); + this.plugins.forEach((plugin) => { + clone.attachPlugin(plugin.clone()); + }); + return clone; + } + freeze() { + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + computeIntrinsicGas(tx) { + const costs = this.getPlugin("org.ethers.gas-cost") || (new GasCostPlugin()); + let gas = costs.txBase; + if (tx.to == null) { + gas += costs.txCreate; + } + if (tx.data) { + for (let i = 2; i < tx.data.length; i += 2) { + if (tx.data.substring(i, i + 2) === "00") { + gas += costs.txDataZero; + } + else { + gas += costs.txDataNonzero; + } + } + } + if (tx.accessList) { + const accessList = this.formatter.accessList(tx.accessList); + for (const addr in accessList) { + gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; + } + } + return gas; + } + static from(network) { + // Default network + if (network == null) { + return Network.from("homestead"); + } + // Canonical name or chain ID + if (typeof (network) === "number") { + network = BigInt(network); + } + if (typeof (network) === "string" || typeof (network) === "bigint") { + const networkFunc = Networks.get(network); + if (networkFunc) { + return networkFunc(); + } + if (typeof (network) === "bigint") { + return new Network("unknown", network); + } + logger.throwArgumentError("unknown network", "network", network); + } + // Clonable with network-like abilities + if (typeof (network.clone) === "function") { + const clone = network.clone(); + //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") { + //} + return clone; + } + // Networkish + if (typeof (network) === "object") { + if (typeof (network.name) !== "string" || typeof (network.chainId) !== "number") { + logger.throwArgumentError("invalid network object name or chainId", "network", network); + } + const custom = new Network((network.name), (network.chainId)); + if (network.ensAddress || network.ensNetwork != null) { + custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork)); + } + //if ((network).layerOneConnection) { + // custom.attachPlugin(new LayerOneConnectionPlugin((network).layerOneConnection)); + //} + return custom; + } + return logger.throwArgumentError("invalid network", "network", network); + } + static register(nameOrChainId, networkFunc) { + if (typeof (nameOrChainId) === "number") { + nameOrChainId = BigInt(nameOrChainId); + } + const existing = Networks.get(nameOrChainId); + if (existing) { + logger.throwArgumentError(`conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); + } + Networks.set(nameOrChainId, networkFunc); + } +} + +function copy$2(obj) { + return JSON.parse(JSON.stringify(obj)); +} +function getPollingSubscriber(provider, event) { + if (event === "block") { + return new PollingBlockSubscriber(provider); + } + if (isHexString(event, 32)) { + return new PollingTransactionSubscriber(provider, event); + } + return logger.throwError("unsupported polling event", "UNSUPPORTED_OPERATION", { + operation: "getPollingSubscriber", info: { event } + }); +} +// @TODO: refactor this +class PollingBlockSubscriber { + #provider; + #poller; + #interval; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + constructor(provider) { + this.#provider = provider; + this.#poller = null; + this.#interval = 4000; + this.#blockNumber = -2; + } + get pollingInterval() { return this.#interval; } + set pollingInterval(value) { this.#interval = value; } + async #poll() { + const blockNumber = await this.#provider.getBlockNumber(); + if (this.#blockNumber === -2) { + this.#blockNumber = blockNumber; + return; + } + // @TODO: Put a cap on the maximum number of events per loop? + if (blockNumber !== this.#blockNumber) { + for (let b = this.#blockNumber + 1; b <= blockNumber; b++) { + this.#provider.emit("block", b); + } + this.#blockNumber = blockNumber; + } + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + start() { + if (this.#poller) { + throw new Error("subscriber already running"); + } + this.#poll(); + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + stop() { + if (!this.#poller) { + throw new Error("subscriber not running"); + } + this.#provider._clearTimeout(this.#poller); + this.#poller = null; + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +class OnBlockSubscriber { + #provider; + #poll; + constructor(provider) { + this.#provider = provider; + this.#poll = (blockNumber) => { + this._poll(blockNumber, this.#provider); + }; + } + async _poll(blockNumber, provider) { + throw new Error("sub-classes must override this"); + } + start() { + this.#poll(-2); + this.#provider.on("block", this.#poll); + } + stop() { + this.#provider.off("block", this.#poll); + } + pause(dropWhilePaused) { this.stop(); } + resume() { this.start(); } +} +class PollingOrphanSubscriber extends OnBlockSubscriber { + #filter; + constructor(provider, filter) { + super(provider); + this.#filter = copy$2(filter); + } + async _poll(blockNumber, provider) { + throw new Error("@TODO"); + console.log(this.#filter); + } +} +class PollingTransactionSubscriber extends OnBlockSubscriber { + #hash; + constructor(provider, hash) { + super(provider); + this.#hash = hash; + } + async _poll(blockNumber, provider) { + const tx = await provider.getTransactionReceipt(this.#hash); + if (tx) { + provider.emit(this.#hash, tx); + } + } +} +class PollingEventSubscriber { + #provider; + #filter; + #poller; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + constructor(provider, filter) { + this.#provider = provider; + this.#filter = copy$2(filter); + this.#poller = this.#poll.bind(this); + this.#blockNumber = -2; + } + async #poll(blockNumber) { + // The initial block hasn't been determined yet + if (this.#blockNumber === -2) { + return; + } + const filter = copy$2(this.#filter); + filter.fromBlock = this.#blockNumber + 1; + filter.toBlock = blockNumber; + const logs = await this.#provider.getLogs(filter); + // No logs could just mean the node has not indexed them yet, + // so we keep a sliding window of 60 blocks to keep scanning + if (logs.length === 0) { + if (this.#blockNumber < blockNumber - 60) { + this.#blockNumber = blockNumber - 60; + } + return; + } + this.#blockNumber = blockNumber; + for (const log of logs) { + this.#provider.emit(this.#filter, log); + } + } + start() { + if (this.#blockNumber === -2) { + this.#provider.getBlockNumber().then((blockNumber) => { + this.#blockNumber = blockNumber; + }); + } + this.#provider.on("block", this.#poller); + } + stop() { + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} + +// @TODO +; +// Constants +const BN_2$1 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v) => { + 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; + }); +} +class UnmanagedSubscriber { + name; + constructor(name) { defineProperties(this, { name }); } + start() { } + stop() { } + pause(dropWhilePaused) { } + resume() { } +} +function copy$1(value) { + return JSON.parse(JSON.stringify(value)); +} +function concisify$1(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +// Normalize a ProviderEvent into a Subscription +// @TODO: Make events sync if possible; like block +//function getSyncSubscription(_event: ProviderEvent): Subscription { +//} +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 "pending": + case "debug": + case "network": { + 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$1(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$1(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$1(addresses.map((a) => a.toLowerCase())); + } + return { filter, tag: getTag("event", filter), type: "event" }; + } + return logger.throwArgumentError("unknown ProviderEvent", "event", _event); +} +function getTime$1() { return (new Date()).getTime(); } +function copyRequest(tx) { + // @TODO: copy the copy from contracts and use it from this + return tx; +} +class AbstractProvider { + #subs; + #plugins; + // null=unpaused, true=paused+dropWhilePaused, false=paused + #pausedState; + #networkPromise; + #anyNetwork; + #performCache; + #nextTimer; + #timers; + #disableCcipRead; + // @TODO: This should be a () => Promise so network can be + // done when needed; or rely entirely on _detectNetwork? + constructor(_network) { + 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.#performCache = new Map(); + this.#subs = new Map(); + this.#plugins = new Map(); + this.#pausedState = null; + this.#nextTimer = 0; + this.#timers = new Map(); + this.#disableCcipRead = false; + } + get provider() { return this; } + get plugins() { + return Array.from(this.#plugins.values()); + } + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.validate(this)); + return this; + } + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + set disableCcipRead(value) { this.#disableCcipRead = !!value; } + get disableCcipRead() { return this.#disableCcipRead; } + // Shares multiple identical requests made during the same 250ms + async #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); + } + }, 250); + } + return await perform; + } + 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 }; + } + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + } + catch (error) { } + // 4xx indicates the result is not present; stop + if (resp.statusCode >= 400 && resp.statusCode < 500) { + return logger.throwError(`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); + } + return logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, info: { urls, errorMessages } + }); + } + _wrapTransaction(tx, hash, blockNumber) { + return tx; + } + _detectNetwork() { + return logger.throwError("sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); + } + // Sub-classes should override this and handle PerformActionRequest requests, calling + // the super for any unhandled actions. + async _perform(req) { + return logger.throwError(`unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + // State + async getBlockNumber() { + return logger.getNumber(await this.#perform({ method: "getBlockNumber" }), "%response"); + } + // @TODO: Make this string | Promsie so no await needed if sync is possible + _getAddress(address) { + return resolveAddress(address, this); + /* + if (typeof(address) === "string") { + if (address.match(/^0x[0-9a-f]+$/i)) { return address; } + const resolved = await this.resolveName(address); + if (resolved == null) { throw new Error("not confiugred @TODO"); } + return resolved; + } + return address.getAddress(); + */ + } + _getBlockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return blockTag; + } + if (isHexString(blockTag)) { + if (dataLength(blockTag) === 32) { + return blockTag; + } + return toQuantity(blockTag); + } + if (typeof (blockTag) === "number") { + if (blockTag >= 0) { + return toQuantity(blockTag); + } + return this.getBlockNumber().then((b) => toQuantity(b + blockTag)); + } + return logger.throwArgumentError("invalid blockTag", "blockTag", blockTag); + } + async getNetwork() { + // 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 = this._detectNetwork().then((network) => { + this.emit("network", network, null); + return network; + }, (error) => { + // Reset the networkPromise on failure, so we will try again + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + }); + this.#networkPromise = detectNetwork; + return await detectNetwork; + } + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork() // 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 + logger.throwError(`network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone().freeze(); + } + async getFeeData() { + const { block, gasPrice } = await resolveProperties({ + block: this.getBlock("latest"), + gasPrice: ((async () => { + try { + const gasPrice = await this.#perform({ method: "getGasPrice" }); + return logger.getBigInt(gasPrice, "%response"); + } + catch (error) { } + return null; + })()) + }); + let maxFeePerGas = null, maxPriorityFeePerGas = null; + if (block && block.baseFeePerGas) { + // We may want to compute this more accurately in the future, + // using the formula "check if the base fee is correct". + // See: https://eips.ethereum.org/EIPS/eip-1559 + maxPriorityFeePerGas = BigInt("1500000000"); + // Allow a network to override their maximum priority fee per gas + //const priorityFeePlugin = (await this.getNetwork()).getPlugin("org.ethers.plugins.max-priority-fee"); + //if (priorityFeePlugin) { + // maxPriorityFeePerGas = await priorityFeePlugin.getPriorityFee(this); + //} + maxFeePerGas = (block.baseFeePerGas * BN_2$1) + maxPriorityFeePerGas; + } + return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + } + async _getTransaction(_request) { + const network = await this.getNetwork(); + // Fill in any addresses + const request = Object.assign({}, _request, await resolveProperties({ + to: (_request.to ? resolveAddress(_request.to, this) : undefined), + from: (_request.from ? resolveAddress(_request.from, this) : undefined), + })); + return network.formatter.transactionRequest(request); + } + async estimateGas(_tx) { + const transaction = await this._getTransaction(_tx); + return logger.getBigInt(await this.#perform({ + method: "estimateGas", transaction + }), "%response"); + } + async #call(tx, blockTag, attempt) { + if (attempt >= MAX_CCIP_REDIRECTS) { + logger.throwError("CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + } + const transaction = copyRequest(tx); + try { + return hexlify(await this._perform({ method: "call", transaction, blockTag })); + } + catch (error) { + // CCIP Read OffchainLookup + if (!this.disableCcipRead && isCallException(error) && 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; + try { + ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + } + catch (error) { + return logger.throwError(error.message, "OFFCHAIN_FAULT", { + reason: "BAD_DATA", + transaction, info: { data } + }); + } + // Check the sender of the OffchainLookup matches the transaction + if (ccipArgs.sender.toLowerCase() !== txSender.toLowerCase()) { + return logger.throwError("CCIP Read sender mismatch", "CALL_EXCEPTION", { + data, transaction, + errorSignature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + errorName: "OffchainLookup", + errorArgs: ccipArgs.errorArgs + }); + } + const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + if (ccipResult == null) { + return logger.throwError("CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + reason: "FETCH_FAILED", + transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } + }); + } + return this.#call({ + to: txSender, + data: concat([ + ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData]) + ]), + }, blockTag, attempt + 1); + } + throw error; + } + } + async call(_tx) { + const [tx, blockTag] = await Promise.all([ + this._getTransaction(_tx), this._getBlockTag(_tx.blockTag) + ]); + return this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1); + } + // Account + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + let blockTag = this._getBlockTag(_blockTag); + if (typeof (address) !== "string" || typeof (blockTag) !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await this.#perform(Object.assign(request, { address, blockTag })); + } + async getBalance(address, blockTag) { + return logger.getBigInt(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return logger.getNumber(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return hexlify(await this.#getAccountValue({ method: "getCode" }, address, blockTag)); + } + async getStorageAt(address, _position, blockTag) { + const position = logger.getBigInt(_position, "position"); + return hexlify(await this.#getAccountValue({ method: "getStorageAt", position }, address, blockTag)); + } + // Write + async broadcastTransaction(signedTx) { + throw new Error(); + return {}; + } + async #getBlock(block, includeTransactions) { + if (isHexString(block, 32)) { + return await this.#perform({ + method: "getBlock", blockHash: block, includeTransactions + }); + } + let blockTag = this._getBlockTag(block); + if (typeof (blockTag) !== "string") { + blockTag = await blockTag; + } + return await this.#perform({ + method: "getBlock", blockTag, includeTransactions + }); + } + // Queries + async getBlock(block) { + const [network, params] = await Promise.all([ + this.getNetwork(), this.#getBlock(block, false) + ]); + if (params == null) { + return null; + } + return network.formatter.block(params, this); + } + async getBlockWithTransactions(block) { + const format = (await this.getNetwork()).formatter; + const params = this.#getBlock(block, true); + if (params == null) { + return null; + } + return format.blockWithTransactions(params, this); + } + async getTransaction(hash) { + const format = (await this.getNetwork()).formatter; + const params = await this.#perform({ method: "getTransaction", hash }); + return format.transactionResponse(params, this); + } + async getTransactionReceipt(hash) { + const format = (await this.getNetwork()).formatter; + const receipt = await this.#perform({ method: "getTransactionReceipt", hash }); + if (receipt == null) { + return null; + } + // Some backends did not backfill the effectiveGasPrice into old transactions + // in the receipt, so we look it up manually and inject it. + if (receipt.gasPrice == null && receipt.effectiveGasPrice == null) { + const tx = await this.#perform({ method: "getTransaction", hash }); + receipt.effectiveGasPrice = tx.gasPrice; + } + return format.receipt(receipt, this); + } + async getTransactionResult(hash) { + const result = await this.#perform({ method: "getTransactionResult", hash }); + if (result == null) { + return null; + } + return hexlify(result); + } + _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$1(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + }); + const blockHash = ("blockHash" in filter) ? filter.blockHash : undefined; + const resolve = (_address, fromBlock, toBlock) => { + 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; + } + 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.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.toBlock); + } + 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 resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock); + } + // Bloom-filter Queries + async getLogs(_filter) { + const { network, filter } = await resolveProperties({ + network: this.getNetwork(), + filter: this._getFilter(_filter) + }); + return (await this.#perform({ method: "getLogs", filter })).map((l) => { + return network.formatter.log(l, this); + }); + } + // ENS + _getProvider(chainId) { + return logger.throwError("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) { + //if (typeof(name) === "string") { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + /* + } else { + const address = await name.getAddress(); + if (address == null) { + return logger.throwArgumentError("Addressable returned no address", "name", name); + } + return address; + } + */ + return null; + } + async lookupAddress(address) { + throw new Error(); + //return "TODO"; + } + async waitForTransaction(hash, confirms = 1, timeout) { + 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(logger.makeError("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); + } + listener(await this.getBlockNumber()); + }); + } + async waitForBlock(blockTag) { + throw new Error(); + //return new Block({ }, this); + } + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); + } + _setTimeout(_func, 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$1() }); + } + return timerId; + } + _forEachSubscriber(func) { + for (const sub of this.#subs.values()) { + func(sub.subscriber); + } + } + // Event API; sub-classes should override this; any supported + // event filter will have been munged into an EventFilter + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "network": + return new UnmanagedSubscriber(sub.type); + case "block": + return new PollingBlockSubscriber(this); + case "event": + return new PollingEventSubscriber(this, sub.filter); + case "transaction": + return new PollingTransactionSubscriber(this, sub.hash); + case "orphan": + return new PollingOrphanSubscriber(this, sub.filter); + } + throw new Error(`unsupported event: ${sub.type}`); + } + _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 (!sub) { + 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; + }); + 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); + } + // Sub-classes should override this to shutdown any sockets, etc. + // but MUST call this super.shutdown. + async shutdown() { + // Stop all listeners + this.removeAllListeners(); + // Shut down all tiemrs + for (const timerId of this.#timers.keys()) { + this._clearTimeout(timerId); + } + } + get paused() { return (this.#pausedState != null); } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } + else { + this.pause(false); + } + } + pause(dropWhilePaused) { + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; + } + return logger.throwError("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$1() - timer.time; + } + } + 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$1(); + // Start the timer + setTimeout(timer.func, timeout); + } + } +} +function _parseString(result, start) { + try { + const bytes = _parseBytes(result, start); + if (bytes) { + return toUtf8String(bytes); + } + } + catch (error) { } + return null; +} +function _parseBytes(result, start) { + if (result === "0x") { + return null; + } + try { + const offset = logger.getNumber(dataSlice(result, start, start + 32)); + const length = logger.getNumber(dataSlice(result, offset, offset + 32)); + return dataSlice(result, offset + 32, offset + 32 + length); + } + catch (error) { } + return null; +} +function numPad(value) { + const result = toArray(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) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +const empty = new Uint8Array([]); +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes(datas) { + const result = []; + 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 = logger.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) { + const result = { + sender: "", urls: [], calldata: "", selector: "", extraData: "", errorArgs: [] + }; + if (dataLength(data) < 5 * 32) { + throw new Error("insufficient OffchainLookup data"); + } + const sender = dataSlice(data, 0, 32); + if (dataSlice(sender, 0, 12) !== dataSlice(zeros, 0, 12)) { + throw new Error("corrupt OffchainLookup sender"); + } + result.sender = dataSlice(sender, 12); + // Read the URLs from the response + try { + const urls = []; + const urlsOffset = logger.getNumber(dataSlice(data, 32, 64)); + const urlsLength = logger.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) { + throw new Error("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) { + throw new Error("corrupt OffchainLookup calldata"); + } + // Get the callbackSelector (bytes4) + if (dataSlice(data, 100, 128) !== dataSlice(zeros, 0, 28)) { + throw new Error("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) { + throw new Error("corrupt OffchainLookup extraData"); + } + result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => result[k]); + return result; +} + +if (false) { + console.log(isHexString, isError); +} // @TODO +const defaultApiKey$2 = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB"; +const EtherscanPluginId = "org.ethers.plugins.etherscan"; +class EtherscanPlugin extends NetworkPlugin { + baseUrl; + communityApiKey; + constructor(baseUrl, communityApiKey) { + super(EtherscanPluginId); + //if (communityApiKey == null) { communityApiKey = null; } + defineProperties(this, { baseUrl, communityApiKey }); + } + clone() { + return new EtherscanPlugin(this.baseUrl, this.communityApiKey); + } +} +class EtherscanProvider extends AbstractProvider { + network; + apiKey; + constructor(_network, apiKey) { + super(); + const network = Network.from(_network); + if (apiKey == null) { + const plugin = network.getPlugin(EtherscanPluginId); + if (plugin) { + apiKey = plugin.communityApiKey; + } + else { + apiKey = defaultApiKey$2; + } + } + defineProperties(this, { apiKey, network }); + // Test that the network is supported by Etherscan + this.getBaseUrl(); + } + getBaseUrl() { + const plugin = this.network.getPlugin(EtherscanPluginId); + if (plugin) { + return plugin.baseUrl; + } + switch (this.network.name) { + case "homestead": + return "https:/\/api.etherscan.io"; + case "ropsten": + return "https:/\/api-ropsten.etherscan.io"; + case "rinkeby": + return "https:/\/api-rinkeby.etherscan.io"; + case "kovan": + return "https:/\/api-kovan.etherscan.io"; + case "goerli": + return "https:/\/api-goerli.etherscan.io"; + default: + } + return logger.throwArgumentError("unsupported network", "network", this.network); + } + getUrl(module, params) { + const query = Object.keys(params).reduce((accum, key) => { + const value = params[key]; + if (value != null) { + accum += `&${key}=${value}`; + } + return accum; + }, ""); + const apiKey = ((this.apiKey) ? `&apikey=${this.apiKey}` : ""); + return `${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`; + } + getPostUrl() { + return `${this.getBaseUrl()}/api`; + } + getPostData(module, params) { + params.module = module; + params.apikey = this.apiKey; + return params; + } + async detectNetwork() { + return this.network; + } + async fetch(module, params, post) { + const url = (post ? this.getPostUrl() : this.getUrl(module, params)); + const payload = (post ? this.getPostData(module, params) : null); + /* + this.emit("debug", { + action: "request", + request: url, + provider: this + }); + */ + const request = new FetchRequest(url); + request.processFunc = async (request, response) => { + const result = response.hasBody() ? JSON.parse(toUtf8String(response.body)) : {}; + const throttle = ((typeof (result.result) === "string") ? result.result : "").toLowerCase().indexOf("rate limit") >= 0; + if (module === "proxy") { + // This JSON response indicates we are being throttled + if (result && result.status == 0 && result.message == "NOTOK" && throttle) { + response.throwThrottleError(result.result); + } + } + else { + if (throttle) { + response.throwThrottleError(result.result); + } + } + return response; + }; + // @TODO: + //throttleSlotInterval: 1000, + if (payload) { + request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); + request.body = Object.keys(payload).map((k) => `${k}=${payload[k]}`).join("&"); + } + const response = await request.send(); + response.assertOk(); + if (!response.hasBody()) { + throw new Error(); + } + /* + this.emit("debug", { + action: "response", + request: url, + response: deepCopy(result), + provider: this + }); + */ + const result = JSON.parse(toUtf8String(response.body)); + if (module === "proxy") { + if (result.jsonrpc != "2.0") { + // @TODO: not any + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + throw error; + } + if (result.error) { + // @TODO: not any + const error = new Error(result.error.message || "unknown error"); + if (result.error.code) { + error.code = result.error.code; + } + if (result.error.data) { + error.data = result.error.data; + } + throw error; + } + return result.result; + } + else { + // getLogs, getHistory have weird success responses + if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { + return result.result; + } + if (result.status != 1 || result.message != "OK") { + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + // if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) { + // error.throttleRetry = true; + // } + throw error; + } + return result.result; + } + } + // The transaction has already been sanitized by the calls in Provider + _getTransactionPostData(transaction) { + const result = {}; + for (let key in transaction) { + if (transaction[key] == null) { + continue; + } + let value = transaction[key]; + if (key === "type" && value === 0) { + continue; + } + // Quantity-types require no leading zero, unless 0 + if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) { + value = toQuantity(hexlify(value)); + } + else if (key === "accessList") { + value = "[" + this.network.formatter.accessList(value).map((set) => { + return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; + }).join(",") + "]"; + } + else { + value = hexlify(value); + } + result[key] = value; + } + return result; + } + _checkError(req, error, transaction) { + /* + let body = ""; + if (isError(error, Logger.Errors.SERVER_ERROR) && error.response && error.response.hasBody()) { + body = toUtf8String(error.response.body); + } + console.log(body); + + // Undo the "convenience" some nodes are attempting to prevent backwards + // incompatibility; maybe for v6 consider forwarding reverts as errors + if (method === "call" && body) { + + // Etherscan keeps changing their string + if (body.match(/reverted/i) || body.match(/VM execution error/i)) { + + // Etherscan prefixes the data like "Reverted 0x1234" + let data = e.data; + if (data) { data = "0x" + data.replace(/^.*0x/i, ""); } + if (!isHexString(data)) { data = "0x"; } + + logger.throwError("call exception", Logger.Errors.CALL_EXCEPTION, { + error, data + }); + } + } + + // Get the message from any nested error structure + let message = error.message; + if (isError(error, Logger.Errors.SERVER_ERROR)) { + if (error.error && typeof(error.error.message) === "string") { + message = error.error.message; + } else if (typeof(error.body) === "string") { + message = error.body; + } else if (typeof(error.responseText) === "string") { + message = error.responseText; + } + } + message = (message || "").toLowerCase(); + + // "Insufficient funds. The account you tried to send transaction from + // does not have enough funds. Required 21464000000000 and got: 0" + if (message.match(/insufficient funds/)) { + logger.throwError("insufficient funds for intrinsic transaction cost", Logger.Errors.INSUFFICIENT_FUNDS, { + error, transaction, info: { method } + }); + } + + // "Transaction with the same hash was already imported." + if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { + logger.throwError("nonce has already been used", Logger.Errors.NONCE_EXPIRED, { + error, transaction, info: { method } + }); + } + + // "Transaction gas price is too low. There is another transaction with + // same nonce in the queue. Try increasing the gas price or incrementing the nonce." + if (message.match(/another transaction with same nonce/)) { + logger.throwError("replacement fee too low", Logger.Errors.REPLACEMENT_UNDERPRICED, { + error, transaction, info: { method } + }); + } + + if (message.match(/execution failed due to an exception|execution reverted/)) { + logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.Errors.UNPREDICTABLE_GAS_LIMIT, { + error, transaction, info: { method } + }); + } + */ + throw error; + } + async _detectNetwork() { + return this.network; + } + async _perform(req) { + switch (req.method) { + case "chainId": + return this.network.chainId; + case "getBlockNumber": + return this.fetch("proxy", { action: "eth_blockNumber" }); + case "getGasPrice": + return this.fetch("proxy", { action: "eth_gasPrice" }); + case "getBalance": + // Returns base-10 result + return this.fetch("account", { + action: "balance", + address: req.address, + tag: req.blockTag + }); + case "getTransactionCount": + return this.fetch("proxy", { + action: "eth_getTransactionCount", + address: req.address, + tag: req.blockTag + }); + case "getCode": + return this.fetch("proxy", { + action: "eth_getCode", + address: req.address, + tag: req.blockTag + }); + case "getStorageAt": + return this.fetch("proxy", { + action: "eth_getStorageAt", + address: req.address, + position: req.position, + tag: req.blockTag + }); + case "broadcastTransaction": + return this.fetch("proxy", { + action: "eth_sendRawTransaction", + hex: req.signedTransaction + }, true).catch((error) => { + return this._checkError(req, error, req.signedTransaction); + }); + case "getBlock": + if ("blockTag" in req) { + return this.fetch("proxy", { + action: "eth_getBlockByNumber", + tag: req.blockTag, + boolean: (req.includeTransactions ? "true" : "false") + }); + } + return logger.throwError("getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", { + operation: "getBlock(blockHash)" + }); + case "getTransaction": + return this.fetch("proxy", { + action: "eth_getTransactionByHash", + txhash: req.hash + }); + case "getTransactionReceipt": + return this.fetch("proxy", { + action: "eth_getTransactionReceipt", + txhash: req.hash + }); + case "call": { + if (req.blockTag !== "latest") { + throw new Error("EtherscanProvider does not support blockTag for call"); + } + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_call"; + try { + return await this.fetch("proxy", postData, true); + } + catch (error) { + return this._checkError(req, error, req.transaction); + } + } + case "estimateGas": { + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_estimateGas"; + try { + return await this.fetch("proxy", postData, true); + } + catch (error) { + return this._checkError(req, error, req.transaction); + } + } + /* + case "getLogs": { + // Needs to complain if more than one address is passed in + const args: Record = { action: "getLogs" } + + if (params.filter.fromBlock) { + args.fromBlock = checkLogTag(params.filter.fromBlock); + } + + if (params.filter.toBlock) { + args.toBlock = checkLogTag(params.filter.toBlock); + } + + if (params.filter.address) { + args.address = params.filter.address; + } + + // @TODO: We can handle slightly more complicated logs using the logs API + if (params.filter.topics && params.filter.topics.length > 0) { + if (params.filter.topics.length > 1) { + logger.throwError("unsupported topic count", Logger.Errors.UNSUPPORTED_OPERATION, { topics: params.filter.topics }); + } + if (params.filter.topics.length === 1) { + const topic0 = params.filter.topics[0]; + if (typeof(topic0) !== "string" || topic0.length !== 66) { + logger.throwError("unsupported topic format", Logger.Errors.UNSUPPORTED_OPERATION, { topic0: topic0 }); + } + args.topic0 = topic0; + } + } + + const logs: Array = await this.fetch("logs", args); + + // Cache txHash => blockHash + let blocks: { [tag: string]: string } = {}; + + // Add any missing blockHash to the logs + for (let i = 0; i < logs.length; i++) { + const log = logs[i]; + if (log.blockHash != null) { continue; } + if (blocks[log.blockNumber] == null) { + const block = await this.getBlock(log.blockNumber); + if (block) { + blocks[log.blockNumber] = block.hash; + } + } + + log.blockHash = blocks[log.blockNumber]; + } + + return logs; + } + */ + default: + break; + } + return super._perform(req); + } + async getNetwork() { + return this.network; + } + async getEtherPrice() { + if (this.network.name !== "homestead") { + return 0.0; + } + return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd); + } + isCommunityResource() { + const plugin = this.network.getPlugin(EtherscanPluginId); + if (plugin) { + return (plugin.communityApiKey === this.apiKey); + } + return (defaultApiKey$2 === this.apiKey); + } +} +/* +(async function() { + const provider = new EtherscanProvider(); + console.log(provider); + console.log(await provider.getBlockNumber()); + / * + provider.on("block", (b) => { + console.log("BB", b); + }); + console.log(await provider.getTransactionReceipt("0xa5ded92f548e9f362192f9ab7e5b3fbc9b5a919a868e29247f177d49ce38de6e")); + + provider.once("0xa5ded92f548e9f362192f9ab7e5b3fbc9b5a919a868e29247f177d49ce38de6e", (tx) => { + console.log("TT", tx); + }); + * / + try { + console.log(await provider.getBlock(100)); + } catch (error) { + console.log(error); + } + + try { + console.log(await provider.getBlock(13821768)); + } catch (error) { + console.log(error); + } + +})(); +*/ + +/** + * Exports the same Network as "./network.js" except with common + * networks injected registered. + */ +// See: https://chainlist.org +function injectCommonNetworks() { + /// Register popular Ethereum networks + function registerEth(name, chainId, options) { + const func = function () { + const network = new Network(name, chainId); + // We use 0 to disable ENS + if (options.ensNetwork != null) { + network.attachPlugin(new EnsPlugin(null, options.ensNetwork)); + } + if (options.priorityFee) { + // network.attachPlugin(new MaxPriorityFeePlugin(options.priorityFee)); + } + if (options.etherscan) { + const { url, apiKey } = options.etherscan; + network.attachPlugin(new EtherscanPlugin(url, apiKey)); + } + network.attachPlugin(new GasCostPlugin()); + return network; + }; + // Register the network by name and chain ID + Network.register(name, func); + Network.register(chainId, func); + if (options.altNames) { + options.altNames.forEach((name) => { + Network.register(name, func); + }); + } + } + registerEth("homestead", 1, { ensNetwork: 1, altNames: ["mainnet"] }); + registerEth("ropsten", 3, { ensNetwork: 3 }); + registerEth("rinkeby", 4, { ensNetwork: 4 }); + registerEth("goerli", 5, { ensNetwork: 5 }); + registerEth("kovan", 42, { ensNetwork: 42 }); + registerEth("classic", 61, {}); + registerEth("classicKotti", 6, {}); + registerEth("xdai", 100, { ensNetwork: 1 }); + // Polygon has a 35 gwei maxPriorityFee requirement + registerEth("matic", 137, { + ensNetwork: 1, + // priorityFee: 35000000000, + etherscan: { + apiKey: "W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7", + url: "https:/\/api.polygonscan.com/" + } + }); + registerEth("maticMumbai", 80001, { + // priorityFee: 35000000000, + etherscan: { + apiKey: "W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7", + url: "https:/\/api-testnet.polygonscan.com/" + } + }); + registerEth("bnb", 56, { + ensNetwork: 1, + etherscan: { + apiKey: "EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9", + url: "http:/\/api.bscscan.com" + } + }); + registerEth("bnbt", 97, { + etherscan: { + apiKey: "EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9", + url: "http:/\/api-testnet.bscscan.com" + } + }); +} +injectCommonNetworks(); + +//const BN_0 = BigInt("0"); +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$2(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +function getTime() { return (new Date()).getTime(); } +; +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 +}; +async function waitForSync(config, blockNumber) { + while (config.blockNumber < 0 || config.blockNumber < blockNumber) { + if (!config._updateNumber) { + config._updateNumber = (async () => { + const blockNumber = await config.provider.getBlockNumber(); + if (blockNumber > config.blockNumber) { + config.blockNumber = blockNumber; + } + config._updateNumber = null; + })(); + } + await config._updateNumber; + config.outOfSync++; + } +} +// Normalizes a result to a string that can be used to compare against +// other results using normal string equality +function normalize(network, value, req) { + switch (req.method) { + case "chainId": + return logger.getBigInt(value).toString(); + case "getBlockNumber": + return logger.getNumber(value).toString(); + case "getGasPrice": + return logger.getBigInt(value).toString(); + case "getBalance": + return logger.getBigInt(value).toString(); + case "getTransactionCount": + return logger.getNumber(value).toString(); + case "getCode": + return hexlify(value); + case "getStorageAt": + return hexlify(value); + case "getBlock": + if (req.includeTransactions) { + return JSON.stringify(network.formatter.blockWithTransactions(value)); + } + return JSON.stringify(network.formatter.block(value)); + case "getTransaction": + return JSON.stringify(network.formatter.transactionResponse(value)); + case "getTransactionReceipt": + return JSON.stringify(network.formatter.receipt(value)); + case "call": + return hexlify(value); + case "estimateGas": + return logger.getBigInt(value).toString(); + case "getLogs": + return JSON.stringify(value.map((v) => network.formatter.log(v))); + } + return logger.throwError("unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${JSON.stringify(req.method)})` + }); +} +// This strategy picks the highest wieght result, as long as the weight is +// equal to or greater than quorum +function checkQuorum(quorum, results) { + const tally = new Map(); + for (const { result, normal, weight } of results) { + const t = tally.get(normal) || { result, weight: 0 }; + t.weight += weight; + tally.set(normal, t); + } + let bestWeight = 0; + let bestResult = undefined; + for (const { weight, result } of tally.values()) { + if (weight >= quorum && weight > bestWeight) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +/* +function getMean(results: Array): bigint { + const total = results.reduce((a, r) => (a + BigInt(r.result)), BN_0); + return total / BigInt(results.length); +} +*/ +function getMedian(results) { + // Get the sorted values + const values = results.map((r) => BigInt(r.result)); + values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0)); + const mid = 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 getFuzzyMode(quorum, results) { + if (quorum === 1) { + return logger.getNumber(getMedian(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, result } of results) { + const r = logger.getNumber(result); + 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; +} +class FallbackProvider extends AbstractProvider { + //readonly providerConfigs!: ReadonlyArray>>; + quorum; + eventQuorum; + eventWorkers; + #configs; + #height; + #initialSyncPromise; + constructor(providers, network) { + super(network); + 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; + this.quorum = 2; //Math.ceil(providers.length / 2); + this.eventQuorum = 1; + this.eventWorkers = 1; + if (this.quorum > this.#configs.reduce((a, c) => (a + c.weight), 0)) { + logger.throwArgumentError("quorum exceed provider wieght", "quorum", this.quorum); + } + } + // @TOOD: Copy these and only return public values + get providerConfigs() { + return this.#configs.slice(); + } + async _detectNetwork() { + return Network.from(logger.getBigInt(await this._perform({ method: "chainId" }))).freeze(); + } + // @TODO: Add support to select providers to be the event subscriber + //_getSubscriber(sub: Subscription): Subscriber { + // throw new Error("@TODO"); + //} + // Grab the next (random) config that is not already part of configs + #getNextConfig(configs) { + // Shuffle the states, sorted by priority + const allConfigs = this.#configs.slice(); + shuffle(allConfigs); + allConfigs.sort((a, b) => (b.priority - a.priority)); + for (const config of allConfigs) { + if (configs.indexOf(config) === -1) { + return config; + } + } + return null; + } + // Adds a new runner (if available) to running. + #addRunner(running, req) { + const config = this.#getNextConfig(Array.from(running).map((r) => r.config)); + if (config == null) { + return null; + } + const result = {}; + const runner = { + config, result, didBump: false, done: false, + perform: null, staller: null + }; + const now = getTime(); + runner.perform = (async () => { + try { + config.requests++; + result.result = await config.provider._perform(req); + } + catch (error) { + config.errorResponses++; + result.error = error; + } + if (runner.done) { + config.lateResponses++; + } + const dt = (getTime() - now); + config._totalTime += dt; + config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt; + runner.perform = null; + })(); + runner.staller = (async () => { + await stall$2(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(waitForSync(config, 0)); + promises.push((async () => { + 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) { + const network = (config._network); + if (chainId == null) { + chainId = network.chainId; + } + else if (network.chainId !== chainId) { + logger.throwError("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 ("result" in runner.result) { + const result = runner.result.result; + results.push({ + result, + normal: normalize((runner.config._network), result, req), + 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) { + const height = Math.ceil(logger.getNumber(getMedian(this.#configs.map((c) => ({ + result: c.blockNumber, + normal: logger.getNumber(c.blockNumber).toString(), + weight: c.weight + }))), "%internal")); + this.#height = height; + } + const mode = getFuzzyMode(this.quorum, results); + if (mode === undefined) { + return undefined; + } + if (mode > this.#height) { + this.#height = mode; + } + return this.#height; + } + case "getGasPrice": + case "estimateGas": + return getMedian(results); + case "getBlock": + // Pending blocks are mempool dependant and already + // quite untrustworthy + if ("blockTag" in req && req.blockTag === "pending") { + return results[0].result; + } + return checkQuorum(this.quorum, results); + case "chainId": + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorageAt": + case "getTransaction": + case "getTransactionReceipt": + case "getLogs": + return checkQuorum(this.quorum, results); + case "call": + // @TODO: Check errors + return checkQuorum(this.quorum, results); + case "broadcastTransaction": + throw new Error("TODO"); + } + return logger.throwError("unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${JSON.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 = []; + //const results: Array = [ ]; + //const errors: Array = [ ]; + let newRunners = 0; + for (const runner of running) { + // @TODO: use runner.perfom != null + /* + if ("result" in runner.result) { + results.push(runner.result.result); + } else if ("error" in runner.result) { + errors.push(runner.result.error); + } +*/ + // 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 for quorum + /* + console.log({ results, errors } ); + if (results.length >= this.quorum) { + return results[0]; + } + + if (errors.length >= this.quorum) { + return errors[0]; + } + */ + 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); + } + if (interesting.length === 0) { + throw new Error("quorum not met"); + // return logger.throwError("failed to meet quorum", "", { + // }); + } + // Wait for someone to either complete its perform or trigger a stall + await Promise.race(interesting); + return await this.#waitForQuorum(running, req); + } + async _perform(req) { + await this.#initialSync(); + // Bootstrap enough to meet quorum + const running = new Set(); + for (let i = 0; i < this.quorum; i++) { + this.#addRunner(running, req); + } + const result = this.#waitForQuorum(running, req); + for (const runner of running) { + runner.done = true; + } + return result; + } +} + +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +class FilterIdSubscriber { + #provider; + #filterIdPromise; + #poller; + #network; + constructor(provider) { + this.#provider = provider; + this.#filterIdPromise = null; + this.#poller = this.#poll.bind(this); + this.#network = null; + } + _subscribe(provider) { + throw new Error("subclasses must override this"); + } + _emitResults(provider, result) { + throw new Error("subclasses must override this"); + } + _recover(provider) { + throw new Error("subclasses must override this"); + } + async #poll(blockNumber) { + try { + if (this.#filterIdPromise == null) { + this.#filterIdPromise = this._subscribe(this.#provider); + } + const filterId = await this.#filterIdPromise; + if (filterId == null) { + this.#provider._recoverSubscriber(this, this._recover(this.#provider)); + return; + } + const network = await this.#provider.getNetwork(); + if (!this.#network) { + this.#network = network; + } + if (this.#network.chainId !== network.chainId) { + throw new Error("chaid changed"); + } + const result = await this.#provider.send("eth_getFilterChanges", [filterId]); + await this._emitResults(this.#provider, result); + } + catch (error) { + console.log("@TODO", error); + } + this.#provider.once("block", this.#poller); + } + #teardown() { + const filterIdPromise = this.#filterIdPromise; + if (filterIdPromise) { + this.#filterIdPromise = null; + filterIdPromise.then((filterId) => { + this.#provider.send("eth_uninstallFilter", [filterId]); + }); + } + } + start() { this.#poll(-2); } + stop() { + this.#teardown(); + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#teardown(); + } + this.#provider.off("block", this.#poller); + } + resume() { this.start(); } +} +class FilterIdEventSubscriber extends FilterIdSubscriber { + #event; + constructor(provider, filter) { + super(provider); + this.#event = copy(filter); + } + _recover(provider) { + return new PollingEventSubscriber(provider, this.#event); + } + async _subscribe(provider) { + const filterId = await provider.send("eth_newFilter", [this.#event]); + console.log("____SUB", filterId); + return filterId; + } + async _emitResults(provider, results) { + const network = await provider.getNetwork(); + for (const result of results) { + const log = network.formatter.log(result, provider); + provider.emit(this.#event, log); + } + } +} +class FilterIdPendingSubscriber extends FilterIdSubscriber { + async _subscribe(provider) { + return await provider.send("eth_newPendingTransactionFilter", []); + } + async _emitResults(provider, results) { + const network = await provider.getNetwork(); + for (const result of results) { + provider.emit("pending", network.formatter.hash(result)); + } + } +} + +// @TODO: +//function copy(value: T): T { +// return JSON.parse(JSON.stringify(value)); +//} +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 getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +function isPollable(value) { + return (value && typeof (value.pollingInterval) === "number"); +} +const defaultOptions = { + polling: false, + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: (1 << 20), + batchMaxCount: 100 // 100 requests +}; +// @TODO: Unchecked Signers +class JsonRpcSigner extends AbstractSigner { + address; + constructor(provider, address) { + super(provider); + defineProperties(this, { address }); + } + connect(provider) { + return logger.throwError("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); + } + //async getNetwork(): Promise> { + // return await this.provider.getNetwork(); + //} + //async estimateGas(tx: TransactionRequest): Promise { + // return await this.provider.estimateGas(tx); + //} + //async call(tx: TransactionRequest): Promise { + // return await this.provider.call(tx); + //} + //async resolveName(name: string | Addressable): Promise { + // return await this.provider.resolveName(name); + //} + //async getNonce(blockTag?: BlockTag): Promise { + // return await this.provider.getTransactionCountOf(this.address); + //} + // 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); + if (from == null || from.toLowerCase() !== this.address.toLowerCase()) { + logger.throwArgumentError("from address mismatch", "transaction", _tx); + } + tx.from = from; + })()); + } + else { + tx.from = this.address; + } + // The JSON-RPC for eth_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("eth_sendTransaction", [hexTx]); + } + async sendTransaction(tx) { + // This cannot be mined any earlier than any recent block + const blockNumber = await this.provider.getBlockNumber(); + // 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]; + const checkTx = async () => { + // Try getting the transaction + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(this.provider._wrapTransaction(tx, hash, blockNumber)); + return; + } + // 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); + if (from == null || from.toLowerCase() !== this.address.toLowerCase()) { + return logger.throwArgumentError("from address mismatch", "transaction", _tx); + } + tx.from = from; + } + else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("eth_sign_Transaction", [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); + if (address == null) { + return logger.throwArgumentError("TypedData does not support null address", "value", value); + } + return address; + }); + return await this.provider.send("eth_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#eth_sign + async _legacySignMessage(_message) { + const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message); + return await this.provider.send("eth_sign", [ + this.address.toLowerCase(), hexlify(message) + ]); + } +} +class JsonRpcApiProvider extends AbstractProvider { + #options; + #nextId; + #payloads; + #drainTimer; + constructor(network, options) { + super(network); + this.#nextId = 1; + this.#options = Object.assign({}, defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + // This could be relaxed in the future to just check equivalent networks + const staticNetwork = this._getOption("staticNetwork"); + if (staticNetwork && staticNetwork !== network) { + logger.throwArgumentError("staticNetwork MUST match network object", "options", options); + } + } + _getOption(key) { + return this.#options[key]; + } + // @TODO: Merge this into send + //prepareRequest(method: string, params: Array): JsonRpcPayload { + // return { + // method, params, id: (this.#nextId++), jsonrpc: "2.0" + // }; + //} + /* + async send(method: string, params: Array): Promise { + // @TODO: This should construct and queue the payload + throw new Error("sub-class must implement this"); + } + */ + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + 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 payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload)); + this.emit("debug", { action: "sendRpcPayload", payload }); + 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) { + // 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) { + return reject(new Error("@TODO: no result")); + } + // The response is an error + if ("error" in resp) { + return reject(this.getRpcError(payload, resp)); + } + // 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); + } + } + })(); + } + }, this.#options.batchStallTime); + } + // Sub-classes should **NOT** override this + send(method, params) { + // @TODO: cache chainId?? purge on switch_networks + const id = this.#nextId++; + const promise = new Promise((resolve, reject) => { + this.#payloads.push({ + resolve, reject, + payload: { method, params, id, jsonrpc: "2.0" } + }); + }); + // If there is not a pending drainTimer, set one + this.#scheduleDrain(); + return promise; + } + // Sub-classes MUST override this + _send(payload) { + return logger.throwError("sub-classes must override _send", "UNSUPPORTED_OPERATION", { + operation: "jsonRpcApiProvider._send" + }); + } + async getSigner(address = 0) { + const accountsPromise = this.send("eth_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 [network, accounts] = await Promise.all([this.getNetwork(), accountsPromise]); + // Account address + address = network.formatter.address(address); + for (const account of accounts) { + if (network.formatter.address(account) === account) { + return new JsonRpcSigner(this, account); + } + } + throw new Error("invalid account"); + } + // Sub-classes can override this; it detects the *actual* network we + // are connected to + async _detectNetwork() { + // We have a static network (like INFURA) + const network = this._getOption("staticNetwork"); + if (network) { + return network; + } + return Network.from(logger.getBigInt(await this._perform({ method: "chainId" }))); + } + _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); + } + // Normalize a JSON-RPC transaction + 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(logger.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; + } + // Get the necessary paramters for making a JSON-RPC request + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "eth_chainId", args: [] }; + case "getBlockNumber": + return { method: "eth_blockNumber", args: [] }; + case "getGasPrice": + return { method: "eth_gasPrice", args: [] }; + case "getBalance": + return { + method: "eth_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "eth_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "eth_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorageAt": + return { + method: "eth_getStorageAt", + args: [ + getLowerCase(req.address), + ("0x" + req.position.toString(16)), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "eth_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "eth_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] + }; + } + else if ("blockHash" in req) { + return { + method: "eth_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] + }; + } + break; + case "getTransaction": + return { + method: "eth_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "eth_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "eth_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "eth_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + 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: "eth_getLogs", args: [req.filter] }; + } + return null; + } + getRpcError(payload, error) { + console.log("getRpcError", payload, error); + return new Error(`JSON-RPC badness; @TODO: ${error}`); + /* + if (payload.method === "eth_call") { + const result = spelunkData(error); + if (result) { + // @TODO: Extract errorSignature, errorName, errorArgs, reason if + // it is Error(string) or Panic(uint25) + return logger.makeError("execution reverted during JSON-RPC call", "CALL_EXCEPTION", { + data: result.data, + transaction: args[0] + }); + } + + return logger.makeError("missing revert data during JSON-RPC call", "CALL_EXCEPTION", { + data: "0x", transaction: args[0], info: { error } + }); + } + + if (method === "eth_estimateGas") { + // @TODO: Spelunk, and adapt the above to allow missing data. + // Then throw an UNPREDICTABLE_GAS exception + } + + const message = JSON.stringify(spelunkMessage(error)); + + if (message.match(/insufficient funds|base fee exceeds gas limit/)) { + return logger.makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: args[0] + }); + } + + if (message.match(/nonce/) && message.match(/too low/)) { + return logger.makeError("nonce has already been used", "NONCE_EXPIRED", { + transaction: args[0] + }); + } + + // "replacement transaction underpriced" + if (message.match(/replacement transaction/) && message.match(/underpriced/)) { + return logger.makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { + transaction: args[0] + }); + } + + if (message.match(/only replay-protected/)) { + return logger.makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, info: { transaction: args[0] } + }); + } + + if (method === "estimateGas" && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) { + return logger.makeError("cannot estimate gas; transaction may fail or may require manual gas limit", "UNPREDICTABLE_GAS_LIMIT", { + transaction: args[0] + }); + } + + return error; + */ + } + 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 + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && logger.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(); + 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); + /* + @TODO: Add debug output to send + this.emit("debug", { type: "sendRequest", request }); + try { + const result = + //console.log("RR", result); + this.emit("debug", { type: "getResponse", result }); + return result; + } catch (error) { + this.emit("debug", { type: "getError", error }); + throw error; + //throw this.getRpcError(request.method, request.args, error); + } + */ + } + return super._perform(req); + } +} +class JsonRpcProvider extends JsonRpcApiProvider { + #connect; + #pollingInterval; + constructor(url, network, options) { + if (url == null) { + url = "http:/\/localhost:8545"; + } + super(network, options); + if (typeof (url) === "string") { + this.#connect = new FetchRequest(url); + } + else { + this.#connect = url.clone(); + } + this.#pollingInterval = 4000; + } + async _send(payload) { + // Configure a POST connection for the requested method + const request = this.#connect.clone(); + request.body = JSON.stringify(payload); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; + } + get pollingInterval() { return this.#pollingInterval; } + set pollingInterval(value) { + if (!Number.isInteger(value) || value < 0) { + throw new Error("invalid interval"); + } + this.#pollingInterval = value; + this._forEachSubscriber((sub) => { + if (isPollable(sub)) { + sub.pollingInterval = this.#pollingInterval; + } + }); + } +} +// This class should only be used when it is not possible for the +// underlying network to change, such as with INFURA. If you are +// using MetaMask or some other client which allows users to change +// their network DO NOT USE THIS. Bad things will happen. +/* +export class StaticJsonRpcProvider extends JsonRpcProvider { + readonly network!: Network; + + constructor(url: string | ConnectionInfo, network?: Network, options?: JsonRpcOptions) { + super(url, network, options); + defineProperties(this, { network }); + } + + async _detectNetwork(): Promise { + return this.network; + } +} +*/ +/* +function spelunkData(value: any): null | { message: string, data: string } { + if (value == null) { return null; } + + // These *are* the droids we're looking for. + if (typeof(value.message) === "string" && value.message.match("reverted") && 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: any, result: Array): void { + 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: any): Array { + const result: Array = [ ]; + _spelunkMessage(value, result); + return result; +} +*/ + +// Show the throttle message only once +const shown = new Set(); +function showThrottleMessage(service) { + if (shown.has(service)) { + return; + } + shown.add(service); + console.log("========= NOTICE ========="); + console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`); + console.log(""); + console.log("The default API keys for each service are provided as a highly-throttled,"); + console.log("community resource for low-traffic projects and early prototyping."); + console.log(""); + console.log("While your application will continue to function, we highly recommended"); + console.log("signing up for your own API keys to improve performance, increase your"); + console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); + console.log(""); + console.log("For more details: https:/\/docs.ethers.io/api-keys/"); + console.log("=========================="); +} + +const defaultApiKey$1 = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; +function getHost$2(name) { + switch (name) { + case "homestead": + return "eth-mainnet.alchemyapi.io"; + case "ropsten": + return "eth-ropsten.alchemyapi.io"; + case "rinkeby": + return "eth-rinkeby.alchemyapi.io"; + case "goerli": + return "eth-goerli.alchemyapi.io"; + case "kovan": + return "eth-kovan.alchemyapi.io"; + case "matic": + return "polygon-mainnet.g.alchemy.com"; + case "maticmum": + return "polygon-mumbai.g.alchemy.com"; + case "arbitrum": + return "arb-mainnet.g.alchemy.com"; + case "arbitrum-rinkeby": + return "arb-rinkeby.g.alchemy.com"; + case "optimism": + return "opt-mainnet.g.alchemy.com"; + case "optimism-kovan": + return "opt-kovan.g.alchemy.com"; + } + return logger.throwArgumentError("unsupported network", "network", name); +} +class AlchemyProvider extends JsonRpcProvider { + apiKey; + constructor(_network = "homestead", apiKey) { + const network = Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey$1; + } + const request = AlchemyProvider.getRequest(network, apiKey); + super(request, network, { staticNetwork: network }); + defineProperties(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AlchemyProvider(chainId, this.apiKey); + } + catch (error) { } + return super._getProvider(chainId); + } + async _perform(req) { + // https://docs.alchemy.com/reference/trace-transaction + if (req.method === "getTransactionResult") { + const trace = await this.send("trace_transaction", [req.hash]); + if (trace == null) { + return null; + } + let data; + let error = false; + try { + data = trace[0].result.output; + error = (trace[0].error === "Reverted"); + } + catch (error) { } + if (data) { + if (error) { + logger.throwError("an error occurred during transaction executions", "CALL_EXCEPTION", { + data + }); + } + return data; + } + return logger.throwError("could not parse trace result", "BAD_DATA", { value: trace }); + } + return await super._perform(req); + } + isCommunityResource() { + return (this.apiKey === defaultApiKey$1); + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey$1; + } + const request = new FetchRequest(`https:/\/${getHost$2(network.name)}/v2/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey$1) { + request.retryFunc = async (request, response, attempt) => { + showThrottleMessage("alchemy"); + return true; + }; + } + return request; + } +} + +const defaultApiKey = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; +function getHost$1(name) { + switch (name) { + case "homestead": + return "rpc.ankr.com/eth"; + case "ropsten": + return "rpc.ankr.com/eth_ropsten"; + case "rinkeby": + return "rpc.ankr.com/eth_rinkeby"; + case "goerli": + return "rpc.ankr.com/eth_goerli"; + case "matic": + return "rpc.ankr.com/polygon"; + case "arbitrum": + return "rpc.ankr.com/arbitrum"; + } + return logger.throwArgumentError("unsupported network", "network", name); +} +class AnkrProvider extends JsonRpcProvider { + apiKey; + constructor(_network = "homestead", apiKey) { + const network = Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey; + } + // Ankr does not support filterId, so we force polling + const options = { polling: true, staticNetwork: network }; + const request = AnkrProvider.getRequest(network, apiKey); + super(request, network, options); + defineProperties(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AnkrProvider(chainId, this.apiKey); + } + catch (error) { } + return super._getProvider(chainId); + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = new FetchRequest(`https:/\/${getHost$1(network.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request, response, attempt) => { + showThrottleMessage("AnkrProvider"); + return true; + }; + } + return request; + } + isCommunityResource() { + return (this.apiKey === defaultApiKey); + } +} + +class CloudflareProvider extends JsonRpcProvider { + constructor(_network = "homestead") { + const network = Network.from(_network); + if (network.name !== "homestead") { + return logger.throwArgumentError("unsupported network", "network", _network); + } + super("https:/\/cloudflare-eth.com/", network, { staticNetwork: network }); + } +} + +const defaultProjectId = "84842078b09946638c03157f83405213"; +function getHost(name) { + switch (name) { + case "homestead": + return "mainnet.infura.io"; + case "ropsten": + return "ropsten.infura.io"; + case "rinkeby": + return "rinkeby.infura.io"; + case "kovan": + return "kovan.infura.io"; + case "goerli": + return "goerli.infura.io"; + case "matic": + return "polygon-mainnet.infura.io"; + case "maticmum": + return "polygon-mumbai.infura.io"; + case "optimism": + return "optimism-mainnet.infura.io"; + case "optimism-kovan": + return "optimism-kovan.infura.io"; + case "arbitrum": + return "arbitrum-mainnet.infura.io"; + case "arbitrum-rinkeby": + return "arbitrum-rinkeby.infura.io"; + } + return logger.throwArgumentError("unsupported network", "network", name); +} +class InfuraProvider extends JsonRpcProvider { + projectId; + projectSecret; + constructor(_network = "homestead", projectId, projectSecret) { + const network = Network.from(_network); + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = InfuraProvider.getRequest(network, projectId, projectSecret); + super(request, network, { staticNetwork: network }); + defineProperties(this, { projectId, projectSecret }); + } + _getProvider(chainId) { + try { + return new InfuraProvider(chainId, this.projectId, this.projectSecret); + } + catch (error) { } + return super._getProvider(chainId); + } + static getRequest(network, projectId, projectSecret) { + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = new FetchRequest(`https:/\/${getHost(network.name)}/v3/${projectId}`); + request.allowGzip = true; + if (projectSecret) { + request.setCredentials("", projectSecret); + } + if (projectId === defaultProjectId) { + request.retryFunc = async (request, response, attempt) => { + showThrottleMessage("InfuraProvider"); + return true; + }; + } + return request; + } + isCommunityResource() { + return (this.projectId === defaultProjectId); + } +} + +const IpcSocketProvider = undefined; + +/** + * SocketProvider + * + * Generic long-lived socket provider. + * + * Sub-classing notes + * - a sub-class MUST call the `_start()` method once connected + * - a sub-class MUST override the `_write(string)` method + * - a sub-class MUST call `_processMessage(string)` for each message + */ +class SocketSubscriber { + #provider; + #filter; + get filter() { return JSON.parse(this.#filter); } + #filterId; + #paused; + #emitPromise; + constructor(provider, filter) { + this.#provider = provider; + this.#filter = JSON.stringify(filter); + this.#filterId = null; + this.#paused = null; + this.#emitPromise = null; + } + start() { + this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId) => { + ; + this.#provider._register(filterId, this); + return filterId; + }); + } + stop() { + (this.#filterId).then((filterId) => { + this.#provider.send("eth_unsubscribe", [filterId]); + }); + this.#filterId = null; + } + // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs + // and resume + pause(dropWhilePaused) { + if (!dropWhilePaused) { + logger.throwError("preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { + operation: "pause(false)" + }); + } + this.#paused = !!dropWhilePaused; + } + resume() { + this.#paused = null; + } + _handleMessage(message) { + if (this.#filterId == null) { + return; + } + if (this.#paused === null) { + let emitPromise = this.#emitPromise; + if (emitPromise == null) { + emitPromise = this._emit(this.#provider, message); + } + else { + emitPromise = emitPromise.then(async () => { + await this._emit(this.#provider, message); + }); + } + this.#emitPromise = emitPromise.then(() => { + if (this.#emitPromise === emitPromise) { + this.#emitPromise = null; + } + }); + } + } + async _emit(provider, message) { + throw new Error("sub-classes must implemente this; _emit"); + } +} +class SocketBlockSubscriber extends SocketSubscriber { + constructor(provider) { + super(provider, ["newHeads"]); + } + async _emit(provider, message) { + provider.emit("block", parseInt(message.number)); + } +} +class SocketPendingSubscriber extends SocketSubscriber { + constructor(provider) { + super(provider, ["newPendingTransactions"]); + } + async _emit(provider, message) { + provider.emit("pending", message); + } +} +class SocketEventSubscriber extends SocketSubscriber { + #logFilter; + get logFilter() { return JSON.parse(this.#logFilter); } + #formatter; + constructor(provider, filter) { + super(provider, ["logs", filter]); + this.#logFilter = JSON.stringify(filter); + this.#formatter = provider.getNetwork().then((network) => network.formatter); + } + async _emit(provider, message) { + const formatter = await this.#formatter; + provider.emit(this.#logFilter, formatter.log(message, provider)); + } +} +class SocketProvider extends JsonRpcApiProvider { + #callbacks; + #ready; + // Maps each filterId to its subscriber + #subs; + // If any events come in before a subscriber has finished + // registering, queue them + #pending; + constructor(network) { + super(network, { batchMaxCount: 1 }); + this.#callbacks = new Map(); + this.#ready = false; + this.#subs = new Map(); + this.#pending = new Map(); + } + _getSubscriber(sub) { + switch (sub.type) { + case "close": + return new UnmanagedSubscriber("close"); + case "block": + return new SocketBlockSubscriber(this); + case "pending": + return new SocketPendingSubscriber(this); + case "event": + return new SocketEventSubscriber(this, sub.filter); + case "orphan": + // Handled auto-matically within AbstractProvider + // when the log.removed = true + if (sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("drop-log"); + } + } + return super._getSubscriber(sub); + } + _register(filterId, subscriber) { + this.#subs.set(filterId, subscriber); + const pending = this.#pending.get(filterId); + if (pending) { + for (const message of pending) { + subscriber._handleMessage(message); + } + this.#pending.delete(filterId); + } + } + async _send(payload) { + // WebSocket provider doesn't accept batches + assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload); + // @TODO: stringify payloads here and store to prevent mutations + const promise = new Promise((resolve, reject) => { + this.#callbacks.set(payload.id, { payload, resolve, reject }); + }); + if (this.#ready) { + await this._write(JSON.stringify(payload)); + } + return [await promise]; + } + // Sub-classes must call this once they are connected + async _start() { + if (this.#ready) { + return; + } + this.#ready = true; + for (const { payload } of this.#callbacks.values()) { + await this._write(JSON.stringify(payload)); + } + } + // Sub-classes must call this for each message + async _processMessage(message) { + const result = (JSON.parse(message)); + if ("id" in result) { + const callback = this.#callbacks.get(result.id); + if (callback == null) { + console.log("Weird... Response for not a thing we sent"); + return; + } + this.#callbacks.delete(result.id); + if ("error" in result) { + const { message, code, data } = result.error; + const error = logger.makeError(message || "unkonwn error", "SERVER_ERROR", { + request: `ws:${JSON.stringify(callback.payload)}`, + info: { code, data } + }); + callback.reject(error); + } + else { + callback.resolve(result.result); + } + } + else if (result.method === "eth_subscription") { + const filterId = result.params.subscription; + const subscriber = this.#subs.get(filterId); + if (subscriber) { + subscriber._handleMessage(result.params.result); + } + else { + let pending = this.#pending.get(filterId); + if (pending == null) { + pending = []; + this.#pending.set(filterId, pending); + } + pending.push(result.params.result); + } + } + } + async _write(message) { + throw new Error("sub-classes must override this"); + } +} + +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const _WebSocket = getGlobal().WebSocket; + +class WebSocketProvider extends SocketProvider { + url; + #websocket; + get websocket() { return this.#websocket; } + constructor(url, network) { + super(network); + if (typeof (url) === "string") { + this.#websocket = new _WebSocket(url); + } + else { + this.#websocket = url; + } + this.websocket.onopen = () => { + this._start(); + }; + this.websocket.onmessage = (message) => { + this._processMessage(message.data); + }; + } + async _write(message) { + this.websocket.send(message); + } +} + +/* +export { + AbstractProvider, UnmanagedSubscriber +} from "./abstract-provider.js"; +*/ + +class EventLog extends Log { + interface; + fragment; + args; + constructor(log, iface, fragment) { + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + defineProperties(this, { args, fragment, interface: iface }); + } + get eventName() { return this.fragment.name; } + get eventSignature() { return this.fragment.format(); } +} +class ContractTransactionReceipt extends TransactionReceipt { + #interface; + constructor(iface, provider, tx) { + super(tx, provider); + this.#interface = iface; + } + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? this.#interface.getEvent(log.topics[0]) : null; + if (fragment) { + return new EventLog(log, this.#interface, fragment); + } + else { + return log; + } + }); + } +} +class ContractTransactionResponse extends TransactionResponse { + #interface; + constructor(iface, provider, tx) { + super(tx, provider); + this.#interface = iface; + } + async wait(confirms) { + const receipt = await super.wait(); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(this.#interface, this.provider, receipt); + } +} +class ContractEventPayload extends EventPayload { + fragment; + log; + args; + constructor(contract, listener, filter, fragment, _log) { + super(contract, listener, filter); + const log = new EventLog(_log, contract.interface, fragment); + const args = contract.interface.decodeEventLog(fragment, log.data, log.topics); + defineProperties(this, { args, fragment, log }); + } + get eventName() { + return this.fragment.name; + } + get eventSignature() { + return this.fragment.format(); + } + async getBlock() { + return await this.log.getBlock(); + } + async getTransaction() { + return await this.log.getTransaction(); + } + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); + } +} + +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 concisify(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +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) => { + return param.walkAsync(args[index], (type, value) => { + if (type === "address") { + 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 _WrappedMethodBase() { + return Function; +} +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; +} +async function copyOverrides(arg) { + // Create a shallow copy (we'll deep-ify anything needed during normalizing) + const overrides = copyRequest$1(Typed.dereference(arg, "overrides")); + // Some sanity checking; these are what these methods adds + //if ((overrides).to) { + if (overrides.to) { + logger.throwArgumentError("cannot override to", "overrides.to", overrides.to); + } + else if (overrides.data) { + logger.throwArgumentError("cannot override data", "overrides.data", overrides.data); + } + // Resolve any from + if (overrides.from) { + overrides.from = await resolveAddress(overrides.from); + } + return overrides; +} +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) => { + if (type === "address") { + return resolveAddress(value, resolver); + } + return value; + }); + })); +} +class WrappedMethod extends _WrappedMethodBase() { + name = ""; // Investigate! + _contract; + _key; + constructor(contract, key) { + super(); + defineProperties(this, { + name: contract.interface.getFunctionName(key), + _contract: contract, _key: key + }); + const proxy = new Proxy(this, { + // Perform the default operation for this fragment type + apply: async (target, thisArg, args) => { + const fragment = target.getFragment(...args); + if (fragment.constant) { + return await target.staticCall(...args); + } + return await target.send(...args); + }, + }); + return proxy; + } + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + get fragment() { + return this._contract.interface.getFunction(this._key); + } + getFragment(...args) { + return this._contract.interface.getFunction(this._key, args); + } + async populateTransaction(...args) { + const fragment = this.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()); + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(this._contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await resolveProperties({ + to: this._contract.getAddress(), + data: this._contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + } + async staticCall(...args) { + const result = await this.staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + } + async send(...args) { + const runner = this._contract.runner; + if (!canSend(runner)) { + return logger.throwError("contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + } + const tx = await runner.sendTransaction(await this.populateTransaction(...args)); + const provider = getProvider(this._contract.runner); + return new ContractTransactionResponse(this._contract.interface, provider, tx); + } + async estimateGas(...args) { + const runner = getRunner(this._contract.runner, "estimateGas"); + if (!canEstimate(runner)) { + return logger.throwError("contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { + operation: "estimateGas" + }); + } + return await runner.estimateGas(await this.populateTransaction(...args)); + } + async staticCallResult(...args) { + const runner = getRunner(this._contract.runner, "call"); + if (!canCall(runner)) { + return logger.throwError("contract runner does not support calling", "UNSUPPORTED_OPERATION", { + operation: "call" + }); + } + const fragment = this.getFragment(...args); + const tx = await this.populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } + catch (error) { + if (isCallException(error)) { + throw this._contract.interface.makeError(fragment, error.data, tx); + } + throw error; + } + return this._contract.interface.decodeFunctionResult(fragment, result); + } +} +function _WrappedEventBase() { + return Function; +} +class WrappedEvent extends _WrappedEventBase() { + name = ""; // @TODO: investigate + _contract; + _key; + constructor(contract, key) { + super(); + defineProperties(this, { + name: contract.interface.getEventName(key), + _contract: contract, _key: key + }); + return new Proxy(this, { + // Perform the default operation for this fragment type + apply: async (target, thisArg, args) => { + return new PreparedTopicFilter(contract, target.getFragment(...args), args); + }, + }); + } + // Only works on non-ambiguous keys + get fragment() { + return this._contract.interface.getEvent(this._key); + } + getFragment(...args) { + return this._contract.interface.getEvent(this._key, args); + } +} +; +// 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("_ethersInternal_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 getSubTag(contract, event) { + let fragment; + let topics; + if (Array.isArray(event)) { + // Topics; e.g. `[ "0x1234...89ab" ]` + fragment = contract.interface.getEvent(event[0]); + topics = event; + } + else if (typeof (event) === "string") { + // Event name (name or signature); `"Transfer"` + fragment = contract.interface.getEvent(event); + topics = [contract.interface.getEventTopic(fragment)]; + } + else if (isDeferred(event)) { + // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` + fragment = event.fragment; + topics = await event.getTopicFilter(); + } + else if ("fragment" in event) { + // ContractEvent; e.g. `contract.filter.Transfer` + fragment = event.fragment; + topics = [contract.interface.getEventTopic(fragment)]; + } + else { + console.log(event); + throw new Error("TODO"); + } + // Normalize topics and sort TopicSets + topics = topics.map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + 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 getSubTag(contract, event)).tag) || null; +} +async function getSub(contract, event) { + // Make sure our runner can actually subscribe to events + const provider = getProvider(contract.runner); + if (!provider) { + return logger.throwError("contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { + operation: "on" + }); + } + const { fragment, tag, topics } = await getSubTag(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) => { + const payload = new ContractEventPayload(contract, null, event, fragment, log); + emit(contract, event, payload.args, payload); + }; + let started = false; + const start = () => { + if (started) { + return; + } + provider.on(filter, listener); + started = true; + }; + const stop = () => { + if (!started) { + return; + } + provider.off(filter, listener); + started = false; + }; + 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, payload) { + 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 = args.slice(); + if (payload) { + passArgs.push(new ContractEventPayload(contract, (once ? null : listener), event, payload.fragment, payload.log)); + } + try { + listener.call(contract, ...passArgs); + } + catch (error) { } + return !once; + }); + return (count > 0); +} +async function emit(contract, event, args, payload) { + try { + await lastEmit; + } + catch (error) { } + const resultPromise = _emit(contract, event, args, payload); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +class BaseContract { + target; + interface; + runner; + filters; + [internal]; + constructor(target, abi, runner = null, _deployTx) { + 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); + 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 logger.makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr) => { + if (addr == null) { + throw new Error("TODO"); + } + 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 (passProperties.indexOf(_prop) >= 0) { + return Reflect.get(target, _prop, receiver); + } + const prop = String(_prop); + const result = this.getEvent(prop); + if (result) { + return result; + } + throw new Error(`unknown contract event: ${prop}`); + } + }); + defineProperties(this, { filters }); + // Return a Proxy that will respond to functions + return new Proxy(this, { + get: (target, _prop, receiver) => { + if (_prop in target || passProperties.indexOf(_prop) >= 0) { + return Reflect.get(target, _prop, receiver); + } + const prop = String(_prop); + const result = target.getFunction(prop); + if (result) { + return result; + } + throw new Error(`unknown contract method: ${prop}`); + } + }); + } + async getAddress() { return await getInternal(this).addrPromise; } + async getDeployedCode() { + const provider = getProvider(this.runner); + if (!provider) { + return logger.throwError("runner does not support .provider", "UNSUPPORTED_OPERATION", { + operation: "getDeployedCode" + }); + } + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; + } + return code; + } + 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); + if (provider == null) { + return logger.throwError("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(); + }); + } + deploymentTransaction() { + return getInternal(this).deployTx; + } + getFunction(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return (new WrappedMethod(this, key)); + } + getEvent(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return (new WrappedEvent(this, key)); + } + async queryTransaction(hash) { + // Is this useful? + throw new Error("@TODO"); + } + async queryFilter(event, fromBlock = 0, toBlock = "latest") { + const { addr, addrPromise } = getInternal(this); + const address = (addr ? addr : (await addrPromise)); + const { fragment, topics } = await getSubTag(this, event); + const filter = { address, topics, fromBlock, toBlock }; + const provider = getProvider(this.runner); + if (!provider) { + return logger.throwError("contract runner does not have a provider", "UNSUPPORTED_OPERATION", { + operation: "queryFilter" + }); + } + return (await provider.getLogs(filter)).map((log) => { + return new EventLog(log, this.interface, fragment); + }); + } + async on(event, listener) { + const sub = await getSub(this, event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + async once(event, listener) { + const sub = await getSub(this, event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + async emit(event, ...args) { + return await emit(this, event, args, null); + } + 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; + } + 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; + } + 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; + } + 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); + } + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null) { + super(address, abi, runner); + } + } + return CustomContract; + } + ; + static from(target, abi, runner = null) { + const contract = new this(target, abi, runner); + return contract; + } +} +function _ContractBase() { + return BaseContract; +} +class Contract extends _ContractBase() { +} + +// A = Arguments to the constructor +// I = Interface of deployed contracts +class ContractFactory { + interface; + bytecode; + runner; + 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(logger.getBytes(bytecode)); + } + else { + if (typeof (bytecode) === "object") { + bytecode = bytecode.object; + } + if (bytecode.substring(0, 2) !== "0x") { + bytecode = "0x" + bytecode; + } + bytecode = hexlify(logger.getBytes(bytecode)); + } + defineProperties(this, { + bytecode, interface: iface, runner: (runner || null) + }); + } + async getDeployTransaction(...args) { + let overrides = {}; + const fragment = this.interface.deploy; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + } + 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({}, overrides, { data }); + } + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + if (!this.runner || typeof (this.runner.sendTransaction) !== "function") { + return logger.throwError("factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + } + const sentTx = await this.runner.sendTransaction(tx); + const address = getCreateAddress(sentTx); + return new BaseContract(address, this.interface, this.runner, sentTx); + } + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); + } + static fromSolidity(output, runner) { + if (output == null) { + logger.throwArgumentError("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); + } +} + +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words, sep) { + let initial = 97; + return words.reduce((accum, word) => { + if (word === sep) { + initial++; + } + else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } + else { + initial = 97; + accum.push(word); + } + return accum; + }, []); +} +function decode(data, subs) { + // Replace all the substitutions with their expanded form + for (let i = subsChrs.length - 1; i >= 0; i--) { + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + } + // Get all tle clumps; each suffix, first-increment and second-increment + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { + if (semi) { + for (let i = parseInt(semi); i >= 0; i--) { + clumps.push(";"); + } + } + else { + clumps.push(item.toLowerCase()); + } + return ""; + }); + /* c8 ignore start */ + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); + } + /* c8 ignore stop */ + return unfold(unfold(clumps, ";"), ":"); +} +function decodeOwl(data) { + assertArgument(data[0] === "0", "unsupported auwl data", "data", data); + return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); +} + +class Wordlist { + locale; + constructor(locale) { + defineProperties(this, { locale }); + } + // Subclasses may override this + split(mnemonic) { + return mnemonic.toLowerCase().split(/ +/g); + } + // Subclasses may override this + join(words) { + return words.join(" "); + } +} + +// Use the encode-latin.js script to create the necessary +class WordlistOwl extends Wordlist { + #data; + #checksum; + constructor(locale, data, checksum) { + super(locale); + this.#data = data; + this.#checksum = checksum; + this.#words = null; + } + get _data() { return this.#data; } + _decodeWords() { + return decodeOwl(this.#data); + } + #words; + #loadWords() { + if (this.#words == null) { + const words = this._decodeWords(); + // Verify the computed list matches the official list + const checksum = id(words.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== this.#checksum) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); + } + /* c8 ignore stop */ + this.#words = words; + } + return this.#words; + } + getWord(index) { + const words = this.#loadWords(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return this.#loadWords().indexOf(word); + } +} + +const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T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gramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; +const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; +class LangEn extends WordlistOwl { + constructor() { super("en", words, checksum); } +} +const langEn = new LangEn(); + +// Returns a byte with the MSB bits set +function getUpperMask(bits) { + return ((1 << bits) - 1) << (8 - bits) & 0xff; +} +// Returns a byte with the LSB bits set +function getLowerMask(bits) { + return ((1 << bits) - 1) & 0xff; +} +function mnemonicToEntropy(mnemonic, wordlist = langEn) { + logger.assertNormalize("NFKD"); + if (wordlist == null) { + wordlist = langEn; + } + const words = wordlist.split(mnemonic); + if ((words.length % 3) !== 0 || words.length < 12 || words.length > 24) { + logger.throwArgumentError("invalid mnemonic length", "mnemonic", "[ REDACTED ]"); + } + const entropy = new Uint8Array(Math.ceil(11 * words.length / 8)); + let offset = 0; + for (let i = 0; i < words.length; i++) { + let index = wordlist.getWordIndex(words[i].normalize("NFKD")); + if (index === -1) { + logger.throwArgumentError(`invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); + } + for (let bit = 0; bit < 11; bit++) { + if (index & (1 << (10 - bit))) { + entropy[offset >> 3] |= (1 << (7 - (offset % 8))); + } + offset++; + } + } + const entropyBits = 32 * words.length / 3; + const checksumBits = words.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum = logger.getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { + logger.throwArgumentError("invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); + } + return hexlify(entropy.slice(0, entropyBits / 8)); +} +function entropyToMnemonic(entropy, wordlist = langEn) { + if ((entropy.length % 4) || entropy.length < 16 || entropy.length > 32) { + logger.throwArgumentError("invalid entropy size", "entropy", "[ REDACTED ]"); + } + if (wordlist == null) { + wordlist = langEn; + } + const indices = [0]; + let remainingBits = 11; + for (let i = 0; i < entropy.length; i++) { + // Consume the whole byte (with still more to go) + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + // This byte will complete an 11-bit index + } + else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); + // Start the next word + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; + } + } + // Compute the checksum bits + const checksumBits = entropy.length / 4; + const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); + // Shift the checksum into the word indices + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= (checksum >> (8 - checksumBits)); + return wordlist.join(indices.map((index) => wordlist.getWord(index))); +} +const _guard$1 = {}; +class Mnemonic { + phrase; + password; + wordlist; + entropy; + constructor(guard, entropy, phrase, password, wordlist) { + if (password == null) { + password = ""; + } + if (wordlist == null) { + wordlist = langEn; + } + logger.assertPrivate(guard, _guard$1, "Mnemonic"); + defineProperties(this, { phrase, password, wordlist, entropy }); + } + computeSeed() { + const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD"); + return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); + } + static fromPhrase(phrase, password, wordlist) { + // Normalize the case and space; throws if invalid + const entropy = mnemonicToEntropy(phrase, wordlist); + phrase = entropyToMnemonic(logger.getBytes(entropy), wordlist); + return new Mnemonic(_guard$1, entropy, phrase, password, wordlist); + } + static fromEntropy(_entropy, password, wordlist) { + const entropy = logger.getBytes(_entropy, "entropy"); + const phrase = entropyToMnemonic(entropy, wordlist); + return new Mnemonic(_guard$1, hexlify(entropy), phrase, password, wordlist); + } + static entropyToPhrase(_entropy, wordlist) { + const entropy = logger.getBytes(_entropy, "entropy"); + return entropyToMnemonic(entropy, wordlist); + } + static phraseToEntropy(phrase, wordlist) { + return mnemonicToEntropy(phrase, wordlist); + } + static isValidMnemonic(phrase, wordlist) { + try { + mnemonicToEntropy(phrase, wordlist); + return true; + } + catch (error) { } + return false; + } +} + +class BaseWallet extends AbstractSigner { + address; + #signingKey; + constructor(privateKey, provider) { + super(provider); + this.#signingKey = privateKey; + const address = computeAddress(this.signingKey.publicKey); + defineProperties(this, { address }); + } + // Store these in getters to reduce visibility in console.log + get signingKey() { return this.#signingKey; } + 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 tx = Object.assign({}, _tx, await resolveProperties({ + to: (_tx.to ? resolveAddress(_tx.to, this.provider) : undefined), + from: (_tx.from ? resolveAddress(_tx.from, this.provider) : undefined) + })); + if (tx.from != null) { + if (getAddress(tx.from) !== this.address) { + logger.throwArgumentError("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.signingKey.sign(hashMessage(message)).serialized; + } + async signTypedData(domain, types, value) { + // Populate any ENS names + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => { + if (this.provider == null) { + return logger.throwError("cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name } + }); + } + const address = await this.provider.resolveName(name); + if (address == null) { + return logger.throwError("unconfigured ENS name", "UNCONFIGURED_NAME", { + value: name + }); + } + return address; + }); + return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized; + } +} + +const defaultPath$1 = "m/44'/60'/0'/0/0"; +// "Bitcoin seed" +const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); +const HardenedBit = 0x80000000; +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const Nibbles = "0123456789abcdef"; +function zpad$1(value, length) { + let result = ""; + while (value) { + result = Nibbles[value % 16] + result; + value = Math.trunc(value / 16); + } + while (result.length < length * 2) { + result = "0" + result; + } + return "0x" + result; +} +function encodeBase58Check(_value) { + const value = logger.getBytes(_value); + const check = dataSlice(sha256(sha256(value)), 0, 4); + const bytes = concat([value, check]); + return encodeBase58(bytes); +} +const _guard = {}; +function ser_I(index, chainCode, publicKey, privateKey) { + const data = new Uint8Array(37); + if (index & HardenedBit) { + if (privateKey == null) { + return logger.throwError("cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { + operation: "deriveChild" + }); + } + // Data = 0x00 || ser_256(k_par) + data.set(logger.getBytes(privateKey), 1); + } + else { + // Data = ser_p(point(k_par)) + data.set(logger.getBytes(publicKey)); + } + // Data += ser_32(i) + for (let i = 24; i >= 0; i -= 8) { + data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); + } + const I = logger.getBytes(computeHmac("sha512", chainCode, data)); + return { IL: I.slice(0, 32), IR: I.slice(32) }; +} +function derivePath(node, path) { + const components = path.split("/"); + if (components.length === 0 || (components[0] === "m" && node.depth !== 0)) { + throw new Error("invalid path - " + path); + } + if (components[0] === "m") { + components.shift(); + } + let result = node; + for (let i = 0; i < components.length; i++) { + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index = parseInt(component.substring(0, component.length - 1)); + if (index >= HardenedBit) { + throw new Error("invalid path index - " + component); + } + result = result.deriveChild(HardenedBit + index); + } + else if (component.match(/^[0-9]+$/)) { + const index = parseInt(component); + if (index >= HardenedBit) { + throw new Error("invalid path index - " + component); + } + result = result.deriveChild(index); + } + else { + throw new Error("invalid path component - " + component); + } + } + return result; +} +class HDNodeWallet extends BaseWallet { + publicKey; + fingerprint; + parentFingerprint; + mnemonic; + chainCode; + path; + index; + depth; + constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) { + super(signingKey, provider); + logger.assertPrivate(guard, _guard, "HDNodeWallet"); + defineProperties(this, { publicKey: signingKey.compressedPublicKey }); + const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4); + defineProperties(this, { + parentFingerprint, fingerprint, + chainCode, path, index, depth + }); + defineProperties(this, { mnemonic }); + } + connect(provider) { + return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); + } + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return encodeBase58Check(concat([ + "0x0488ADE4", zpad$1(this.depth, 1), this.parentFingerprint, + zpad$1(this.index, 4), this.chainCode, + concat(["0x00", this.privateKey]) + ])); + } + hasPath() { return (this.path != null); } + neuter() { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); + } + deriveChild(_index) { + const index = logger.getNumber(_index, "index"); + if (index > 0xffffffff) { + throw new Error("invalid index - " + String(index)); + } + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); + const ki = new SigningKey(toHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); + return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider); + } + derivePath(path) { + return derivePath(this, path); + } + static #fromSeed(_seed, mnemonic) { + const seed = logger.getBytes(_seed, "seed"); + if (seed.length < 16 || seed.length > 64) { + throw new Error("invalid seed"); + } + const I = logger.getBytes(computeHmac("sha512", MasterSecret, seed)); + const signingKey = new SigningKey(hexlify(I.slice(0, 32))); + return new HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I.slice(32)), "m", 0, 0, mnemonic, null); + } + static fromSeed(seed) { + return HDNodeWallet.#fromSeed(seed, null); + } + static fromPhrase(phrase, password = "", path = defaultPath$1, wordlist = langEn) { + if (!path) { + path = defaultPath$1; + } + const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromMnemonic(mnemonic, path = defaultPath$1) { + if (!path) { + path = defaultPath$1; + } + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromExtendedKey(extendedKey) { + const bytes = logger.getBytes(decodeBase58(extendedKey)); // @TODO: redact + if (bytes.length !== 82 || encodeBase58Check(bytes.slice(0, 78)) !== extendedKey) { + logger.throwArgumentError("invalid extended key", "extendedKey", "[ REDACTED ]"); + } + const depth = bytes[4]; + const parentFingerprint = hexlify(bytes.slice(5, 9)); + const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16); + const chainCode = hexlify(bytes.slice(13, 45)); + const key = bytes.slice(45, 78); + switch (hexlify(bytes.slice(0, 4))) { + // Public Key + case "0x0488b21e": + case "0x043587cf": { + const publicKey = hexlify(key); + return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); + } + // Private Key + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); + } + return logger.throwArgumentError("invalid extended key prefix", "extendedKey", "[ REDACTED ]"); + } + static createRandom(password = "", path = defaultPath$1, wordlist = langEn) { + if (!path) { + path = defaultPath$1; + } + const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } +} +class HDNodeVoidWallet extends VoidSigner { + publicKey; + fingerprint; + parentFingerprint; + chainCode; + path; + index; + depth; + constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) { + super(address, provider); + logger.assertPrivate(guard, _guard, "HDNodeVoidWallet"); + defineProperties(this, { publicKey }); + const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4); + defineProperties(this, { + publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth + }); + } + connect(provider) { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); + } + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return encodeBase58Check(concat([ + "0x0488B21E", + zpad$1(this.depth, 1), + this.parentFingerprint, + zpad$1(this.index, 4), + this.chainCode, + this.publicKey, + ])); + } + hasPath() { return (this.path != null); } + deriveChild(_index) { + const index = logger.getNumber(_index, "index"); + if (index > 0xffffffff) { + throw new Error("invalid index - " + String(index)); + } + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); + const Ki = SigningKey._addPoints(IL, this.publicKey, true); + const address = computeAddress(Ki); + return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider); + } + derivePath(path) { + return derivePath(this, path); + } +} +class HDNodeWalletManager { + #root; + constructor(phrase, password = "", path = "m/44'/60'/0'/0", locale = langEn) { + this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale); + } + getSigner(index = 0) { + return this.#root.deriveChild(index); + } +} +function getAccountPath(_index) { + const index = logger.getNumber(_index, "index"); + if (index < 0 || index >= HardenedBit) { + logger.throwArgumentError("invalid account index", "index", index); + } + return `m/44'/60'/${index}'/0/0`; +} + +/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */ +var __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AES_key, _AES_Kd, _AES_Ke; +// Number of rounds by keysize +const numberOfRounds = { 16: 10, 24: 12, 32: 14 }; +// Round constant words +const rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]; +// S-box and Inverse S-box (S is for Substitution) +const S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,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60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]; +// Transformations for encryption +const T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a]; +const T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616]; +const T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16]; +const T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c]; +// Transformations for decryption +const T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742]; +const T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857]; +const T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8]; +const T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0]; +// Transformations for decryption key expansion +const U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]; +const U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697]; +const U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46]; +const U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d]; +function convertToInt32(bytes) { + const result = []; + for (let i = 0; i < bytes.length; i += 4) { + result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); + } + return result; +} +class AES { + constructor(key) { + _AES_key.set(this, void 0); + _AES_Kd.set(this, void 0); + _AES_Ke.set(this, void 0); + if (!(this instanceof AES)) { + throw Error('AES must be instanitated with `new`'); + } + __classPrivateFieldSet$4(this, _AES_key, new Uint8Array(key), "f"); + const rounds = numberOfRounds[this.key.length]; + if (rounds == null) { + throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)'); + } + // encryption round keys + __classPrivateFieldSet$4(this, _AES_Ke, [], "f"); + // decryption round keys + __classPrivateFieldSet$4(this, _AES_Kd, [], "f"); + for (let i = 0; i <= rounds; i++) { + __classPrivateFieldGet$4(this, _AES_Ke, "f").push([0, 0, 0, 0]); + __classPrivateFieldGet$4(this, _AES_Kd, "f").push([0, 0, 0, 0]); + } + const roundKeyCount = (rounds + 1) * 4; + const KC = this.key.length / 4; + // convert the key into ints + const tk = convertToInt32(this.key); + // copy values into round key arrays + let index; + for (let i = 0; i < KC; i++) { + index = i >> 2; + __classPrivateFieldGet$4(this, _AES_Ke, "f")[index][i % 4] = tk[i]; + __classPrivateFieldGet$4(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i]; + } + // key expansion (fips-197 section 5.2) + let rconpointer = 0; + let t = KC, tt; + while (t < roundKeyCount) { + tt = tk[KC - 1]; + tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^ + (S[(tt >> 8) & 0xFF] << 16) ^ + (S[tt & 0xFF] << 8) ^ + S[(tt >> 24) & 0xFF] ^ + (rcon[rconpointer] << 24)); + rconpointer += 1; + // key expansion (for non-256 bit) + if (KC != 8) { + for (let i = 1; i < KC; i++) { + tk[i] ^= tk[i - 1]; + } + // key expansion for 256-bit keys is "slightly different" (fips-197) + } + else { + for (let i = 1; i < (KC / 2); i++) { + tk[i] ^= tk[i - 1]; + } + tt = tk[(KC / 2) - 1]; + tk[KC / 2] ^= (S[tt & 0xFF] ^ + (S[(tt >> 8) & 0xFF] << 8) ^ + (S[(tt >> 16) & 0xFF] << 16) ^ + (S[(tt >> 24) & 0xFF] << 24)); + for (let i = (KC / 2) + 1; i < KC; i++) { + tk[i] ^= tk[i - 1]; + } + } + // copy values into round key arrays + let i = 0, r, c; + while (i < KC && t < roundKeyCount) { + r = t >> 2; + c = t % 4; + __classPrivateFieldGet$4(this, _AES_Ke, "f")[r][c] = tk[i]; + __classPrivateFieldGet$4(this, _AES_Kd, "f")[rounds - r][c] = tk[i++]; + t++; + } + } + // inverse-cipher-ify the decryption round key (fips-197 section 5.3) + for (let r = 1; r < rounds; r++) { + for (let c = 0; c < 4; c++) { + tt = __classPrivateFieldGet$4(this, _AES_Kd, "f")[r][c]; + __classPrivateFieldGet$4(this, _AES_Kd, "f")[r][c] = (U1[(tt >> 24) & 0xFF] ^ + U2[(tt >> 16) & 0xFF] ^ + U3[(tt >> 8) & 0xFF] ^ + U4[tt & 0xFF]); + } + } + } + get key() { return __classPrivateFieldGet$4(this, _AES_key, "f").slice(); } + encrypt(plaintext) { + if (plaintext.length != 16) { + throw new TypeError('invalid plaintext size (must be 16 bytes)'); + } + const rounds = __classPrivateFieldGet$4(this, _AES_Ke, "f").length - 1; + const a = [0, 0, 0, 0]; + // convert plaintext to (ints ^ key) + let t = convertToInt32(plaintext); + for (let i = 0; i < 4; i++) { + t[i] ^= __classPrivateFieldGet$4(this, _AES_Ke, "f")[0][i]; + } + // apply round transforms + for (let r = 1; r < rounds; r++) { + for (let i = 0; i < 4; i++) { + a[i] = (T1[(t[i] >> 24) & 0xff] ^ + T2[(t[(i + 1) % 4] >> 16) & 0xff] ^ + T3[(t[(i + 2) % 4] >> 8) & 0xff] ^ + T4[t[(i + 3) % 4] & 0xff] ^ + __classPrivateFieldGet$4(this, _AES_Ke, "f")[r][i]); + } + t = a.slice(); + } + // the last round is special + const result = new Uint8Array(16); + let tt = 0; + for (let i = 0; i < 4; i++) { + tt = __classPrivateFieldGet$4(this, _AES_Ke, "f")[rounds][i]; + result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; + result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; + result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; + result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff; + } + return result; + } + decrypt(ciphertext) { + if (ciphertext.length != 16) { + throw new TypeError('invalid ciphertext size (must be 16 bytes)'); + } + const rounds = __classPrivateFieldGet$4(this, _AES_Kd, "f").length - 1; + const a = [0, 0, 0, 0]; + // convert plaintext to (ints ^ key) + let t = convertToInt32(ciphertext); + for (let i = 0; i < 4; i++) { + t[i] ^= __classPrivateFieldGet$4(this, _AES_Kd, "f")[0][i]; + } + // apply round transforms + for (let r = 1; r < rounds; r++) { + for (let i = 0; i < 4; i++) { + a[i] = (T5[(t[i] >> 24) & 0xff] ^ + T6[(t[(i + 3) % 4] >> 16) & 0xff] ^ + T7[(t[(i + 2) % 4] >> 8) & 0xff] ^ + T8[t[(i + 1) % 4] & 0xff] ^ + __classPrivateFieldGet$4(this, _AES_Kd, "f")[r][i]); + } + t = a.slice(); + } + // the last round is special + const result = new Uint8Array(16); + let tt = 0; + for (let i = 0; i < 4; i++) { + tt = __classPrivateFieldGet$4(this, _AES_Kd, "f")[rounds][i]; + result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; + result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; + result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; + result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff; + } + return result; + } +} +_AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap(); + +class ModeOfOperation { + constructor(name, key, cls) { + if (cls && !(this instanceof cls)) { + throw new Error(`${name} must be instantiated with "new"`); + } + Object.defineProperties(this, { + aes: { enumerable: true, value: new AES(key) }, + name: { enumerable: true, value: name } + }); + } +} + +// Cipher Block Chaining +var __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CBC_iv, _CBC_lastBlock; +class CBC extends ModeOfOperation { + constructor(key, iv) { + super("ECC", key, CBC); + _CBC_iv.set(this, void 0); + _CBC_lastBlock.set(this, void 0); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + __classPrivateFieldSet$3(this, _CBC_iv, new Uint8Array(iv), "f"); + } + else { + __classPrivateFieldSet$3(this, _CBC_iv, new Uint8Array(16), "f"); + } + __classPrivateFieldSet$3(this, _CBC_lastBlock, this.iv, "f"); + } + get iv() { return new Uint8Array(__classPrivateFieldGet$3(this, _CBC_iv, "f")); } + encrypt(plaintext) { + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + } + const ciphertext = new Uint8Array(plaintext.length); + for (let i = 0; i < plaintext.length; i += 16) { + for (let j = 0; j < 16; j++) { + __classPrivateFieldGet$3(this, _CBC_lastBlock, "f")[j] ^= plaintext[i + j]; + } + __classPrivateFieldSet$3(this, _CBC_lastBlock, this.aes.encrypt(__classPrivateFieldGet$3(this, _CBC_lastBlock, "f")), "f"); + ciphertext.set(__classPrivateFieldGet$3(this, _CBC_lastBlock, "f"), i); + } + return ciphertext; + } + decrypt(ciphertext) { + if (ciphertext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); + } + const plaintext = new Uint8Array(ciphertext.length); + for (let i = 0; i < ciphertext.length; i += 16) { + const block = this.aes.decrypt(ciphertext.subarray(i, i + 16)); + for (let j = 0; j < 16; j++) { + plaintext[i + j] = block[j] ^ __classPrivateFieldGet$3(this, _CBC_lastBlock, "f")[j]; + __classPrivateFieldGet$3(this, _CBC_lastBlock, "f")[j] = ciphertext[i + j]; + } + } + return plaintext; + } +} +_CBC_iv = new WeakMap(), _CBC_lastBlock = new WeakMap(); + +// Cipher Feedback +var __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CFB_instances, _CFB_iv, _CFB_shiftRegister, _CFB_shift; +class CFB extends ModeOfOperation { + constructor(key, iv, segmentSize = 8) { + super("CFB", key, CFB); + _CFB_instances.add(this); + _CFB_iv.set(this, void 0); + _CFB_shiftRegister.set(this, void 0); + // This library currently only handles byte-aligned segmentSize + if (!Number.isInteger(segmentSize) || (segmentSize % 8)) { + throw new TypeError("invalid segmentSize"); + } + Object.defineProperties(this, { + segmentSize: { enumerable: true, value: segmentSize } + }); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + __classPrivateFieldSet$2(this, _CFB_iv, new Uint8Array(iv), "f"); + } + else { + __classPrivateFieldSet$2(this, _CFB_iv, new Uint8Array(16), "f"); + } + __classPrivateFieldSet$2(this, _CFB_shiftRegister, this.iv, "f"); + } + get iv() { return new Uint8Array(__classPrivateFieldGet$2(this, _CFB_iv, "f")); } + encrypt(plaintext) { + if (8 * plaintext.length % this.segmentSize) { + throw new TypeError("invalid plaintext size (must be multiple of segmentSize bytes)"); + } + const segmentSize = this.segmentSize / 8; + const ciphertext = new Uint8Array(plaintext); + for (let i = 0; i < ciphertext.length; i += segmentSize) { + const xorSegment = this.aes.encrypt(__classPrivateFieldGet$2(this, _CFB_shiftRegister, "f")); + for (let j = 0; j < segmentSize; j++) { + ciphertext[i + j] ^= xorSegment[j]; + } + __classPrivateFieldGet$2(this, _CFB_instances, "m", _CFB_shift).call(this, ciphertext.subarray(i)); + } + return ciphertext; + } + decrypt(ciphertext) { + if (8 * ciphertext.length % this.segmentSize) { + throw new TypeError("invalid ciphertext size (must be multiple of segmentSize bytes)"); + } + const segmentSize = this.segmentSize / 8; + const plaintext = new Uint8Array(ciphertext); + for (let i = 0; i < plaintext.length; i += segmentSize) { + const xorSegment = this.aes.encrypt(__classPrivateFieldGet$2(this, _CFB_shiftRegister, "f")); + for (let j = 0; j < segmentSize; j++) { + plaintext[i + j] ^= xorSegment[j]; + } + __classPrivateFieldGet$2(this, _CFB_instances, "m", _CFB_shift).call(this, ciphertext.subarray(i)); + } + return plaintext; + } +} +_CFB_iv = new WeakMap(), _CFB_shiftRegister = new WeakMap(), _CFB_instances = new WeakSet(), _CFB_shift = function _CFB_shift(data) { + const segmentSize = this.segmentSize / 8; + // Shift the register + __classPrivateFieldGet$2(this, _CFB_shiftRegister, "f").set(__classPrivateFieldGet$2(this, _CFB_shiftRegister, "f").subarray(segmentSize)); + __classPrivateFieldGet$2(this, _CFB_shiftRegister, "f").set(data.subarray(0, segmentSize), 16 - segmentSize); +}; + +// Counter Mode +var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; +class CTR extends ModeOfOperation { + constructor(key, initialValue) { + super("CTR", key, CTR); + // Remaining bytes for the one-time pad + _CTR_remaining.set(this, void 0); + _CTR_remainingIndex.set(this, void 0); + // The current counter + _CTR_counter.set(this, void 0); + __classPrivateFieldSet$1(this, _CTR_counter, new Uint8Array(16), "f"); + __classPrivateFieldGet$1(this, _CTR_counter, "f").fill(0); + __classPrivateFieldSet$1(this, _CTR_remaining, __classPrivateFieldGet$1(this, _CTR_counter, "f"), "f"); // This will be discarded immediately + __classPrivateFieldSet$1(this, _CTR_remainingIndex, 16, "f"); + if (initialValue == null) { + initialValue = 1; + } + if (typeof (initialValue) === "number") { + this.setCounterValue(initialValue); + } + else { + this.setCounterBytes(initialValue); + } + } + get counter() { return new Uint8Array(__classPrivateFieldGet$1(this, _CTR_counter, "f")); } + setCounterValue(value) { + if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { + throw new TypeError("invalid counter initial integer value"); + } + for (let index = 15; index >= 0; --index) { + __classPrivateFieldGet$1(this, _CTR_counter, "f")[index] = value % 256; + value = Math.floor(value / 256); + } + } + setCounterBytes(value) { + if (value.length !== 16) { + throw new TypeError("invalid counter initial Uint8Array value length"); + } + __classPrivateFieldGet$1(this, _CTR_counter, "f").set(value); + } + increment() { + for (let i = 15; i >= 0; i--) { + if (__classPrivateFieldGet$1(this, _CTR_counter, "f")[i] === 255) { + __classPrivateFieldGet$1(this, _CTR_counter, "f")[i] = 0; + } + else { + __classPrivateFieldGet$1(this, _CTR_counter, "f")[i]++; + break; + } + } + } + encrypt(plaintext) { + var _a, _b; + const crypttext = new Uint8Array(plaintext); + for (let i = 0; i < crypttext.length; i++) { + if (__classPrivateFieldGet$1(this, _CTR_remainingIndex, "f") === 16) { + __classPrivateFieldSet$1(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet$1(this, _CTR_counter, "f")), "f"); + __classPrivateFieldSet$1(this, _CTR_remainingIndex, 0, "f"); + this.increment(); + } + crypttext[i] ^= __classPrivateFieldGet$1(this, _CTR_remaining, "f")[__classPrivateFieldSet$1(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet$1(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a]; + } + return crypttext; + } + decrypt(ciphertext) { + return this.encrypt(ciphertext); + } +} +_CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap(); + +// Electronic Code Book +class ECB extends ModeOfOperation { + constructor(key) { + super("ECB", key, ECB); + } + encrypt(plaintext) { + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + } + const crypttext = new Uint8Array(plaintext.length); + for (let i = 0; i < plaintext.length; i += 16) { + crypttext.set(this.aes.encrypt(plaintext.subarray(i, i + 16)), i); + } + return crypttext; + } + decrypt(crypttext) { + if (crypttext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); + } + const plaintext = new Uint8Array(crypttext.length); + for (let i = 0; i < crypttext.length; i += 16) { + plaintext.set(this.aes.decrypt(crypttext.subarray(i, i + 16)), i); + } + return plaintext; + } +} + +// Output Feedback +var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _OFB_iv, _OFB_lastPrecipher, _OFB_lastPrecipherIndex; +class OFB extends ModeOfOperation { + constructor(key, iv) { + super("OFB", key, OFB); + _OFB_iv.set(this, void 0); + _OFB_lastPrecipher.set(this, void 0); + _OFB_lastPrecipherIndex.set(this, void 0); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + __classPrivateFieldSet(this, _OFB_iv, new Uint8Array(iv), "f"); + } + else { + __classPrivateFieldSet(this, _OFB_iv, new Uint8Array(16), "f"); + } + __classPrivateFieldSet(this, _OFB_lastPrecipher, this.iv, "f"); + __classPrivateFieldSet(this, _OFB_lastPrecipherIndex, 16, "f"); + } + get iv() { return new Uint8Array(__classPrivateFieldGet(this, _OFB_iv, "f")); } + encrypt(plaintext) { + var _a, _b; + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); + } + const ciphertext = new Uint8Array(plaintext); + for (let i = 0; i < ciphertext.length; i++) { + if (__classPrivateFieldGet(this, _OFB_lastPrecipherIndex, "f") === 16) { + __classPrivateFieldSet(this, _OFB_lastPrecipher, this.aes.encrypt(__classPrivateFieldGet(this, _OFB_lastPrecipher, "f")), "f"); + __classPrivateFieldSet(this, _OFB_lastPrecipherIndex, 0, "f"); + } + ciphertext[i] ^= __classPrivateFieldGet(this, _OFB_lastPrecipher, "f")[__classPrivateFieldSet(this, _OFB_lastPrecipherIndex, (_b = __classPrivateFieldGet(this, _OFB_lastPrecipherIndex, "f"), _a = _b++, _b), "f"), _a]; + } + return ciphertext; + } + decrypt(ciphertext) { + if (ciphertext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); + } + return this.encrypt(ciphertext); + } +} +_OFB_iv = new WeakMap(), _OFB_lastPrecipher = new WeakMap(), _OFB_lastPrecipherIndex = new WeakMap(); + +function pkcs7Pad(data) { + const padder = 16 - (data.length % 16); + const result = new Uint8Array(data.length + padder); + result.set(data); + for (let i = data.length; i < result.length; i++) { + result[i] = padder; + } + return result; +} +function pkcs7Strip(data) { + if (data.length < 16) { + throw new TypeError('PKCS#7 invalid length'); + } + const padder = data[data.length - 1]; + if (padder > 16) { + throw new TypeError('PKCS#7 padding byte out of range'); + } + const length = data.length - padder; + for (let i = 0; i < padder; i++) { + if (data[length + i] !== padder) { + throw new TypeError('PKCS#7 invalid padding byte'); + } + } + return new Uint8Array(data.subarray(0, length)); +} + +function looseArrayify(hexString) { + if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') { + hexString = '0x' + hexString; + } + return logger.getBytesCopy(hexString); +} +function zpad(value, length) { + value = String(value); + while (value.length < length) { + value = '0' + value; + } + return value; +} +function getPassword(password) { + if (typeof (password) === 'string') { + return toUtf8Bytes(password, "NFKC"); + } + return logger.getBytesCopy(password); +} +function spelunk(object, _path) { + const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); + if (match == null) { + return logger.throwArgumentError("invalid path", "path", _path); + } + const path = match[1]; + const type = match[3]; + const reqd = (match[4] === "!"); + let cur = object; + for (const comp of path.toLowerCase().split('.')) { + // Search for a child object with a case-insensitive matching key + if (Array.isArray(cur)) { + if (!comp.match(/^[0-9]+$/)) { + break; + } + cur = cur[parseInt(comp)]; + } + else if (typeof (cur) === "object") { + let found = null; + for (const key in cur) { + if (key.toLowerCase() === comp) { + found = cur[key]; + break; + } + } + cur = found; + } + else { + cur = null; + } + if (cur == null) { + break; + } + } + if (reqd && cur == null) { + logger.throwArgumentError("missing required value", "path", path); + } + if (type && cur != null) { + if (type === "int") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9]+$/)) { + return parseInt(cur); + } + else if (Number.isSafeInteger(cur)) { + return cur; + } + } + if (type === "number") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9.]*$/)) { + return parseFloat(cur); + } + } + if (type === "data") { + if (typeof (cur) === "string") { + return looseArrayify(cur); + } + } + if (type === "array" && Array.isArray(cur)) { + return cur; + } + if (type === typeof (cur)) { + return cur; + } + logger.throwArgumentError(`wrong type found for ${type} `, "path", path); + } + return cur; +} +/* +export function follow(object: any, path: string): null | string { + let currentChild = object; + + for (const comp of path.toLowerCase().split('/')) { + + // Search for a child object with a case-insensitive matching key + let matchingChild = null; + for (const key in currentChild) { + if (key.toLowerCase() === comp) { + matchingChild = currentChild[key]; + break; + } + } + + if (matchingChild === null) { return null; } + + currentChild = matchingChild; + } + + return currentChild; +} + +// "path/to/something:type!" +export function followRequired(data: any, path: string): string { + const value = follow(data, path); + if (value != null) { return value; } + return logger.throwArgumentError("invalid value", `data:${ path }`, + JSON.stringify(data)); +} +*/ +// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4) +function uuidV4(randomBytes) { + const bytes = logger.getBytes(randomBytes, "randomBytes"); + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + bytes[6] = (bytes[6] & 0x0f) | 0x40; + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const value = hexlify(bytes); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34), + ].join("-"); +} + +function isCrowdsaleJson(json) { + try { + const data = JSON.parse(json); + if (data.encseed) { + return true; + } + } + catch (error) { } + return false; +} +// See: https://github.com/ethereum/pyethsaletool +function decryptCrowdsaleJson(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + // Ethereum Address + const address = getAddress(spelunk(data, "ethaddr:string!")); + // Encrypted Seed + const encseed = looseArrayify(spelunk(data, "encseed:string!")); + if (!encseed || (encseed.length % 16) !== 0) { + logger.throwArgumentError("invalid encseed", "json", json); + } + const key = logger.getBytes(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + // Decrypt the seed + const aesCbc = new CBC(key, iv); + const seed = pkcs7Strip(logger.getBytes(aesCbc.decrypt(encryptedSeed))); + // This wallet format is weird... Convert the binary encoded hex to a string. + let seedHex = ""; + for (let i = 0; i < seed.length; i++) { + seedHex += String.fromCharCode(seed[i]); + } + return { address, privateKey: id(seedHex) }; +} + +const defaultPath = "m/44'/60'/0'/0/0"; +function isKeystoreJson(json) { + try { + const data = JSON.parse(json); + const version = ((data.version != null) ? parseInt(data.version) : 0); + if (version === 3) { + return true; + } + } + catch (error) { } + return false; +} +function decrypt(data, key, ciphertext) { + const cipher = spelunk(data, "crypto.cipher:string"); + if (cipher === "aes-128-ctr") { + const iv = spelunk(data, "crypto.cipherparams.iv:data!"); + const aesCtr = new CTR(key, iv); + return hexlify(aesCtr.decrypt(ciphertext)); + } + return logger.throwError("unsupported cipher", "UNSUPPORTED_OPERATION", { + operation: "decrypt" + }); +} +function getAccount(data, _key) { + const key = logger.getBytes(_key); + const ciphertext = spelunk(data, "crypto.ciphertext:data!"); + const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2); + if (computedMAC !== spelunk(data, "crypto.mac:string!").toLowerCase()) { + return logger.throwArgumentError("incorrect password", "password", "[ REDACTED ]"); + } + const privateKey = decrypt(data, key.slice(0, 16), ciphertext); + const address = computeAddress(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (check.substring(0, 2) !== "0x") { + check = "0x" + check; + } + if (getAddress(check) !== address) { + logger.throwArgumentError("keystore address/privateKey mismatch", "address", data.address); + } + } + const account = { address, privateKey }; + // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase + const version = spelunk(data, "x-ethers.version:string"); + if (version === "0.1") { + const mnemonicKey = key.slice(32, 64); + const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!"); + const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!"); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + account.mnemonic = { + path: (spelunk(data, "x-ethers.path:string") || defaultPath), + locale: (spelunk(data, "x-ethers.locale:string") || "en"), + entropy: hexlify(logger.getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))) + }; + } + return account; +} +function getKdfParams(data) { + const kdf = spelunk(data, "crypto.kdf:string"); + if (kdf && typeof (kdf) === "string") { + const throwError = function (name, value) { + return logger.throwArgumentError("invalid key-derivation function parameters", name, value); + }; + if (kdf.toLowerCase() === "scrypt") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const N = spelunk(data, "crypto.kdfparams.n:int!"); + const r = spelunk(data, "crypto.kdfparams.r:int!"); + const p = spelunk(data, "crypto.kdfparams.p:int!"); + // Check for all required parameters + if (!N || !r || !p) { + return throwError("kdf", kdf); + } + // Make sure N is a power of 2 + if ((N & (N - 1)) !== 0) { + return throwError("N", N); + } + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + if (dkLen !== 32) { + return throwError("dklen", dkLen); + } + return { name: "scrypt", salt, N, r, p, dkLen: 64 }; + } + else if (kdf.toLowerCase() === "pbkdf2") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const prf = spelunk(data, "crypto.kdfparams.prf:string!"); + const algorithm = prf.split("-").pop(); + if (algorithm !== "sha256" && algorithm !== "sha512") { + return throwError("prf", prf); + } + const count = spelunk(data, "crypto.kdfparams.c:int!"); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + if (dkLen !== 32) { + throwError("dklen", dkLen); + } + return { name: "pbkdf2", salt, count, dkLen, algorithm }; + } + } + return logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf); +} +function decryptKeystoreJsonSync(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getKdfParams(data); + if (params.name === "pbkdf2") { + const { salt, count, dkLen, algorithm } = params; + const key = pbkdf2(password, salt, count, dkLen, algorithm); + return getAccount(data, key); + } + else if (params.name === "scrypt") { + const { salt, N, r, p, dkLen } = params; + const key = scryptSync(password, salt, N, r, p, dkLen); + return getAccount(data, key); + } + throw new Error("unreachable"); +} +function stall$1(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +async function decryptKeystoreJson(json, _password, progress) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getKdfParams(data); + if (params.name === "pbkdf2") { + if (progress) { + progress(0); + await stall$1(0); + } + const { salt, count, dkLen, algorithm } = params; + const key = pbkdf2(password, salt, count, dkLen, algorithm); + if (progress) { + progress(1); + await stall$1(0); + } + return getAccount(data, key); + } + else if (params.name === "scrypt") { + const { salt, N, r, p, dkLen } = params; + const key = await scrypt(password, salt, N, r, p, dkLen, progress); + return getAccount(data, key); + } + throw new Error("unreachable"); +} +async function encryptKeystoreJson(account, password, options, progressCallback) { + // Check the address matches the private key + //if (getAddress(account.address) !== computeAddress(account.privateKey)) { + // throw new Error("address/privateKey mismatch"); + //} + // Check the mnemonic (if any) matches the private key + /* + if (hasMnemonic(account)) { + const mnemonic = account.mnemonic; + const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath); + + if (node.privateKey != account.privateKey) { + throw new Error("mnemonic mismatch"); + } + } + */ + // The options are optional, so adjust the call as needed + if (typeof (options) === "function" && !progressCallback) { + progressCallback = options; + options = {}; + } + if (!options) { + options = {}; + } + const privateKey = logger.getBytes(account.privateKey, "privateKey"); + const passwordBytes = getPassword(password); + /* + let mnemonic: null | Mnemonic = null; + let entropy: Uint8Array = null + let path: string = null; + let locale: string = null; + if (hasMnemonic(account)) { + const srcMnemonic = account.mnemonic; + entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en")); + path = srcMnemonic.path || defaultPath; + locale = srcMnemonic.locale || "en"; + mnemonic = Mnemonic.from( + } + */ + // Check/generate the salt + const salt = (options.salt != null) ? logger.getBytes(options.salt, "options.slat") : randomBytes(32); + // Override initialization vector + const iv = (options.iv != null) ? logger.getBytes(options.iv, "options.iv") : randomBytes(16); + if (iv.length !== 16) { + logger.throwArgumentError("invalid options.iv", "options.iv", options.iv); + } + // Override the uuid + const uuidRandom = (options.uuid != null) ? logger.getBytes(options.uuid, "options.uuid") : randomBytes(16); + if (uuidRandom.length !== 16) { + logger.throwArgumentError("invalid options.uuid", "options.uuid", options.iv); + } + if (uuidRandom.length !== 16) { + throw new Error("invalid uuid"); + } + // Override the scrypt password-based key derivation function parameters + let N = (1 << 17), r = 8, p = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N = options.scrypt.N; + } + if (options.scrypt.r) { + r = options.scrypt.r; + } + if (options.scrypt.p) { + p = options.scrypt.p; + } + } + // We take 64 bytes: + // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) + // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet) + const _key = await scrypt(passwordBytes, salt, N, r, p, 64, progressCallback); + const key = logger.getBytes(_key); + // This will be used to encrypt the wallet (as per Web3 secret storage) + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + // Encrypt the private key + const aesCtr = new CTR(derivedKey, iv); + const ciphertext = logger.getBytes(aesCtr.encrypt(privateKey)); + // Compute the message authentication code, used to check the password + const mac = keccak256(concat([macPrefix, ciphertext])); + // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + const data = { + address: account.address.substring(2).toLowerCase(), + id: uuidV4(uuidRandom), + version: 3, + Crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: hexlify(iv).substring(2), + }, + ciphertext: hexlify(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: hexlify(salt).substring(2), + n: N, + dklen: 32, + p: p, + r: r + }, + mac: mac.substring(2) + } + }; + // If we have a mnemonic, encrypt it into the JSON wallet + if (account.mnemonic) { + const client = (options.client != null) ? options.client : `ethers/${version}`; + const path = account.mnemonic.path || defaultPath; + const locale = account.mnemonic.locale || "en"; + const mnemonicKey = key.slice(32, 64); + const entropy = logger.getBytes(account.mnemonic.entropy, "account.mnemonic.entropy"); + const mnemonicIv = randomBytes(16); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + const mnemonicCiphertext = logger.getBytes(mnemonicAesCtr.encrypt(entropy)); + const now = new Date(); + const timestamp = (now.getUTCFullYear() + "-" + + zpad(now.getUTCMonth() + 1, 2) + "-" + + zpad(now.getUTCDate(), 2) + "T" + + zpad(now.getUTCHours(), 2) + "-" + + zpad(now.getUTCMinutes(), 2) + "-" + + zpad(now.getUTCSeconds(), 2) + ".0Z"); + const gethFilename = ("UTC--" + timestamp + "--" + data.address); + data["x-ethers"] = { + client, gethFilename, path, locale, + mnemonicCounter: hexlify(mnemonicIv).substring(2), + mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), + version: "0.1" + }; + } + return JSON.stringify(data); +} + +function tryWallet(value) { + try { + if (!value || !value.signingKey) { + return null; + } + const key = trySigningKey(value.signingKey); + if (key == null || computeAddress(key.publicKey) !== value.address) { + return null; + } + if (value.mnemonic) { + const wallet = HDNodeWallet.fromMnemonic(value.mnemonic); + if (wallet.privateKey !== key.privateKey) { + return null; + } + } + return value; + } + catch (e) { + console.log(e); + } + return null; +} +// Try using value as mnemonic to derive the defaultPath HDodeWallet +function tryMnemonic(value) { + try { + if (value == null || typeof (value.phrase) !== "string" || + typeof (value.password) !== "string" || + value.wordlist == null) { + return null; + } + return HDNodeWallet.fromPhrase(value.phrase, value.password, null, value.wordlist); + } + catch (error) { + console.log(error); + } + return null; +} +function trySigningKey(value) { + try { + if (!value || !isHexString(value.privateKey, 32)) { + return null; + } + const key = value.privateKey; + if (SigningKey.computePublicKey(key) !== value.publicKey) { + return null; + } + return new SigningKey(key); + } + catch (e) { + console.log(e); + } + return null; +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +class Wallet extends BaseWallet { + #mnemonic; + constructor(key, provider) { + let signingKey = null; + let mnemonic = null; + // A normal private key + if (typeof (key) === "string") { + signingKey = new SigningKey(key); + } + // Try Wallet + if (signingKey == null) { + const wallet = tryWallet(key); + if (wallet) { + signingKey = wallet.signingKey; + mnemonic = wallet.mnemonic || null; + } + } + // Try Mnemonic, with the defaultPath wallet + if (signingKey == null) { + const wallet = tryMnemonic(key); + if (wallet) { + signingKey = wallet.signingKey; + mnemonic = wallet.mnemonic || null; + } + } + // A signing key + if (signingKey == null) { + signingKey = trySigningKey(key); + } + if (signingKey == null) { + logger.throwArgumentError("invalid key", "key", "[ REDACTED ]"); + } + super(signingKey, provider); + this.#mnemonic = mnemonic; + } + // Store this in a getter to reduce visibility in console.log + get mnemonic() { return this.#mnemonic; } + connect(provider) { + return new Wallet(this, provider); + } + async encrypt(password, options, progressCallback) { + throw new Error("TODO"); + } + encryptSync(password, options) { + throw new Error("TODO"); + } + static async fromEncryptedJson(json, password, progress) { + let account = null; + if (isKeystoreJson(json)) { + account = await decryptKeystoreJson(json, password, progress); + } + else if (isCrowdsaleJson(json)) { + if (progress) { + progress(0); + await stall(0); + } + account = decryptCrowdsaleJson(json, password); + if (progress) { + progress(1); + await stall(0); + } + } + else { + return logger.throwArgumentError("invalid JSON wallet", "json", "[ REDACTED ]"); + } + const wallet = new Wallet(account.privateKey); + if (wallet.address !== account.address) { + logger.throwArgumentError("address/privateKey mismatch", "json", "[ REDACTED ]"); + } + // @TODO: mnemonic + return wallet; + } + static fromEncryptedJsonSync(json, password) { + let account = null; + if (isKeystoreJson(json)) { + account = decryptKeystoreJsonSync(json, password); + } + else if (isCrowdsaleJson(json)) { + account = decryptCrowdsaleJson(json, password); + } + else { + return logger.throwArgumentError("invalid JSON wallet", "json", "[ REDACTED ]"); + } + const wallet = new Wallet(account.privateKey); + if (wallet.address !== account.address) { + logger.throwArgumentError("address/privateKey mismatch", "json", "[ REDACTED ]"); + } + // @TODO: mnemonic + return wallet; + } + static createRandom(provider, password, wordlist) { + return new Wallet(Mnemonic.fromEntropy(randomBytes(16), password, wordlist), provider); + } + static fromMnemonic(mnemonic, provider) { + return new Wallet(mnemonic, provider); + } + static fromPhrase(phrase, provider, password = "", wordlist) { + return new Wallet(Mnemonic.fromPhrase(phrase, password, wordlist), provider); + } +} + +// wordlists/wordlists-browser.js +const wordlists = Object.freeze({ + en: langEn +}); + +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +function decodeBits(width, data) { + const maxValue = (1 << width) - 1; + const result = []; + let accum = 0, bits = 0, flood = 0; + for (let i = 0; i < data.length; i++) { + // Accumulate 6 bits of data + accum = ((accum << 6) | Base64.indexOf(data[i])); + bits += 6; + // While we have enough for a word... + while (bits >= width) { + // ...read the word + const value = (accum >> (bits - width)); + accum &= (1 << (bits - width)) - 1; + bits -= width; + // A value of 0 indicates we exceeded maxValue, it + // floods over into the next value + if (value === 0) { + flood += maxValue; + } + else { + result.push(value + flood); + flood = 0; + } + } + } + return result; +} + +function decodeOwlA(data, accents) { + let words = decodeOwl(data).join(","); + // Inject the accents + accents.split(/,/g).forEach((accent) => { + const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); + assertArgument(match !== null, "internal error parsing accents", "accents", accents); + let posOffset = 0; + const positions = decodeBits(parseInt(match[3]), match[4]); + const charCode = parseInt(match[2]); + const regex = new RegExp(`([${match[1]}])`, "g"); + words = words.replace(regex, (all, letter) => { + const rem = --positions[posOffset]; + if (rem === 0) { + letter = String.fromCharCode(letter.charCodeAt(0), charCode); + posOffset++; + } + return letter; + }); + }); + return words.split(","); +} + +class WordlistOwlA extends WordlistOwl { + #accent; + constructor(locale, data, accent, checksum) { + super(locale, data, checksum); + this.#accent = accent; + } + get _accent() { return this.#accent; } + _decodeWords() { + return decodeOwlA(this._data, this._accent); + } +} + +///////////////////////////// + +var ethers = /*#__PURE__*/Object.freeze({ + __proto__: null, + version: version, + formatBytes32String: formatBytes32String, + parseBytes32String: parseBytes32String, + AbiCoder: AbiCoder, + defaultAbiCoder: defaultAbiCoder, + ConstructorFragment: ConstructorFragment, + ErrorFragment: ErrorFragment, + EventFragment: EventFragment, + Fragment: Fragment, + FunctionFragment: FunctionFragment, + ParamType: ParamType, + checkResultErrors: checkResultErrors, + Indexed: Indexed, + Interface: Interface, + LogDescription: LogDescription, + Result: Result, + TransactionDescription: TransactionDescription, + Typed: Typed, + getAddress: getAddress, + getIcapAddress: getIcapAddress, + getCreateAddress: getCreateAddress, + getCreate2Address: getCreate2Address, + ZeroAddress: ZeroAddress, + NegativeOne: NegativeOne, + Zero: Zero, + One: One, + Two: Two, + WeiPerEther: WeiPerEther, + MaxUint256: MaxUint256, + MinInt256: MinInt256, + MaxInt256: MaxInt256, + ZeroHash: ZeroHash, + EtherSymbol: EtherSymbol, + MessagePrefix: MessagePrefix, + BaseContract: BaseContract, + Contract: Contract, + ContractFactory: ContractFactory, + ContractEventPayload: ContractEventPayload, + ContractTransactionReceipt: ContractTransactionReceipt, + ContractTransactionResponse: ContractTransactionResponse, + EventLog: EventLog, + computeHmac: computeHmac, + randomBytes: randomBytes, + keccak256: keccak256, + ripemd160: ripemd160, + sha256: sha256, + sha512: sha512, + pbkdf2: pbkdf2, + scrypt: scrypt, + scryptSync: scryptSync, + lock: lock, + Signature: Signature, + SigningKey: SigningKey, + id: id, + hashMessage: hashMessage, + solidityPacked: solidityPacked, + solidityPackedKeccak256: solidityPackedKeccak256, + solidityPackedSha256: solidityPackedSha256, + TypedDataEncoder: TypedDataEncoder, + accessListify: accessListify, + computeAddress: computeAddress, + recoverAddress: recoverAddress, + Transaction: Transaction, + decodeBase58: decodeBase58, + encodeBase58: encodeBase58, + isCallException: isCallException, + isError: isError, + FetchRequest: FetchRequest, + FetchResponse: FetchResponse, + FixedFormat: FixedFormat, + FixedNumber: FixedNumber, + formatFixed: formatFixed, + parseFixed: parseFixed, + assertArgument: assertArgument, + Logger: Logger, + logger: logger, + fromTwos: fromTwos, + toTwos: toTwos, + mask: mask, + toArray: toArray, + toBigInt: toBigInt, + toHex: toHex, + toNumber: toNumber, + formatEther: formatEther, + parseEther: parseEther, + formatUnits: formatUnits, + parseUnits: parseUnits, + _toEscapedUtf8String: _toEscapedUtf8String, + toUtf8Bytes: toUtf8Bytes, + toUtf8CodePoints: toUtf8CodePoints, + toUtf8String: toUtf8String, + Utf8ErrorFuncs: Utf8ErrorFuncs, + decodeRlp: decodeRlp, + encodeRlp: encodeRlp, + defaultPath: defaultPath$1, + getAccountPath: getAccountPath, + HDNodeWallet: HDNodeWallet, + HDNodeVoidWallet: HDNodeVoidWallet, + HDNodeWalletManager: HDNodeWalletManager, + isCrowdsaleJson: isCrowdsaleJson, + decryptCrowdsaleJson: decryptCrowdsaleJson, + isKeystoreJson: isKeystoreJson, + decryptKeystoreJsonSync: decryptKeystoreJsonSync, + decryptKeystoreJson: decryptKeystoreJson, + encryptKeystoreJson: encryptKeystoreJson, + Mnemonic: Mnemonic, + Wallet: Wallet, + Wordlist: Wordlist, + langEn: langEn, + LangEn: LangEn, + wordlists: wordlists, + WordlistOwl: WordlistOwl, + WordlistOwlA: WordlistOwlA, + FallbackProvider: FallbackProvider, + JsonRpcApiProvider: JsonRpcApiProvider, + JsonRpcProvider: JsonRpcProvider, + JsonRpcSigner: JsonRpcSigner, + AlchemyProvider: AlchemyProvider, + AnkrProvider: AnkrProvider, + CloudflareProvider: CloudflareProvider, + EtherscanProvider: EtherscanProvider, + InfuraProvider: InfuraProvider, + IpcSocketProvider: IpcSocketProvider, + SocketProvider: SocketProvider, + WebSocketProvider: WebSocketProvider, + Network: Network +}); + +export { AbiCoder, AlchemyProvider, AnkrProvider, BaseContract, CloudflareProvider, ConstructorFragment, Contract, ContractEventPayload, ContractFactory, ContractTransactionReceipt, ContractTransactionResponse, ErrorFragment, EtherSymbol, EtherscanProvider, EventFragment, EventLog, FallbackProvider, FetchRequest, FetchResponse, FixedFormat, FixedNumber, Fragment, FunctionFragment, HDNodeVoidWallet, HDNodeWallet, HDNodeWalletManager, Indexed, InfuraProvider, Interface, IpcSocketProvider, JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner, LangEn, LogDescription, Logger, MaxInt256, MaxUint256, MessagePrefix, MinInt256, Mnemonic, NegativeOne, Network, One, ParamType, Result, Signature, SigningKey, SocketProvider, Transaction, TransactionDescription, Two, Typed, TypedDataEncoder, Utf8ErrorFuncs, Wallet, WebSocketProvider, WeiPerEther, Wordlist, WordlistOwl, WordlistOwlA, Zero, ZeroAddress, ZeroHash, _toEscapedUtf8String, accessListify, assertArgument, checkResultErrors, computeAddress, computeHmac, decodeBase58, decodeRlp, decryptCrowdsaleJson, decryptKeystoreJson, decryptKeystoreJsonSync, defaultAbiCoder, defaultPath$1 as defaultPath, encodeBase58, encodeRlp, encryptKeystoreJson, ethers, formatBytes32String, formatEther, formatFixed, formatUnits, fromTwos, getAccountPath, getAddress, getCreate2Address, getCreateAddress, getIcapAddress, hashMessage, id, isCallException, isCrowdsaleJson, isError, isKeystoreJson, keccak256, langEn, lock, logger, mask, parseBytes32String, parseEther, parseFixed, parseUnits, pbkdf2, randomBytes, recoverAddress, ripemd160, scrypt, scryptSync, sha256, sha512, solidityPacked, solidityPackedKeccak256, solidityPackedSha256, toArray, toBigInt, toHex, toNumber, toTwos, toUtf8Bytes, toUtf8CodePoints, toUtf8String, version, wordlists }; +//# sourceMappingURL=ethers.js.map diff --git a/dist/ethers.min.js b/dist/ethers.min.js new file mode 100644 index 000000000..b76ded205 --- /dev/null +++ b/dist/ethers.min.js @@ -0,0 +1 @@ +const version="6.0.0-beta-exports.0";const LogLevels=["debug","info","warning","error","off"];const _normalizeForms=["NFD","NFC","NFKD","NFKC"].reduce((accum,form)=>{try{if("test".normalize(form)!=="test"){throw new Error("bad")}if(form==="NFD"){const check=String.fromCharCode(233).normalize("NFD");const expected=String.fromCharCode(101,769);if(check!==expected){throw new Error("broken")}}accum.push(form)}catch(error){}return accum},[]);function defineReadOnly$1(object,name,value){Object.defineProperty(object,name,{enumerable:true,writable:false,value:value})}const maxValue=9007199254740991;const ErrorConstructors={};ErrorConstructors.INVALID_ARGUMENT=TypeError;ErrorConstructors.NUMERIC_FAULT=RangeError;ErrorConstructors.BUFFER_OVERRUN=RangeError;class Logger{version;#logLevel;constructor(version){defineReadOnly$1(this,"version",version||"_");this.#logLevel=1}get logLevel(){return LogLevels[this.#logLevel]}set logLevel(value){const logLevel=LogLevels.indexOf(value);if(logLevel==null){this.throwArgumentError("invalid logLevel","logLevel",value)}this.#logLevel=logLevel}makeError(message,code,info){{const details=[];if(info){for(const key in info){const value=info[key];try{details.push(key+"="+JSON.stringify(value))}catch(error){details.push(key+"=[could not serialize object]")}}}details.push(`code=${code}`);details.push(`version=${this.version}`);if(details.length){message+=" ("+details.join(", ")+")"}}const create=ErrorConstructors[code]||Error;const error=new create(message);defineReadOnly$1(error,"code",code);if(info){for(const key in info){defineReadOnly$1(error,key,info[key])}}return error}throwError(message,code,info){throw this.makeError(message,code,info)}throwArgumentError(message,name,value){return this.throwError(message,"INVALID_ARGUMENT",{argument:name,value:value})}assertNormalize(form){if(_normalizeForms.indexOf(form)===-1){this.throwError("platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:form}})}}assertPrivate(givenGuard,guard,className=""){if(givenGuard!==guard){let method=className,operation="new";if(className){method+=".";operation+=" "+className}this.throwError(`private constructor; use ${method}from* methods`,"UNSUPPORTED_OPERATION",{operation:operation})}}assertArgumentCount(count,expectedCount,message=""){if(message){message=": "+message}if(countexpectedCount){this.throwError("too many arguemnts"+message,"UNEXPECTED_ARGUMENT",{count:count,expectedCount:expectedCount})}}#getBytes(value,name,copy){if(value instanceof Uint8Array){if(copy){return new Uint8Array(value)}return value}if(typeof value==="string"&&value.match(/^0x([0-9a-f][0-9a-f])*$/i)){const result=new Uint8Array((value.length-2)/2);let offset=2;for(let i=0;imaxValue){this.throwArgumentError("overflow",name||"value",value)}return Number(value);case"number":if(!Number.isInteger(value)){this.throwArgumentError("underflow",name||"value",value)}else if(value<-maxValue||value>maxValue){this.throwArgumentError("overflow",name||"value",value)}return value;case"string":try{return this.getNumber(BigInt(value),name)}catch(e){this.throwArgumentError(`invalid numeric string: ${e.message}`,name||"value",value)}}return this.throwArgumentError("invalid numeric value",name||"value",value)}getBigInt(value,name){switch(typeof value){case"bigint":return value;case"number":if(!Number.isInteger(value)){this.throwArgumentError("underflow",name||"value",value)}else if(value<-maxValue||value>maxValue){this.throwArgumentError("overflow",name||"value",value)}return BigInt(value);case"string":try{return BigInt(value)}catch(e){this.throwArgumentError(`invalid BigNumberish string: ${e.message}`,name||"value",value)}}return this.throwArgumentError("invalid BigNumberish value",name||"value",value)}#log(_logLevel,args){const logLevel=LogLevels.indexOf(_logLevel);if(logLevel===-1){this.throwArgumentError("invalid log level name","logLevel",_logLevel)}if(this.#logLevel>logLevel){return}console.log.apply(console,args)}debug(...args){this.#log("debug",args)}info(...args){this.#log("info",args)}warn(...args){this.#log("warning",args)}}const logger=new Logger(version);function assertArgument(check,message,name,value){if(!check){logger.throwArgumentError(message,name,value)}}function isHexString(value,length){if(typeof value!=="string"||!value.match(/^0x[0-9A-Fa-f]*$/)){return false}if(typeof length==="number"&&value.length!==2+2*length){return false}if(length===true&&value.length%2!==0){return false}return true}function isBytesLike(value){return isHexString(value,true)||value instanceof Uint8Array}const HexCharacters="0123456789abcdef";function hexlify(data){const bytes=logger.getBytes(data);let result="0x";for(let i=0;i>4]+HexCharacters[v&15]}return result}function concat(datas){return"0x"+datas.map(d=>hexlify(d).substring(2)).join("")}function dataLength(data){if(isHexString(data,true)){return(data.length-2)/2}return logger.getBytes(data).length}function dataSlice(data,start,end){const bytes=logger.getBytes(data);if(end!=null&&end>bytes.length){logger.throwError("cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:bytes,length:bytes.length,offset:end})}return hexlify(bytes.slice(start==null?0:start,end==null?bytes.length:end))}function stripZerosLeft(data){let bytes=hexlify(data).substring(2);while(bytes.substring(0,2)=="00"){bytes=bytes.substring(2)}return"0x"+bytes}function zeroPad(data,length,left){const bytes=logger.getBytes(data);if(length>width-BN_1$5){const mask=(BN_1$5<>4];result+=Nibbles$1[v&15]}return BigInt(result)}return logger.getBigInt(value)}function toNumber(value){return logger.getNumber(toBigInt(value))}function toHex(_value,_width){const value=logger.getBigInt(_value,"value");if(value<0){throw new Error("cannot convert negative value to hex")}let result=value.toString(16);if(_width==null){if(result.length%2){result="0"+result}}else{const width=logger.getNumber(_width,"width");if(width*2Promise.resolve(value[k])));return results.reduce((accum,v,index)=>{accum[keys[index]]=v;return accum},{})}function defineReadOnly(object,name,value){Object.defineProperty(object,name,{enumerable:true,value:value,writable:false})}function checkType(value,type){const types=type.split("|").map(t=>t.trim());for(let i=0;i{if(key==null){return}if(this.#indices.has(key)){this.#indices.get(key).push(index)}else{this.#indices.set(key,[index])}})}Object.freeze(this);return new Proxy(this,{get:(target,prop,receiver)=>{if(typeof prop==="string"){if(prop.match(/^[0-9]+$/)){const index=logger.getNumber(prop,"%index");if(index<0||index>=this.length){throw new RangeError("out of result range")}const item=target[index];if(item instanceof Error){this.#throwError(`index ${index}`,item)}return item}if(prop in target||passProperties$1.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}if(!(prop in target)){return target.getValue(prop)}}return Reflect.get(target,prop,receiver)}})}slice(start,end){if(start==null){start=0}if(end==null){end=this.length}const result=[];for(let i=start;iWordSize){logger.throwError("value out-of-bounds","BUFFER_OVERRUN",{buffer:bytes,length:WordSize,offset:bytes.length})}if(bytes.length!==WordSize){bytes=logger.getBytesCopy(concat([Padding.slice(bytes.length%WordSize),bytes]))}return bytes}class Coder{name;type;localName;dynamic;constructor(name,type,localName,dynamic){defineProperties(this,{name:name,type:type,localName:localName,dynamic:dynamic},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(message,value){return logger.throwArgumentError(message,this.localName,value)}}class Writer{#data;#dataLength;constructor(){this.#data=[];this.#dataLength=0}get data(){return concat(this.#data)}get length(){return this.#dataLength}#writeData(data){this.#data.push(data);this.#dataLength+=data.length;return data.length}appendWriter(writer){return this.#writeData(logger.getBytesCopy(writer.data))}writeBytes(value){let bytes=logger.getBytesCopy(value);const paddingOffset=bytes.length%WordSize;if(paddingOffset){bytes=logger.getBytesCopy(concat([bytes,Padding.slice(paddingOffset)]))}return this.#writeData(bytes)}writeValue(value){return this.#writeData(getValue$1(value))}writeUpdatableValue(){const offset=this.#data.length;this.#data.push(Padding);this.#dataLength+=WordSize;return value=>{this.#data[offset]=getValue$1(value)}}}class Reader{allowLoose;#data;#offset;constructor(data,allowLoose){defineProperties(this,{allowLoose:!!allowLoose});this.#data=logger.getBytesCopy(data);this.#offset=0}get data(){return hexlify(this.#data)}get dataLength(){return this.#data.length}get consumed(){return this.#offset}get bytes(){return new Uint8Array(this.#data)}#peekBytes(offset,length,loose){let alignedLength=Math.ceil(length/WordSize)*WordSize;if(this.#offset+alignedLength>this.#data.length){if(this.allowLoose&&loose&&this.#offset+length<=this.#data.length){alignedLength=length}else{logger.throwError("data out-of-bounds","BUFFER_OVERRUN",{buffer:logger.getBytesCopy(this.#data),length:this.#data.length,offset:this.#offset+alignedLength})}}return this.#data.slice(this.#offset,this.#offset+alignedLength)}subReader(offset){return new Reader(this.#data.slice(this.#offset+offset),this.allowLoose)}readBytes(length,loose){let bytes=this.#peekBytes(0,length,!!loose);this.#offset+=bytes.length;return bytes.slice(0,length)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bool(b){if(typeof b!=="boolean")throw new Error(`Expected boolean, not ${b}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function hash(hash){if(typeof hash!=="function"||typeof hash.create!=="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(hash.outputLen);number(hash.blockLen)}function exists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function output(out,instance){bytes(out);const min=instance.outputLen;if(out.length>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;iBigInt(h>>>0)<<_32n|BigInt(l>>>0);const shrSH=(h,l,s)=>h>>>s;const shrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;const rotr32H=(h,l)=>l;const rotr32L=(h,l)=>h;const rotlSH=(h,l,s)=>h<>>32-s;const rotlSL=(h,l,s)=>l<>>32-s;const rotlBH=(h,l,s)=>l<>>64-s;const rotlBL=(h,l,s)=>h<>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;const u64={fromBig:fromBig,split:split,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH,rotlSL:rotlSL,rotlBH:rotlBH,rotlBL:rotlBL,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L};const crypto$2={node:undefined,web:typeof self==="object"&&"crypto"in self?self.crypto:undefined};const u8=arr=>new Uint8Array(arr.buffer,arr.byteOffset,arr.byteLength);const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);const rotr=(word,shift)=>word<<32-shift|word>>>shift;const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");const hexes$1=Array.from({length:256},(v,i)=>i.toString(16).padStart(2,"0"));function bytesToHex$1(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Uint8Array expected");let hex="";for(let i=0;i{};async function asyncLoop(iters,tick,cb){let ts=Date.now();for(let i=0;i=0&&diffa instanceof Uint8Array))throw new Error("Uint8Array list expected");if(arrays.length===1)return arrays[0];const length=arrays.reduce((a,arr)=>a+arr.length,0);const result=new Uint8Array(length);for(let i=0,pad=0;iObject.prototype.toString.call(obj)==="[object Object]"&&obj.constructor===Object;function checkOpts(defaults,opts){if(opts!==undefined&&(typeof opts!=="object"||!isPlainObject(opts)))throw new TypeError("Options should be object or undefined");const merged=Object.assign(defaults,opts);return merged}function wrapConstructor(hashConstructor){const hashC=message=>hashConstructor().update(toBytes(message)).digest();const tmp=hashConstructor();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashConstructor();return hashC}function wrapConstructorWithOpts(hashCons){const hashC=(msg,opts)=>hashCons(opts).update(toBytes(msg)).digest();const tmp=hashCons({});hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=opts=>hashCons(opts);return hashC}function randomBytes$2(bytesLength=32){if(crypto$2.web){return crypto$2.web.getRandomValues(new Uint8Array(bytesLength))}else if(crypto$2.node){return new Uint8Array(crypto$2.node.randomBytes(bytesLength).buffer)}else{throw new Error("The environment doesn't have randomBytes function")}}const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];const _0n$1=BigInt(0);const _1n$1=BigInt(1);const _2n$1=BigInt(2);const _7n=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n$1,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n$1;for(let j=0;j<7;j++){R=(R<<_1n$1^(R>>_7n)*_0x71n)%_256n;if(R&_2n$1)t^=_1n$1<<(_1n$1<s>32?u64.rotlBH(h,l,s):u64.rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?u64.rotlBL(h,l,s):u64.rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;assert.number(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds);this.posOut=0;this.pos=0}update(data){assert.exists(this);const{blockLen,state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){assert.number(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){assert.output(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor(()=>new Keccak(blockLen,suffix,outputLen));const sha3_224=gen(6,144,224/8);const sha3_256=gen(6,136,256/8);const sha3_384=gen(6,104,384/8);const sha3_512=gen(6,72,512/8);const keccak_224=gen(1,144,224/8);const keccak_256=gen(1,136,256/8);const keccak_384=gen(1,104,384/8);const keccak_512=gen(1,72,512/8);const genShake=(suffix,blockLen,outputLen)=>wrapConstructorWithOpts((opts={})=>new Keccak(blockLen,suffix,opts.dkLen===undefined?outputLen:opts.dkLen,true));const shake128=genShake(31,168,128/8);const shake256=genShake(31,136,256/8);const Alphabet="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";let Lookup=null;function getAlpha(letter){if(Lookup==null){Lookup={};for(let i=0;i>6!==2){break}i++}return i}if(reason==="OVERRUN"){return bytes.length-offset-1}return 0}function replaceFunc(reason,offset,bytes,output,badCodepoint){if(reason==="OVERLONG"){output.push(badCodepoint!=null?badCodepoint:-1);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes,output,badCodepoint)}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(_bytes,onError){if(onError==null){onError=Utf8ErrorFuncs.error}const bytes=logger.getBytes(_bytes,"bytes");const result=[];let i=0;while(i>7===0){result.push(c);continue}let extraLength=null;let overlongMask=null;if((c&224)===192){extraLength=1;overlongMask=127}else if((c&240)===224){extraLength=2;overlongMask=2047}else if((c&248)===240){extraLength=3;overlongMask=65535}else{if((c&192)===128){i+=onError("UNEXPECTED_CONTINUE",i-1,bytes,result)}else{i+=onError("BAD_PREFIX",i-1,bytes,result)}continue}if(i-1+extraLength>=bytes.length){i+=onError("OVERRUN",i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j1114111){i+=onError("OUT_OF_RANGE",i-1-extraLength,bytes,result,res);continue}if(res>=55296&&res<=57343){i+=onError("UTF16_SURROGATE",i-1-extraLength,bytes,result,res);continue}if(res<=overlongMask){i+=onError("OVERLONG",i-1-extraLength,bytes,result,res);continue}result.push(res)}return result}function toUtf8Bytes(str,form){if(form!=null){logger.assertNormalize(form);str=str.normalize(form)}let result=[];for(let i=0;i>6|192);result.push(c&63|128)}else if((c&64512)==55296){i++;const c2=str.charCodeAt(i);if(i>=str.length||(c2&64512)!==56320){throw new Error("invalid utf-8 string")}const pair=65536+((c&1023)<<10)+(c2&1023);result.push(pair>>18|240);result.push(pair>>12&63|128);result.push(pair>>6&63|128);result.push(pair&63|128)}else{result.push(c>>12|224);result.push(c>>6&63|128);result.push(c&63|128)}}return new Uint8Array(result)}function escapeChar(value){const hex="0000"+value.toString(16);return"\\u"+hex.substring(hex.length-4)}function _toEscapedUtf8String(bytes,onError){return'"'+getUtf8CodePoints(bytes,onError).map(codePoint=>{if(codePoint<256){switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 13:return"\\r";case 34:return'\\"';case 92:return"\\\\"}if(codePoint>=32&&codePoint<127){return String.fromCharCode(codePoint)}}if(codePoint<=65535){return escapeChar(codePoint)}codePoint-=65536;return escapeChar((codePoint>>10&1023)+55296)+escapeChar((codePoint&1023)+56320)}).join("")+'"'}function _toUtf8String(codePoints){return codePoints.map(codePoint=>{if(codePoint<=65535){return String.fromCharCode(codePoint)}codePoint-=65536;return String.fromCharCode((codePoint>>10&1023)+55296,(codePoint&1023)+56320)}).join("")}function toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}function toUtf8CodePoints(str,form){return getUtf8CodePoints(toUtf8Bytes(str,form))}async function getUrl(req,_signal){const protocol=req.url.split(":")[0].toLowerCase();if(protocol!=="http"&&protocol!=="https"){logger.throwError(`unsupported protocol ${protocol}`,"UNSUPPORTED_OPERATION",{info:{protocol:protocol},operation:"request"})}if(req.credentials&&!req.allowInsecureAuthentication){logger.throwError("insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"})}let signal=undefined;if(_signal){const controller=new AbortController;signal=controller.signal;_signal.addListener(()=>{controller.abort()})}const init={method:req.method,headers:new Headers(Array.from(req)),body:req.body||undefined,signal:signal};const resp=await fetch(req.url,init);const headers={};resp.headers.forEach((value,key)=>{headers[key.toLowerCase()]=value});const respBody=await resp.arrayBuffer();const body=respBody==null?null:new Uint8Array(respBody);return{statusCode:resp.status,statusMessage:resp.statusText,headers:headers,body:body}}const MAX_ATTEMPTS=12;const SLOT_INTERVAL=250;let getUrlFunc=getUrl;const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i");const reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$5=false;async function gatewayData(url,signal){try{const match=url.match(reData);if(!match){throw new Error("invalid data")}return new FetchResponse(200,"OK",{"content-type":match[1]||"text/plain"},match[1]?decodeBase64(match[3]):unpercent(match[3]))}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid data: URI)",{},null,new FetchRequest(url))}}function getIpfsGatewayFunc(base){async function gatewayIpfs(url,signal){try{const match=url.match(reIpfs);if(!match){throw new Error("invalid link")}return new FetchRequest(`${base}${match[2]}`)}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid IPFS URI)",{},null,new FetchRequest(url))}}return gatewayIpfs}const Gateways={data:gatewayData,ipfs:getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")};const fetchSignals=new WeakMap;class FetchCancelSignal{#listeners;#cancelled;constructor(request){this.#listeners=[];this.#cancelled=false;fetchSignals.set(request,()=>{if(this.#cancelled){return}this.#cancelled=true;for(const listener of this.#listeners){setTimeout(()=>{listener()},0)}this.#listeners=[]})}addListener(listener){if(this.#cancelled){logger.throwError("singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"})}this.#listeners.push(listener)}get cancelled(){return this.cancelled}checkSignal(){if(!this.cancelled){return}logger.throwError("cancelled","CANCELLED",{})}}function checkSignal(signal){if(signal==null){throw new Error("missing signal; should not happen")}signal.checkSignal();return signal}class FetchRequest{#allowInsecure;#gzip;#headers;#method;#timeout;#url;#body;#bodyType;#creds;#preflight;#process;#retry;#signal;get url(){return this.#url}set url(url){this.#url=String(url)}get body(){if(this.#body==null){return null}return new Uint8Array(this.#body)}set body(body){if(body==null){this.#body=undefined;this.#bodyType=undefined}else if(typeof body==="string"){this.#body=toUtf8Bytes(body);this.#bodyType="text/plain"}else if(body instanceof Uint8Array){this.#body=body;this.#bodyType="application/octet-stream"}else if(typeof body==="object"){this.#body=toUtf8Bytes(JSON.stringify(body));this.#bodyType="application/json"}else{throw new Error("invalid body")}}hasBody(){return this.#body!=null}get method(){if(this.#method){return this.#method}if(this.hasBody()){return"POST"}return"GET"}set method(method){if(method==null){method=""}this.#method=String(method).toUpperCase()}get headers(){const headers=Object.assign({},this.#headers);if(this.#creds){headers["authorization"]=`Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`}if(this.allowGzip){headers["accept-encoding"]="gzip"}if(headers["content-type"]==null&&this.#bodyType){headers["content-type"]=this.#bodyType}if(this.body){headers["content-length"]=String(this.body.length)}return Object.freeze(headers)}getHeader(key){return this.headers[key.toLowerCase()]}setHeader(key,value){this.#headers[String(key).toLowerCase()]=String(value)}clearHeaders(){this.#headers={}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index=0,"timeout must be non-zero","timeout",timeout);this.#timeout=timeout}get preflightFunc(){return this.#preflight||null}set preflightFunc(preflight){this.#preflight=preflight}get processFunc(){return this.#process||null}set processFunc(process){this.#process=process}get retryFunc(){return this.#retry||null}set retryFunc(retry){this.#retry=retry}constructor(url){this.#url=String(url);this.#allowInsecure=false;this.#gzip=false;this.#headers={};this.#method="";this.#timeout=300}async#send(attempt,expires,delay,_request,_response){if(attempt>=MAX_ATTEMPTS){return _response.makeServerError("exceeded maximum retry limit")}if(getTime$2()>expires){return logger.throwError("timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:_request})}if(delay>0){await wait(delay)}let req=this.clone();const scheme=(req.url.split(":")[0]||"").toLowerCase();if(scheme in Gateways){const result=await Gateways[scheme](req.url,checkSignal(_request.#signal));if(result instanceof FetchResponse){let response=result;if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}}}return response}req=result}if(this.preflightFunc){req=await this.preflightFunc(req)}const resp=await getUrlFunc(req,checkSignal(_request.#signal));let response=new FetchResponse(resp.statusCode,resp.statusMessage,resp.headers,resp.body,_request);if(response.statusCode===301||response.statusCode===302){try{const location=response.headers.location||"";return req.redirect(location).#send(attempt+1,expires,0,_request,response)}catch(error){}return response}else if(response.statusCode===429){if(this.retryFunc==null||await this.retryFunc(req,response,attempt)){const retryAfter=response.headers["retry-after"];let delay=SLOT_INTERVAL*Math.trunc(Math.random()*Math.pow(2,attempt));if(typeof retryAfter==="string"&&retryAfter.match(/^[1-9][0-9]*$/)){delay=parseInt(retryAfter)}return req.clone().#send(attempt+1,expires,delay,_request,response)}}if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}let delay=SLOT_INTERVAL*Math.trunc(Math.random()*Math.pow(2,attempt));if(error.stall>=0){delay=error.stall}return req.clone().#send(attempt+1,expires,delay,_request,response)}}return response}send(){if(this.#signal!=null){return logger.throwError("request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"})}this.#signal=new FetchCancelSignal(this);return this.#send(0,getTime$2()+this.timeout,0,this,new FetchResponse(0,"",{},null,this))}cancel(){if(this.#signal==null){return logger.throwError("request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"})}const signal=fetchSignals.get(this);if(!signal){throw new Error("missing signal; should not happen")}signal()}redirect(location){const current=this.url.split(":")[0].toLowerCase();const target=location.split(":")[0].toLowerCase();if(this.method!=="GET"||current==="https"&&target==="http"||!location.match(/^https?:/)){return logger.throwError(`unsupported redirect`,"UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`})}const req=new FetchRequest(location);req.method="GET";req.allowGzip=this.allowGzip;req.timeout=this.timeout;req.#headers=Object.assign({},this.#headers);if(this.#body){req.#body=new Uint8Array(this.#body)}req.#bodyType=this.#bodyType;return req}clone(){const clone=new FetchRequest(this.url);clone.#method=this.#method;if(this.#body){clone.#body=this.#body}clone.#bodyType=this.#bodyType;clone.#headers=Object.assign({},this.#headers);clone.#creds=this.#creds;if(this.allowGzip){clone.allowGzip=true}clone.timeout=this.timeout;if(this.allowInsecureAuthentication){clone.allowInsecureAuthentication=true}clone.#preflight=this.#preflight;clone.#process=this.#process;clone.#retry=this.#retry;return clone}static lockConfig(){locked$5=true}static getGateway(scheme){return Gateways[scheme.toLowerCase()]||null}static registerGateway(scheme,func){scheme=scheme.toLowerCase();if(scheme==="http"||scheme==="https"){throw new Error(`cannot intercept ${scheme}; use registerGetUrl`)}if(locked$5){throw new Error("gateways locked")}Gateways[scheme]=func}static registerGetUrl(getUrl){if(locked$5){throw new Error("gateways locked")}getUrlFunc=getUrl}}class FetchResponse{#statusCode;#statusMessage;#headers;#body;#request;#error;toString(){return``}get statusCode(){return this.#statusCode}get statusMessage(){return this.#statusMessage}get headers(){return this.#headers}get body(){return this.#body==null?null:new Uint8Array(this.#body)}get bodyText(){try{return this.#body==null?"":toUtf8String(this.#body)}catch(error){return logger.throwError("response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(error){return logger.throwError("response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index{accum[k.toLowerCase()]=String(headers[k]);return accum},{})));this.#body=body==null?null:new Uint8Array(body);this.#request=request||null;this.#error={message:""}}makeServerError(message,error){let statusMessage;if(!message){message=`${this.statusCode} ${this.statusMessage}`;statusMessage=`CLIENT ESCALATED SERVER ERROR (${message})`}else{statusMessage=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`}const response=new FetchResponse(599,statusMessage,this.headers,this.body,this.#request||undefined);response.#error={message:message,error:error};return response}throwThrottleError(message,stall){if(stall==null){stall=-1}else if(typeof stall!=="number"||!Number.isInteger(stall)||stall<0){return logger.throwArgumentError("invalid stall timeout","stall",stall)}const error=new Error(message||"throttling requests");defineProperties(error,{stall:stall,throttle:true});throw error}getHeader(key){return this.headers[key.toLowerCase()]}hasBody(){return this.#body!=null}get request(){return this.#request}ok(){return this.#error.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok()){return}let{message,error}=this.#error;if(message===""){message=`server response ${this.statusCode} ${this.statusMessage}`}logger.throwError(message,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:error})}}function getTime$2(){return(new Date).getTime()}function unpercent(value){return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi,(all,code)=>{return String.fromCharCode(parseInt(code,16))}))}function wait(delay){return new Promise(resolve=>setTimeout(resolve,delay))}const _constructorGuard={};const NegativeOne$1=BigInt(-1);function throwFault(message,fault,operation,value){const params={fault:fault,operation:operation};if(value!==undefined){params.value=value}return logger.throwError(message,"NUMERIC_FAULT",params)}let zeros$1="0";while(zeros$1.length<256){zeros$1+=zeros$1}function getMultiplier(decimals){if(typeof decimals!=="number"||decimals<0||decimals>256||decimals%1){logger.throwArgumentError("invalid decimal length","decimals",decimals)}return BigInt("1"+zeros$1.substring(0,decimals))}function formatFixed(_value,_decimals){if(_decimals==null){_decimals=18}let value=logger.getBigInt(_value,"value");const decimals=logger.getNumber(_decimals,"decimals");const multiplier=getMultiplier(decimals);const multiplierStr=String(multiplier);const negative=value<0;if(negative){value*=NegativeOne$1}let fraction=String(value%multiplier);while(fraction.length1&&fraction.substring(fraction.length-1)==="0"){fraction=fraction.substring(0,fraction.length-1)}let result=String(value/multiplier);if(multiplierStr.length!==1){result+="."+fraction}if(negative){result="-"+result}return result}function parseFixed(value,_decimals){if(_decimals==null){_decimals=18}const decimals=logger.getNumber(_decimals,"decimals");const multiplier=getMultiplier(decimals);if(typeof value!=="string"||!value.match(/^-?[0-9.]+$/)){logger.throwArgumentError("invalid decimal value","value",value)}const negative=value.substring(0,1)==="-";if(negative){value=value.substring(1)}if(value==="."){logger.throwArgumentError("missing value","value",value)}const comps=value.split(".");if(comps.length>2){logger.throwArgumentError("too many decimal points","value",value)}let whole=comps[0]||"0",fraction=comps[1]||"0";while(fraction[fraction.length-1]==="0"){fraction=fraction.substring(0,fraction.length-1)}if(fraction.length>String(multiplier).length-1){throwFault("fractional component exceeds decimals","underflow","parseFixed")}if(fraction===""){fraction="0"}while(fraction.length{if(value[key]==null){return defaultValue}if(typeof value[key]!==type){logger.throwArgumentError("invalid fixed format ("+key+" not "+type+")","format."+key,value[key])}return value[key]};signed=check("signed","boolean",signed);width=check("width","number",width);decimals=check("decimals","number",decimals)}if(width%8){logger.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",width)}if(decimals>80){logger.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",decimals)}return new FixedFormat(_constructorGuard,signed,width,decimals)}}class FixedNumber{format;_isFixedNumber;#value;constructor(constructorGuard,hex,value,format){if(constructorGuard!==_constructorGuard){logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from","UNSUPPORTED_OPERATION",{operation:"new FixedFormat"})}this.format=FixedFormat.from(format);this.#value=value;this._isFixedNumber=true;Object.freeze(this)}#checkFormat(other){if(this.format.name!==other.format.name){logger.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",other)}}addUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a+b,this.format.decimals,this.format)}subUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a-b,this.format.decimals,this.format)}mulUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a*b/this.format._multiplier,this.format.decimals,this.format)}divUnsafe(other){this.#checkFormat(other);const a=parseFixed(this.#value,this.format.decimals);const b=parseFixed(other.#value,other.format.decimals);return FixedNumber.fromValue(a*this.format._multiplier/b,this.format.decimals,this.format)}floor(){const comps=this.toString().split(".");if(comps.length===1){comps.push("0")}let result=FixedNumber.from(comps[0],this.format);const hasFraction=!comps[1].match(/^(0*)$/);if(this.isNegative()&&hasFraction){result=result.subUnsafe(ONE.toFormat(result.format))}return result}ceiling(){const comps=this.toString().split(".");if(comps.length===1){comps.push("0")}let result=FixedNumber.from(comps[0],this.format);const hasFraction=!comps[1].match(/^(0*)$/);if(!this.isNegative()&&hasFraction){result=result.addUnsafe(ONE.toFormat(result.format))}return result}round(decimals){if(decimals==null){decimals=0}const comps=this.toString().split(".");if(comps.length===1){comps.push("0")}if(decimals<0||decimals>80||decimals%1){logger.throwArgumentError("invalid decimal count","decimals",decimals)}if(comps[1].length<=decimals){return this}const factor=FixedNumber.from("1"+zeros$1.substring(0,decimals),this.format);const bump=BUMP.toFormat(this.format);return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor)}isZero(){return this.#value==="0.0"||this.#value==="0"}isNegative(){return this.#value[0]==="-"}toString(){return this.#value}toHexString(_width){throw new Error("TODO")}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(format){return FixedNumber.fromString(this.#value,format)}static fromValue(value,decimals=0,format="fixed"){return FixedNumber.fromString(formatFixed(value,decimals),FixedFormat.from(format))}static fromString(value,format="fixed"){const fixedFormat=FixedFormat.from(format);const numeric=parseFixed(value,fixedFormat.decimals);if(!fixedFormat.signed&&numeric<0){throwFault("unsigned value cannot be negative","overflow","value",value)}const hex=function(){if(fixedFormat.signed){return toHex(toTwos(numeric,fixedFormat.width))}return toHex(numeric,fixedFormat.width/8)}();const decimal=formatFixed(numeric,fixedFormat.decimals);return new FixedNumber(_constructorGuard,hex,decimal,fixedFormat)}static fromBytes(_value,format="fixed"){const value=logger.getBytes(_value,"value");const fixedFormat=FixedFormat.from(format);if(value.length>fixedFormat.width/8){throw new Error("overflow")}let numeric=toBigInt(value);if(fixedFormat.signed){numeric=fromTwos(numeric,fixedFormat.width)}const hex=toHex(toTwos(numeric,(fixedFormat.signed?0:1)+fixedFormat.width));const decimal=formatFixed(numeric,fixedFormat.decimals);return new FixedNumber(_constructorGuard,hex,decimal,fixedFormat)}static from(value,format){if(typeof value==="string"){return FixedNumber.fromString(value,format)}if(value instanceof Uint8Array){return FixedNumber.fromBytes(value,format)}try{return FixedNumber.fromValue(value,0,format)}catch(error){if(error.code!=="INVALID_ARGUMENT"){throw error}}return logger.throwArgumentError("invalid FixedNumber value","value",value)}static isFixedNumber(value){return!!(value&&value._isFixedNumber)}}const ONE=FixedNumber.from(1);const BUMP=FixedNumber.from("0.5");function hexlifyByte(value){let result=value.toString(16);while(result.length<2){result="0"+result}return"0x"+result}function unarrayifyInteger(data,offset,length){let result=0;for(let i=0;ioffset+1+length){logger.throwError("child data too short","BUFFER_OVERRUN",{buffer:data,length:length,offset:offset})}}return{consumed:1+length,result:result}}function _decode(data,offset){if(data.length===0){logger.throwError("data too short","BUFFER_OVERRUN",{buffer:data,length:0,offset:1})}const checkOffset=offset=>{if(offset>data.length){logger.throwError("data short segment too short","BUFFER_OVERRUN",{buffer:data,length:data.length,offset:offset})}};if(data[offset]>=248){const lengthLength=data[offset]-247;checkOffset(offset+1+lengthLength);const length=unarrayifyInteger(data,offset+1,lengthLength);checkOffset(offset+1+lengthLength+length);return _decodeChildren(data,offset,offset+1+lengthLength,lengthLength+length)}else if(data[offset]>=192){const length=data[offset]-192;checkOffset(offset+1+length);return _decodeChildren(data,offset,offset+1,length)}else if(data[offset]>=184){const lengthLength=data[offset]-183;checkOffset(offset+1+lengthLength);const length=unarrayifyInteger(data,offset+1,lengthLength);checkOffset(offset+1+lengthLength+length);const result=hexlify(data.slice(offset+1+lengthLength,offset+1+lengthLength+length));return{consumed:1+lengthLength+length,result:result}}else if(data[offset]>=128){const length=data[offset]-128;checkOffset(offset+1+length);const result=hexlify(data.slice(offset+1,offset+1+length));return{consumed:1+length,result:result}}return{consumed:1,result:hexlifyByte(data[offset])}}function decodeRlp(_data){const data=logger.getBytes(_data,"data");const decoded=_decode(data,0);if(decoded.consumed!==data.length){logger.throwArgumentError("unexpected junk after rlp payload","data",_data)}return decoded.result}function arrayifyInteger(value){const result=[];while(value){result.unshift(value&255);value>>=8}return result}function _encode(object){if(Array.isArray(object)){let payload=[];object.forEach(function(child){payload=payload.concat(_encode(child))});if(payload.length<=55){payload.unshift(192+payload.length);return payload}const length=arrayifyInteger(payload.length);length.unshift(247+length.length);return length.concat(payload)}const data=Array.prototype.slice.call(logger.getBytes(object,"object"));if(data.length===1&&data[0]<=127){return data}else if(data.length<=55){data.unshift(128+data.length);return data}const length=arrayifyInteger(data.length);length.unshift(183+length.length);return length.concat(data)}const nibbles="0123456789abcdef";function encodeRlp(object){let result="0x";for(const v of _encode(object)){result+=nibbles[v>>4];result+=nibbles[v&15]}return result}function getStore(store,key){return store[key]}function setStore(store,key,value){if(Object.isFrozen(store)){throw new Error(`frozen object is immuatable; cannot set ${String(key)}`)}store[key]=value}const names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function formatUnits(value,unit){if(typeof unit==="string"){const index=names.indexOf(unit);if(index===-1){logger.throwArgumentError("invalid unit","unit",unit)}unit=3*index}return formatFixed(value,unit!=null?unit:18)}function parseUnits(value,unit){if(typeof value!=="string"){logger.throwArgumentError("value must be a string","value",value)}if(typeof unit==="string"){const index=names.indexOf(unit);if(index===-1){logger.throwArgumentError("invalid unit","unit",unit)}unit=3*index}return parseFixed(value,unit!=null?unit:18)}function formatEther(wei){return formatUnits(wei,18)}function parseEther(ether){return parseUnits(ether,18)}let locked$4=false;const _keccak256=function(data){return keccak_256(data)};let __keccak256=_keccak256;function keccak256(_data){const data=logger.getBytes(_data,"data");return hexlify(__keccak256(data))}keccak256._=_keccak256;keccak256.lock=function(){locked$4=true};keccak256.register=function(func){if(locked$4){throw new TypeError("keccak256 is locked")}__keccak256=func};Object.freeze(keccak256);const BN_0$4=BigInt(0);const BN_36=BigInt(36);function getChecksumAddress(address){address=address.toLowerCase();const chars=address.substring(2).split("");const expanded=new Uint8Array(40);for(let i=0;i<40;i++){expanded[i]=chars[i].charCodeAt(0)}const hashed=logger.getBytes(keccak256(expanded));for(let i=0;i<40;i+=2){if(hashed[i>>1]>>4>=8){chars[i]=chars[i].toUpperCase()}if((hashed[i>>1]&15)>=8){chars[i+1]=chars[i+1].toUpperCase()}}return"0x"+chars.join("")}const ibanLookup={};for(let i=0;i<10;i++){ibanLookup[String(i)]=String(i)}for(let i=0;i<26;i++){ibanLookup[String.fromCharCode(65+i)]=String(10+i)}const safeDigits=15;function ibanChecksum(address){address=address.toUpperCase();address=address.substring(4)+address.substring(0,2)+"00";let expanded=address.split("").map(c=>{return ibanLookup[c]}).join("");while(expanded.length>=safeDigits){let block=expanded.substring(0,safeDigits);expanded=parseInt(block,10)%97+expanded.substring(block.length)}let checksum=String(98-parseInt(expanded,10)%97);while(checksum.length<2){checksum="0"+checksum}return checksum}const Base36=function(){const result={};for(let i=0;i<36;i++){const key="0123456789abcdefghijklmnopqrstuvwxyz"[i];result[key]=BigInt(i)}return result}();function fromBase36(value){value=value.toLowerCase();let result=BN_0$4;for(let i=0;iv.format()).join(",")})`}return this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.substring(0,5)==="bytes"}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple"){throw TypeError("not a tuple")}return this.#options}get arrayLength(){if(this.type!=="array"){throw TypeError("not an array")}if(this.#options===true){return-1}if(this.#options===false){return this.value.length}return null}static from(type,value){return new Typed(_gaurd,type,value)}static uint8(v){return n(v,8)}static uint16(v){return n(v,16)}static uint24(v){return n(v,24)}static uint32(v){return n(v,32)}static uint40(v){return n(v,40)}static uint48(v){return n(v,46)}static uint56(v){return n(v,56)}static uint64(v){return n(v,64)}static uint72(v){return n(v,72)}static uint80(v){return n(v,80)}static uint88(v){return n(v,88)}static uint96(v){return n(v,96)}static uint104(v){return n(v,104)}static uint112(v){return n(v,112)}static uint120(v){return n(v,120)}static uint128(v){return n(v,128)}static uint136(v){return n(v,136)}static uint144(v){return n(v,144)}static uint152(v){return n(v,152)}static uint160(v){return n(v,160)}static uint168(v){return n(v,168)}static uint176(v){return n(v,176)}static uint184(v){return n(v,184)}static uint192(v){return n(v,192)}static uint200(v){return n(v,200)}static uint208(v){return n(v,208)}static uint216(v){return n(v,216)}static uint224(v){return n(v,224)}static uint232(v){return n(v,232)}static uint240(v){return n(v,240)}static uint248(v){return n(v,248)}static uint256(v){return n(v,256)}static uint(v){return n(v,256)}static int8(v){return n(v,-8)}static int16(v){return n(v,-16)}static int24(v){return n(v,-24)}static int32(v){return n(v,-32)}static int40(v){return n(v,-40)}static int48(v){return n(v,-46)}static int56(v){return n(v,-56)}static int64(v){return n(v,-64)}static int72(v){return n(v,-72)}static int80(v){return n(v,-80)}static int88(v){return n(v,-88)}static int96(v){return n(v,-96)}static int104(v){return n(v,-104)}static int112(v){return n(v,-112)}static int120(v){return n(v,-120)}static int128(v){return n(v,-128)}static int136(v){return n(v,-136)}static int144(v){return n(v,-144)}static int152(v){return n(v,-152)}static int160(v){return n(v,-160)}static int168(v){return n(v,-168)}static int176(v){return n(v,-176)}static int184(v){return n(v,-184)}static int192(v){return n(v,-192)}static int200(v){return n(v,-200)}static int208(v){return n(v,-208)}static int216(v){return n(v,-216)}static int224(v){return n(v,-224)}static int232(v){return n(v,-232)}static int240(v){return n(v,-240)}static int248(v){return n(v,-248)}static int256(v){return n(v,-256)}static int(v){return n(v,-256)}static bytes(v){return b(v)}static bytes1(v){return b(v,1)}static bytes2(v){return b(v,2)}static bytes3(v){return b(v,3)}static bytes4(v){return b(v,4)}static bytes5(v){return b(v,5)}static bytes6(v){return b(v,6)}static bytes7(v){return b(v,7)}static bytes8(v){return b(v,8)}static bytes9(v){return b(v,9)}static bytes10(v){return b(v,10)}static bytes11(v){return b(v,11)}static bytes12(v){return b(v,12)}static bytes13(v){return b(v,13)}static bytes14(v){return b(v,14)}static bytes15(v){return b(v,15)}static bytes16(v){return b(v,16)}static bytes17(v){return b(v,17)}static bytes18(v){return b(v,18)}static bytes19(v){return b(v,19)}static bytes20(v){return b(v,20)}static bytes21(v){return b(v,21)}static bytes22(v){return b(v,22)}static bytes23(v){return b(v,23)}static bytes24(v){return b(v,24)}static bytes25(v){return b(v,25)}static bytes26(v){return b(v,26)}static bytes27(v){return b(v,27)}static bytes28(v){return b(v,28)}static bytes29(v){return b(v,29)}static bytes30(v){return b(v,30)}static bytes31(v){return b(v,31)}static bytes32(v){return b(v,32)}static address(v){return new Typed(_gaurd,"address",v)}static bool(v){return new Typed(_gaurd,"bool",!!v)}static string(v){return new Typed(_gaurd,"string",v)}static array(v,dynamic){throw new Error("not implemented yet");return new Typed(_gaurd,"array",v,dynamic)}static tuple(v,name){throw new Error("not implemented yet");return new Typed(_gaurd,"tuple",v,name)}static overrides(v){return new Typed(_gaurd,"overrides",Object.assign({},v))}static isTyped(value){return value&&value._typedSymbol===_typedSymbol}static dereference(value,type){if(Typed.isTyped(value)){if(value.type!==type){throw new Error(`invalid type: expecetd ${type}, got ${value.type}`)}return value.value}return value}}class AddressCoder extends Coder{constructor(localName){super("address","address",localName,false)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(writer,_value){let value=Typed.dereference(_value,"string");try{value=getAddress(value)}catch(error){return this._throwError(error.message,_value)}return writer.writeValue(value)}decode(reader){return getAddress(toHex(reader.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(coder){super(coder.name,coder.type,"_",coder.dynamic);this.coder=coder}defaultValue(){return this.coder.defaultValue()}encode(writer,value){return this.coder.encode(writer,value)}decode(reader){return this.coder.decode(reader)}}function pack(writer,coders,values){let arrayValues=[];if(Array.isArray(values)){arrayValues=values}else if(values&&typeof values==="object"){let unique={};arrayValues=coders.map(coder=>{const name=coder.localName;if(!name){logger.throwError("cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values})}if(unique[name]){logger.throwError("cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values})}unique[name]=true;return values[name]})}else{logger.throwArgumentError("invalid tuple value","tuple",values)}if(coders.length!==arrayValues.length){logger.throwArgumentError("types/value length mismatch","tuple",values)}let staticWriter=new Writer;let dynamicWriter=new Writer;let updateFuncs=[];coders.forEach((coder,index)=>{let value=arrayValues[index];if(coder.dynamic){let dynamicOffset=dynamicWriter.length;coder.encode(dynamicWriter,value);let updateFunc=staticWriter.writeUpdatableValue();updateFuncs.push(baseOffset=>{updateFunc(baseOffset+dynamicOffset)})}else{coder.encode(staticWriter,value)}});updateFuncs.forEach(func=>{func(staticWriter.length)});let length=writer.appendWriter(staticWriter);length+=writer.appendWriter(dynamicWriter);return length}function unpack(reader,coders){let values=[];let keys=[];let baseReader=reader.subReader(0);coders.forEach(coder=>{let value=null;if(coder.dynamic){let offset=reader.readIndex();let offsetReader=baseReader.subReader(offset);try{value=coder.decode(offsetReader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}else{try{value=coder.decode(reader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}if(value==undefined){throw new Error("investigate")}values.push(value);keys.push(coder.localName||null)});return Result.fromItems(values,keys)}class ArrayCoder extends Coder{coder;length;constructor(coder,length,localName){const type=coder.type+"["+(length>=0?length:"")+"]";const dynamic=length===-1||coder.dynamic;super("array",type,localName,dynamic);defineProperties(this,{coder:coder,length:length})}defaultValue(){const defaultChild=this.coder.defaultValue();const result=[];for(let i=0;ireader.dataLength){logger.throwError("insufficient data length","BUFFER_OVERRUN",{buffer:reader.bytes,offset:count*WordSize,length:reader.dataLength})}}let coders=[];for(let i=0;ibounds||value<-(bounds+BN_1$4)){this._throwError("value out-of-bounds",_value)}}else if(valuemask(maxUintValue,this.size*8)){this._throwError("value out-of-bounds",_value)}value=mask(toTwos(value,this.size*8),this.size*8);if(this.signed){value=toTwos(fromTwos(value,this.size*8),8*WordSize)}return writer.writeValue(value)}decode(reader){let value=mask(reader.readValue(),this.size*8);if(this.signed){value=fromTwos(value,this.size*8)}return value}}class StringCoder extends DynamicBytesCoder{constructor(localName){super("string",localName)}defaultValue(){return""}encode(writer,_value){return super.encode(writer,toUtf8Bytes(Typed.dereference(_value,"string")))}decode(reader){return toUtf8String(super.decode(reader))}}class TupleCoder extends Coder{coders;constructor(coders,localName){let dynamic=false;const types=[];coders.forEach(coder=>{if(coder.dynamic){dynamic=true}types.push(coder.type)});const type="tuple("+types.join(",")+")";super("tuple",type,localName,dynamic);defineProperties(this,{coders:Object.freeze(coders.slice())})}defaultValue(){const values=[];this.coders.forEach(coder=>{values.push(coder.defaultValue())});const uniqueNames=this.coders.reduce((accum,coder)=>{const name=coder.localName;if(name){if(!accum[name]){accum[name]=0}accum[name]++}return accum},{});this.coders.forEach((coder,index)=>{let name=coder.localName;if(!name||uniqueNames[name]!==1){return}if(name==="length"){name="_length"}if(values[name]!=null){return}values[name]=values[index]});return Object.freeze(values)}encode(writer,_value){const value=Typed.dereference(_value,"tuple");return pack(writer,this.coders,value)}decode(reader){return unpack(reader,this.coders)}}var FormatType;(function(FormatType){FormatType["sighash"]="sighash";FormatType["minimal"]="minimal";FormatType["full"]="full";FormatType["json"]="json"})(FormatType||(FormatType={}));function setify(items){const result=new Set;items.forEach(k=>result.add(k));return Object.freeze(result)}const _kwVisib="constant external internal payable private public pure view";const KwVisib=setify(_kwVisib.split(" "));const _kwTypes="constructor error event function struct";const KwTypes=setify(_kwTypes.split(" "));const _kwModifiers="calldata memory storage payable indexed";const KwModifiers=setify(_kwModifiers.split(" "));const _kwOther="tuple returns";const _keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" ");const Keywords=setify(_keywords.split(" "));const SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"};const regexWhitespace=new RegExp("^(\\s*)");const regexNumber$1=new RegExp("^([0-9]+)");const regexIdentifier=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");const regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))");class TokenString{#offset;#tokens;get offset(){return this.#offset}get length(){return this.#tokens.length-this.#offset}constructor(tokens){this.#offset=0;this.#tokens=tokens.slice()}clone(){return new TokenString(this.#tokens)}reset(){this.#offset=0}#subTokenString(from=0,to=0){return new TokenString(this.#tokens.slice(from,to).map(t=>{return Object.freeze(Object.assign({},t,{match:t.match-from,linkBack:t.linkBack-from,linkNext:t.linkNext-from}));return t}))}popKeyword(allowed){const top=this.peek();if(top.type!=="KEYWORD"||!allowed.has(top.text)){throw new Error(`expected keyword ${top.text}`)}return this.pop().text}popType(type){if(this.peek().type!==type){throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`)}return this.pop().text}popParen(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=this.#subTokenString(this.#offset+1,top.match+1);this.#offset=top.match+1;return result}popParams(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=[];while(this.#offset=this.#tokens.length){throw new Error("out-of-bounds")}return this.#tokens[this.#offset]}peekKeyword(allowed){const top=this.peekType("KEYWORD");return top!=null&&allowed.has(top)?top:null}peekType(type){if(this.length===0){return null}const top=this.peek();return top.type===type?top.text:null}pop(){const result=this.peek();this.#offset++;return result}toString(){const tokens=[];for(let i=this.#offset;i`}}function lex(text){const tokens=[];const throwError=message=>{const token=offset0&&tokens[tokens.length-1].type==="NUMBER"){const value=tokens.pop().text;suffix=value+suffix;tokens[tokens.length-1].value=logger.getNumber(value)}if(tokens.length===0||tokens[tokens.length-1].type!=="BRACKET"){throw new Error("missing opening bracket")}tokens[tokens.length-1].text+=suffix}continue}match=cur.match(regexIdentifier);if(match){token.text=match[1];offset+=token.text.length;if(Keywords.has(token.text)){token.type="KEYWORD";continue}if(token.text.match(regexType)){token.type="TYPE";continue}token.type="ID";continue}match=cur.match(regexNumber$1);if(match){token.text=match[1];token.type="NUMBER";offset+=token.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`)}return new TokenString(tokens.map(t=>Object.freeze(t)))}function allowSingle(set,allowed){let included=[];for(const key in allowed.keys()){if(set.has(key)){included.push(key)}}if(included.length>1){throw new Error(`conflicting types: ${included.join(", ")}`)}}function consumeName(type,tokens){if(tokens.peekKeyword(KwTypes)){const keyword=tokens.pop().text;if(keyword!==type){throw new Error(`expected ${type}, got ${keyword}`)}}return tokens.popType("ID")}function consumeKeywords(tokens,allowed){const keywords=new Set;while(true){const keyword=tokens.peekType("KEYWORD");if(keyword==null||allowed&&!allowed.has(keyword)){break}tokens.pop();if(keywords.has(keyword)){throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`)}keywords.add(keyword)}return Object.freeze(keywords)}function consumeMutability(tokens){let modifiers=consumeKeywords(tokens,KwVisib);allowSingle(modifiers,setify("constant payable nonpayable".split(" ")));allowSingle(modifiers,setify("pure view payable nonpayable".split(" ")));if(modifiers.has("view")){return"view"}if(modifiers.has("pure")){return"pure"}if(modifiers.has("payable")){return"payable"}if(modifiers.has("nonpayable")){return"nonpayable"}if(modifiers.has("constant")){return"view"}return"nonpayable"}function consumeParams(tokens,allowIndexed){return tokens.popParams().map(t=>ParamType.fromTokens(t,allowIndexed))}function consumeGas(tokens){if(tokens.peekType("AT")){tokens.pop();if(tokens.peekType("NUMBER")){return logger.getBigInt(tokens.pop().text)}throw new Error("invalid gas")}return null}function consumeEoi(tokens){if(tokens.length){throw new Error(`unexpected tokens: ${tokens.toString()}`)}}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(type){const match=type.match(regexType);if(!match){return logger.throwArgumentError("invalid type","type",type)}if(type==="uint"){return"uint256"}if(type==="int"){return"int256"}if(match[2]){const length=parseInt(match[2]);if(length===0||length>32){logger.throwArgumentError("invalid bytes length","type",type)}}else if(match[3]){const size=parseInt(match[3]);if(size===0||size>256||size%8){logger.throwArgumentError("invalid numeric width","type",type)}}return type}const _guard$3={};const internal$1=Symbol.for("_ethers_internal");const ParamTypeInternal="_ParamTypeInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(guard,name,type,baseType,indexed,components,arrayLength,arrayChildren){logger.assertPrivate(guard,_guard$3,"ParamType");Object.defineProperty(this,internal$1,{value:ParamTypeInternal});if(components){components=Object.freeze(components.slice())}if(baseType==="array"){if(arrayLength==null||arrayChildren==null){throw new Error("")}}else if(arrayLength!=null||arrayChildren!=null){throw new Error("")}if(baseType==="tuple"){if(components==null){throw new Error("")}}else if(components!=null){throw new Error("")}defineProperties(this,{name:name,type:type,baseType:baseType,indexed:indexed,components:components,arrayLength:arrayLength,arrayChildren:arrayChildren})}format(format=FormatType.sighash){if(!FormatType[format]){logger.throwArgumentError("invalid format type","format",format)}if(format===FormatType.json){let result={type:this.baseType==="tuple"?"tuple":this.type,name:this.name||undefined};if(typeof this.indexed==="boolean"){result.indexed=this.indexed}if(this.isTuple()){result.components=this.components.map(c=>JSON.parse(c.format(format)))}return JSON.stringify(result)}let result="";if(this.isArray()){result+=this.arrayChildren.format(format);result+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`}else{if(this.isTuple()){if(format!==FormatType.sighash){result+=this.type}result+="("+this.components.map(comp=>comp.format(format)).join(format===FormatType.full?", ":",")+")"}else{result+=this.type}}if(format!==FormatType.sighash){if(this.indexed===true){result+=" indexed"}if(format===FormatType.full&&this.name){result+=" "+this.name}}return result}static isArray(value){return value&&value.baseType==="array"}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(value,process){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invlaid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}return value.map(v=>this.arrayChildren.walk(v,process))}if(this.isTuple()){if(!Array.isArray(value)){throw new Error("invlaid tuple value")}if(value.length!==this.components.length){throw new Error("array is wrong length")}return value.map((v,i)=>this.components[i].walk(v,process))}return process(this.type,value)}#walkAsync(promises,value,process,setValue){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invlaid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const childType=this.arrayChildren;const result=value.slice();result.forEach((value,index)=>{childType.#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}if(this.isTuple()){const components=this.components;let result;if(Array.isArray(value)){result=value.slice()}else{if(value==null||typeof value!=="object"){throw new Error("invlaid tuple value")}result=components.map(param=>{if(!param.name){throw new Error("cannot use object value with unnamed components")}if(!(param.name in value)){throw new Error(`missing value for component ${param.name}`)}return value[param.name]})}if(value.length!==this.components.length){throw new Error("array is wrong length")}result.forEach((value,index)=>{components[index].#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}const result=process(this.type,value);if(result.then){promises.push(async function(){setValue(await result)}())}else{setValue(result)}}async walkAsync(value,process){const promises=[];const result=[value];this.#walkAsync(promises,value,process,value=>{result[0]=value});if(promises.length){await Promise.all(promises)}return result[0]}static from(obj,allowIndexed){if(ParamType.isParamType(obj)){return obj}if(typeof obj==="string"){return ParamType.fromTokens(lex(obj),allowIndexed)}if(obj instanceof TokenString){return ParamType.fromTokens(obj,allowIndexed)}const name=obj.name;if(name&&(typeof name!=="string"||!name.match(regexIdentifier))){logger.throwArgumentError("invalid name","obj.name",name)}let indexed=obj.indexed;if(indexed!=null){if(!allowIndexed){logger.throwArgumentError("parameter cannot be indexed","obj.indexed",obj.indexed)}indexed=!!indexed}let type=obj.type;let arrayMatch=type.match(regexArrayType);if(arrayMatch){const arrayLength=arrayMatch[2];const arrayChildren=ParamType.from({type:arrayMatch[1],components:obj.components});return new ParamType(_guard$3,name,type,"array",indexed,null,arrayLength,arrayChildren)}if(type.substring(0,5)==="tuple("||type[0]==="("){const comps=obj.components!=null?obj.components.map(c=>ParamType.from(c)):null;const tuple=new ParamType(_guard$3,name,type,"tuple",indexed,comps,null,null);return tuple}type=verifyBasicType(obj.type);return new ParamType(_guard$3,name,type,type,indexed,null,null,null)}static fromObject(obj,allowIndexed){throw new Error("@TODO")}static fromTokens(tokens,allowIndexed){let type="",baseType="";let comps=null;if(consumeKeywords(tokens,setify(["tuple"])).has("tuple")||tokens.peekType("OPEN_PAREN")){baseType="tuple";comps=tokens.popParams().map(t=>ParamType.from(t));type=`tuple(${comps.map(c=>c.format()).join(",")})`}else{type=verifyBasicType(tokens.popType("TYPE"));baseType=type}let arrayChildren=null;let arrayLength=null;while(tokens.length&&tokens.peekType("BRACKET")){const bracket=tokens.pop();arrayChildren=new ParamType(_guard$3,"",type,baseType,null,comps,arrayLength,arrayChildren);arrayLength=bracket.value;type+=bracket.text;baseType="array";comps=null}let indexed=null;const keywords=consumeKeywords(tokens,KwModifiers);if(keywords.has("indexed")){if(!allowIndexed){throw new Error("")}indexed=true}const name=tokens.peekType("ID")?tokens.pop().text:"";if(tokens.length){throw new Error("leftover tokens")}return new ParamType(_guard$3,name,type,baseType,indexed,comps,arrayLength,arrayChildren)}static isParamType(value){return value&&value[internal$1]===ParamTypeInternal}}var FragmentType;(function(FragmentType){FragmentType["constructor"]="constructor";FragmentType["error"]="error";FragmentType["event"]="event";FragmentType["function"]="function";FragmentType["struct"]="struct"})(FragmentType||(FragmentType={}));class Fragment{type;inputs;constructor(guard,type,inputs){logger.assertPrivate(guard,_guard$3,"Fragment");inputs=Object.freeze(inputs.slice());defineProperties(this,{type:type,inputs:inputs})}static from(obj){if(typeof obj==="string"){return this.fromString(obj)}if(obj instanceof TokenString){return this.fromTokens(obj)}if(typeof obj==="object"){return this.fromObject(obj)}throw new Error(`unsupported type: ${obj}`)}static fromObject(obj){switch(obj.type){case"constructor":return ConstructorFragment.fromObject(obj);case"error":return ErrorFragment.fromObject(obj);case"event":return EventFragment.fromObject(obj);case"function":return FunctionFragment.fromObject(obj);case"struct":return StructFragment.fromObject(obj)}throw new Error("not implemented yet")}static fromString(text){try{Fragment.from(JSON.parse(text))}catch(e){}return Fragment.fromTokens(lex(text))}static fromTokens(tokens){const type=tokens.popKeyword(KwTypes);switch(type){case"constructor":return ConstructorFragment.fromTokens(tokens);case"error":return ErrorFragment.fromTokens(tokens);case"event":return EventFragment.fromTokens(tokens);case"function":return FunctionFragment.fromTokens(tokens);case"struct":return StructFragment.fromTokens(tokens)}throw new Error(`unsupported type: ${type}`)}static isConstructor(value){return value&&value.type==="constructor"}static isError(value){return value&&value.type==="error"}static isEvent(value){return value&&value.type==="event"}static isFunction(value){return value&&value.type==="function"}static isStruct(value){return value&&value.type==="struct"}}class NamedFragment extends Fragment{name;constructor(guard,type,name,inputs){super(guard,type,inputs);inputs=Object.freeze(inputs.slice());defineProperties(this,{name:name})}}function joinParams(format,params){return"("+params.map(p=>p.format(format)).join(format===FormatType.full?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(guard,name,inputs){super(guard,FragmentType.error,name,inputs)}format(format=FormatType.sighash){if(!FormatType[format]){logger.throwArgumentError("invalid format type","format",format)}if(format===FormatType.json){return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(input=>JSON.parse(input.format(format)))})}const result=[];if(format!==FormatType.sighash){result.push("error")}result.push(this.name+joinParams(format,this.inputs));return result.join(" ")}static fromString(text){return ErrorFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("error",tokens);const inputs=consumeParams(tokens);consumeEoi(tokens);return new ErrorFragment(_guard$3,name,inputs)}}class EventFragment extends NamedFragment{anonymous;constructor(guard,name,inputs,anonymous){super(guard,FragmentType.event,name,inputs);defineProperties(this,{anonymous:anonymous})}format(format=FormatType.sighash){if(!FormatType[format]){logger.throwArgumentError("invalid format type","format",format)}if(format===FormatType.json){return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[];if(format!==FormatType.sighash){result.push("event")}result.push(this.name+joinParams(format,this.inputs));if(format!==FormatType.sighash&&this.anonymous){result.push("anonymous")}return result.join(" ")}static fromString(text){return EventFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("event",tokens);const inputs=consumeParams(tokens,true);const anonymous=!!consumeKeywords(tokens,setify(["anonymous"])).has("anonymous");consumeEoi(tokens);return new EventFragment(_guard$3,name,inputs,anonymous)}}class ConstructorFragment extends Fragment{payable;gas;constructor(guard,type,inputs,payable,gas){super(guard,type,inputs);defineProperties(this,{payable:payable,gas:gas})}format(format=FormatType.sighash){if(!FormatType[format]){logger.throwArgumentError("invalid format type","format",format)}if(format===FormatType.sighash){logger.throwError("cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"})}if(format===FormatType.json){return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[`constructor${joinParams(format,this.inputs)}`];result.push(this.payable?"payable":"nonpayable");if(this.gas!=null){result.push(`@${this.gas.toString()}`)}return result.join(" ")}static fromString(text){return ConstructorFragment.fromTokens(lex(text))}static fromObject(obj){throw new Error("TODO")}static fromTokens(tokens){consumeKeywords(tokens,setify(["constructor"]));const inputs=consumeParams(tokens);const payable=!!consumeKeywords(tokens,setify(["payable"])).has("payable");const gas=consumeGas(tokens);consumeEoi(tokens);return new ConstructorFragment(_guard$3,FragmentType.constructor,inputs,payable,gas)}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(guard,name,stateMutability,inputs,outputs,gas){super(guard,FragmentType.function,name,inputs);outputs=Object.freeze(outputs.slice());const constant=stateMutability==="view"||stateMutability==="pure";const payable=stateMutability==="payable";defineProperties(this,{constant:constant,gas:gas,outputs:outputs,payable:payable,stateMutability:stateMutability})}format(format=FormatType.sighash){if(!FormatType[format]){logger.throwArgumentError("invalid format type","format",format)}if(format===FormatType.json){return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:undefined,payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format))),outputs:this.outputs.map(o=>JSON.parse(o.format(format)))})}const result=[];if(format!==FormatType.sighash){result.push("function")}result.push(this.name+joinParams(format,this.inputs));if(format!==FormatType.sighash){if(this.stateMutability!=="nonpayable"){result.push(this.stateMutability)}if(this.outputs&&this.outputs.length){result.push("returns");result.push(joinParams(format,this.outputs))}if(this.gas!=null){result.push(`@${this.gas.toString()}`)}}return result.join(" ")}static fromString(text){return FunctionFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("function",tokens);const inputs=consumeParams(tokens);const mutability=consumeMutability(tokens);let outputs=[];if(consumeKeywords(tokens,setify(["returns"])).has("returns")){outputs=consumeParams(tokens)}const gas=consumeGas(tokens);consumeEoi(tokens);return new FunctionFragment(_guard$3,name,mutability,inputs,outputs,gas)}}class StructFragment extends NamedFragment{format(){throw new Error("@TODO")}static fromString(text){return StructFragment.fromTokens(lex(text))}static fromTokens(tokens){const name=consumeName("struct",tokens);const inputs=consumeParams(tokens);consumeEoi(tokens);return new StructFragment(_guard$3,FragmentType.struct,name,inputs)}}const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/);const paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);class AbiCoder{#getCoder(param){if(param.isArray()){return new ArrayCoder(this.#getCoder(param.arrayChildren),param.arrayLength,param.name)}if(param.isTuple()){return new TupleCoder(param.components.map(c=>this.#getCoder(c)),param.name)}switch(param.baseType){case"address":return new AddressCoder(param.name);case"bool":return new BooleanCoder(param.name);case"string":return new StringCoder(param.name);case"bytes":return new BytesCoder(param.name);case"":return new NullCoder(param.name)}let match=param.type.match(paramTypeNumber);if(match){let size=parseInt(match[2]||"256");if(size===0||size>256||size%8!==0){logger.throwArgumentError("invalid "+match[1]+" bit length","param",param)}return new NumberCoder(size/8,match[1]==="int",param.name)}match=param.type.match(paramTypeBytes);if(match){let size=parseInt(match[1]);if(size===0||size>32){logger.throwArgumentError("invalid bytes length","param",param)}return new FixedBytesCoder(size,param.name)}return logger.throwArgumentError("invalid type","type",param.type)}getDefaultValue(types){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.defaultValue()}encode(types,values){logger.assertArgumentCount(values.length,types.length,"types/values length mismatch");const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");const writer=new Writer;coder.encode(writer,values);return writer.data}decode(types,data,loose){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.decode(new Reader(data,loose))}}const defaultAbiCoder=new AbiCoder;function formatBytes32String(text){const bytes=toUtf8Bytes(text);if(bytes.length>31){throw new Error("bytes32 string must be less than 32 bytes")}return zeroPadBytes(bytes,32)}function parseBytes32String(_bytes){const data=logger.getBytes(_bytes,"bytes");if(data.length!==32){throw new Error("invalid bytes32 - not 32 bytes long")}if(data[31]!==0){throw new Error("invalid bytes32 string - no null terminator")}let length=31;while(data[length-1]===0){length--}return toUtf8String(data.slice(0,length))}class HMAC extends Hash{constructor(hash,_key){super();this.finished=false;this.destroyed=false;assert.hash(hash);const key=toBytes(_key);this.iHash=hash.create();if(!(this.iHash instanceof Hash))throw new TypeError("Expected instance of class which extends utils.Hash");const blockLen=this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const pad=new Uint8Array(blockLen);pad.set(key.length>this.iHash.blockLen?hash.create().update(key).digest():key);for(let i=0;inew HMAC(hash,key).update(message).digest();hmac.create=(hash,key)=>new HMAC(hash,key);function pbkdf2Init(hash,_password,_salt,_opts){assert.hash(hash);const opts=checkOpts({dkLen:32,asyncTick:10},_opts);const{c,dkLen,asyncTick}=opts;assert.number(c);assert.number(dkLen);assert.number(asyncTick);if(c<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const password=toBytes(_password);const salt=toBytes(_salt);const DK=new Uint8Array(dkLen);const PRF=hmac.create(hash,password);const PRFSalt=PRF._cloneInto().update(salt);return{c:c,dkLen:dkLen,asyncTick:asyncTick,DK:DK,PRF:PRF,PRFSalt:PRFSalt}}function pbkdf2Output(PRF,PRFSalt,DK,prfW,u){PRF.destroy();PRFSalt.destroy();if(prfW)prfW.destroy();u.fill(0);return DK}function pbkdf2$1(hash,password,salt,opts){const{c,dkLen,DK,PRF,PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4);const view=createView(arr);const u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos{PRF._cloneInto(prfW).update(u).digestInto(u);for(let i=0;i>_32n&_u32_max);const wl=Number(value&_u32_max);const h=isLE?4:0;const l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE);view.setUint32(byteOffset+l,wl,isLE)}class SHA2 extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super();this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE;this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.buffer=new Uint8Array(blockLen);this.view=createView(this.buffer)}update(data){assert.exists(this);const{view,buffer,blockLen}=this;data=toBytes(data);const len=data.length;for(let pos=0;posblockLen-pos){this.process(view,0);pos=0}for(let i=pos;ioview.setUint32(4*i,v,isLE))}digest(){const{buffer,outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneInto(to){to||(to=new this.constructor);to.set(...this.get());const{blockLen,buffer,length,finished,destroyed,pos}=this;to.length=length;to.pos=pos;to.finished=finished;to.destroyed=destroyed;if(length%blockLen)to.buffer.set(buffer);return to}}const Chi=(a,b,c)=>a&b^~a&c;const Maj=(a,b,c)=>a&b^a&c^b&c;const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,false);this.A=IV[0]|0;this.B=IV[1]|0;this.C=IV[2]|0;this.D=IV[3]|0;this.E=IV[4]|0;this.F=IV[5]|0;this.G=IV[6]|0;this.H=IV[7]|0}get(){const{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0;this.B=B|0;this.C=C|0;this.D=D|0;this.E=E|0;this.F=F|0;this.G=G|0;this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W[i-15];const W2=SHA256_W[i-2];const s0=rotr(W15,7)^rotr(W15,18)^W15>>>3;const s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){const sigma1=rotr(E,6)^rotr(E,11)^rotr(E,25);const T1=H+sigma1+Chi(E,F,G)+SHA256_K[i]+SHA256_W[i]|0;const sigma0=rotr(A,2)^rotr(A,13)^rotr(A,22);const T2=sigma0+Maj(A,B,C)|0;H=G;G=F;F=E;E=D+T1|0;D=C;C=B;B=A;A=T1+T2|0}A=A+this.A|0;B=B+this.B|0;C=C+this.C|0;D=D+this.D|0;E=E+this.E|0;F=F+this.F|0;G=G+this.G|0;H=H+this.H|0;this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0);this.buffer.fill(0)}}const sha256$1=wrapConstructor(()=>new SHA256);const[SHA512_Kh,SHA512_Kl]=u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n)));const SHA512_W_H=new Uint32Array(80);const SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,false);this.Ah=1779033703|0;this.Al=4089235720|0;this.Bh=3144134277|0;this.Bl=2227873595|0;this.Ch=1013904242|0;this.Cl=4271175723|0;this.Dh=2773480762|0;this.Dl=1595750129|0;this.Eh=1359893119|0;this.El=2917565137|0;this.Fh=2600822924|0;this.Fl=725511199|0;this.Gh=528734635|0;this.Gl=4215389547|0;this.Hh=1541459225|0;this.Hl=327033209|0}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=u64.rotrSH(W15h,W15l,1)^u64.rotrSH(W15h,W15l,8)^u64.shrSH(W15h,W15l,7);const s0l=u64.rotrSL(W15h,W15l,1)^u64.rotrSL(W15h,W15l,8)^u64.shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=u64.rotrSH(W2h,W2l,19)^u64.rotrBH(W2h,W2l,61)^u64.shrSH(W2h,W2l,6);const s1l=u64.rotrSL(W2h,W2l,19)^u64.rotrBL(W2h,W2l,61)^u64.shrSL(W2h,W2l,6);const SUMl=u64.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=u64.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64.rotrSH(Eh,El,14)^u64.rotrSH(Eh,El,18)^u64.rotrBH(Eh,El,41);const sigma1l=u64.rotrSL(Eh,El,14)^u64.rotrSL(Eh,El,18)^u64.rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=u64.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=u64.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=u64.rotrSH(Ah,Al,28)^u64.rotrBH(Ah,Al,34)^u64.rotrBH(Ah,Al,39);const sigma0l=u64.rotrSL(Ah,Al,28)^u64.rotrBL(Ah,Al,34)^u64.rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=u64.add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=u64.add3L(T1l,sigma0l,MAJl);Ah=u64.add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=u64.add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=u64.add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=u64.add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=u64.add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=u64.add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=u64.add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=u64.add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=u64.add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){SHA512_W_H.fill(0);SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class SHA512_256 extends SHA512{constructor(){super();this.Ah=573645204|0;this.Al=4230739756|0;this.Bh=2673172387|0;this.Bl=3360449730|0;this.Ch=596883563|0;this.Cl=1867755857|0;this.Dh=2520282905|0;this.Dl=1497426621|0;this.Eh=2519219938|0;this.El=2827943907|0;this.Fh=3193839141|0;this.Fl=1401305490|0;this.Gh=721525244|0;this.Gl=746961066|0;this.Hh=246885852|0;this.Hl=2177182882|0;this.outputLen=32}}class SHA384 extends SHA512{constructor(){super();this.Ah=3418070365|0;this.Al=3238371032|0;this.Bh=1654270250|0;this.Bl=914150663|0;this.Ch=2438529370|0;this.Cl=812702999|0;this.Dh=355462360|0;this.Dl=4144912697|0;this.Eh=1731405415|0;this.El=4290775857|0;this.Fh=2394180231|0;this.Fl=1750603025|0;this.Gh=3675008525|0;this.Gl=1694076839|0;this.Hh=1203062813|0;this.Hl=3204075428|0;this.outputLen=48}}const sha512$1=wrapConstructor(()=>new SHA512);const sha512_256=wrapConstructor(()=>new SHA512_256);const sha384=wrapConstructor(()=>new SHA384);function getGlobal$1(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const anyGlobal=getGlobal$1();const crypto$1=anyGlobal.crypto||anyGlobal.msCrypto;function createHash(algo){switch(algo){case"sha256":return sha256$1.create();case"sha512":return sha512$1.create()}return logger.throwArgumentError("invalid hashing algorithm name","algorithm",algo)}function createHmac(_algo,key){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];if(algo==null){return logger.throwArgumentError("invalid hmac algorithm","algorithm",_algo)}return hmac.create(algo,key)}function pbkdf2Sync(password,salt,iterations,keylen,_algo){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];if(algo==null){return logger.throwArgumentError("invalid pbkdf2 algorithm","algorithm",_algo)}return pbkdf2$1(algo,password,salt,{c:iterations,dkLen:keylen})}function randomBytes$1(length){if(crypto$1==null){return logger.throwError("platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"})}if(!Number.isInteger(length)||length<=0||length>1024){logger.throwArgumentError("invalid length","length",length)}const result=new Uint8Array(length);crypto$1.getRandomValues(result);return result}let locked$3=false;const _computeHmac=function(algorithm,key,data){return"0x"+createHmac(algorithm,key).update(data).digest("hex")};let __computeHmac=_computeHmac;function computeHmac(algorithm,_key,_data){const key=logger.getBytes(_key,"key");const data=logger.getBytes(_data,"data");return hexlify(__computeHmac(algorithm,key,data))}computeHmac._=_computeHmac;computeHmac.lock=function(){locked$3=true};computeHmac.register=function(func){if(locked$3){throw new Error("computeHmac is locked")}__computeHmac=func};Object.freeze(computeHmac);const Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]);const Id=Uint8Array.from({length:16},(_,i)=>i);const Pi=Id.map(i=>(9*i+5)%16);let idxL=[Id];let idxR=[Pi];for(let i=0;i<4;i++)for(let j of[idxL,idxR])j.push(j[i].map(k=>Rho[k]));const shifts=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>new Uint8Array(i));const shiftsL=idxL.map((idx,i)=>idx.map(j=>shifts[i][j]));const shiftsR=idxR.map((idx,i)=>idx.map(j=>shifts[i][j]));const Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]);const Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);const rotl$1=(word,shift)=>word<>>32-shift;function f(group,x,y,z){if(group===0)return x^y^z;else if(group===1)return x&y|~x&z;else if(group===2)return(x|~y)^z;else if(group===3)return x&z|y&~z;else return x^(y|~z)}const BUF=new Uint32Array(16);class RIPEMD160 extends SHA2{constructor(){super(64,20,8,true);this.h0=1732584193|0;this.h1=4023233417|0;this.h2=2562383102|0;this.h3=271733878|0;this.h4=3285377520|0}get(){const{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0;this.h1=h1|0;this.h2=h2|0;this.h3=h3|0;this.h4=h4|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF[i]=view.getUint32(offset,true);let al=this.h0|0,ar=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){const rGroup=4-group;const hbl=Kl[group],hbr=Kr[group];const rl=idxL[group],rr=idxR[group];const sl=shiftsL[group],sr=shiftsR[group];for(let i=0;i<16;i++){const tl=rotl$1(al+f(group,bl,cl,dl)+BUF[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl$1(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){const tr=rotl$1(ar+f(rGroup,br,cr,dr)+BUF[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=rotl$1(cr,10)|0,cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){BUF.fill(0)}destroy(){this.destroyed=true;this.buffer.fill(0);this.set(0,0,0,0,0)}}const ripemd160$1=wrapConstructor(()=>new RIPEMD160);let locked$2=false;const _ripemd160=function(data){return ripemd160$1(data)};let __ripemd160=_ripemd160;function ripemd160(_data){const data=logger.getBytes(_data,"data");return hexlify(__ripemd160(data))}ripemd160._=_ripemd160;ripemd160.lock=function(){locked$2=true};ripemd160.register=function(func){if(locked$2){throw new TypeError("ripemd160 is locked")}__ripemd160=func};Object.freeze(ripemd160);let locked$1=false;const _pbkdf2=function(password,salt,iterations,keylen,algo){return pbkdf2Sync(password,salt,iterations,keylen,algo)};let __pbkdf2=_pbkdf2;function pbkdf2(_password,_salt,iterations,keylen,algo){const password=logger.getBytes(_password,"password");const salt=logger.getBytes(_salt,"salt");return hexlify(__pbkdf2(password,salt,iterations,keylen,algo))}pbkdf2._=_pbkdf2;pbkdf2.lock=function(){locked$1=true};pbkdf2.register=function(func){if(locked$1){throw new Error("pbkdf2 is locked")}__pbkdf2=func};Object.freeze(pbkdf2);let locked=false;const _randomBytes=function(length){return new Uint8Array(randomBytes$1(length))};let __randomBytes=_randomBytes;function randomBytes(length){return __randomBytes(length)}randomBytes._=_randomBytes;randomBytes.lock=function(){locked=true};randomBytes.register=function(func){if(locked){throw new Error("random is locked")}__randomBytes=func};Object.freeze(randomBytes);const rotl=(a,b)=>a<>>32-b;function XorAndSalsa(prev,pi,input,ii,out,oi){let y00=prev[pi++]^input[ii++],y01=prev[pi++]^input[ii++];let y02=prev[pi++]^input[ii++],y03=prev[pi++]^input[ii++];let y04=prev[pi++]^input[ii++],y05=prev[pi++]^input[ii++];let y06=prev[pi++]^input[ii++],y07=prev[pi++]^input[ii++];let y08=prev[pi++]^input[ii++],y09=prev[pi++]^input[ii++];let y10=prev[pi++]^input[ii++],y11=prev[pi++]^input[ii++];let y12=prev[pi++]^input[ii++],y13=prev[pi++]^input[ii++];let y14=prev[pi++]^input[ii++],y15=prev[pi++]^input[ii++];let x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let i=0;i<8;i+=2){x04^=rotl(x00+x12|0,7);x08^=rotl(x04+x00|0,9);x12^=rotl(x08+x04|0,13);x00^=rotl(x12+x08|0,18);x09^=rotl(x05+x01|0,7);x13^=rotl(x09+x05|0,9);x01^=rotl(x13+x09|0,13);x05^=rotl(x01+x13|0,18);x14^=rotl(x10+x06|0,7);x02^=rotl(x14+x10|0,9);x06^=rotl(x02+x14|0,13);x10^=rotl(x06+x02|0,18);x03^=rotl(x15+x11|0,7);x07^=rotl(x03+x15|0,9);x11^=rotl(x07+x03|0,13);x15^=rotl(x11+x07|0,18);x01^=rotl(x00+x03|0,7);x02^=rotl(x01+x00|0,9);x03^=rotl(x02+x01|0,13);x00^=rotl(x03+x02|0,18);x06^=rotl(x05+x04|0,7);x07^=rotl(x06+x05|0,9);x04^=rotl(x07+x06|0,13);x05^=rotl(x04+x07|0,18);x11^=rotl(x10+x09|0,7);x08^=rotl(x11+x10|0,9);x09^=rotl(x08+x11|0,13);x10^=rotl(x09+x08|0,18);x12^=rotl(x15+x14|0,7);x13^=rotl(x12+x15|0,9);x14^=rotl(x13+x12|0,13);x15^=rotl(x14+x13|0,18)}out[oi++]=y00+x00|0;out[oi++]=y01+x01|0;out[oi++]=y02+x02|0;out[oi++]=y03+x03|0;out[oi++]=y04+x04|0;out[oi++]=y05+x05|0;out[oi++]=y06+x06|0;out[oi++]=y07+x07|0;out[oi++]=y08+x08|0;out[oi++]=y09+x09|0;out[oi++]=y10+x10|0;out[oi++]=y11+x11|0;out[oi++]=y12+x12|0;out[oi++]=y13+x13|0;out[oi++]=y14+x14|0;out[oi++]=y15+x15|0}function BlockMix(input,ii,out,oi,r){let head=oi+0;let tail=oi+16*r;for(let i=0;i<16;i++)out[tail+i]=input[ii+(2*r-1)*16+i];for(let i=0;i0)tail+=16;XorAndSalsa(out,head,input,ii+=16,out,tail)}}function scryptInit(password,salt,_opts){const opts=checkOpts({dkLen:32,asyncTick:10,maxmem:1024**3+1024},_opts);const{N,r,p,dkLen,asyncTick,maxmem,onProgress}=opts;assert.number(N);assert.number(r);assert.number(p);assert.number(dkLen);assert.number(asyncTick);assert.number(maxmem);if(onProgress!==undefined&&typeof onProgress!=="function")throw new Error("progressCb should be function");const blockSize=128*r;const blockSize32=blockSize/4;if(N<=1||(N&N-1)!==0||N>=2**(blockSize/8)||N>2**32){throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32")}if(p<0||p>(2**32-1)*32/blockSize){throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)")}if(dkLen<0||dkLen>(2**32-1)*32){throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32")}const memUsed=blockSize*(N+p);if(memUsed>maxmem){throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`)}const B=pbkdf2$1(sha256$1,password,salt,{c:1,dkLen:blockSize*p});const B32=u32(B);const V=u32(new Uint8Array(blockSize*N));const tmp=u32(new Uint8Array(blockSize));let blockMixCb=()=>{};if(onProgress){const totalBlockMix=2*N*p;const callbackPer=Math.max(Math.floor(totalBlockMix/1e4),1);let blockMixCnt=0;blockMixCb=()=>{blockMixCnt++;if(onProgress&&(!(blockMixCnt%callbackPer)||blockMixCnt===totalBlockMix))onProgress(blockMixCnt/totalBlockMix)}}return{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb,asyncTick:asyncTick}}function scryptOutput(password,dkLen,B,V,tmp){const res=pbkdf2$1(sha256$1,password,B,{c:1,dkLen:dkLen});B.fill(0);V.fill(0);tmp.fill(0);return res}function scrypt$1(password,salt,opts){const{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb}=scryptInit(password,salt,opts);for(let pi=0;pi{BlockMix(V,pos,V,pos+=blockSize32,r);blockMixCb()});BlockMix(V,(N-1)*blockSize32,B32,Pi,r);blockMixCb();await asyncLoop(N,asyncTick,i=>{const j=B32[Pi+blockSize32-16]%N;for(let k=0;kp.z));return points.map((p,i)=>p.toAffine(toInv[i]))}static normalizeZ(points){return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine)}equals(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected");const{x:X1,y:Y1,z:Z1}=this;const{x:X2,y:Y2,z:Z2}=other;const Z1Z1=mod(Z1**_2n);const Z2Z2=mod(Z2**_2n);const U1=mod(X1*Z2Z2);const U2=mod(X2*Z1Z1);const S1=mod(mod(Y1*Z2)*Z2Z2);const S2=mod(mod(Y2*Z1)*Z1Z1);return U1===U2&&S1===S2}negate(){return new JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:X1,y:Y1,z:Z1}=this;const A=mod(X1**_2n);const B=mod(Y1**_2n);const C=mod(B**_2n);const D=mod(_2n*(mod((X1+B)**_2n)-A-C));const E=mod(_3n*A);const F=mod(E**_2n);const X3=mod(F-_2n*D);const Y3=mod(E*(D-X3)-_8n*C);const Z3=mod(_2n*Y1*Z1);return new JacobianPoint(X3,Y3,Z3)}add(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected");const{x:X1,y:Y1,z:Z1}=this;const{x:X2,y:Y2,z:Z2}=other;if(X2===_0n||Y2===_0n)return this;if(X1===_0n||Y1===_0n)return other;const Z1Z1=mod(Z1**_2n);const Z2Z2=mod(Z2**_2n);const U1=mod(X1*Z2Z2);const U2=mod(X2*Z1Z1);const S1=mod(mod(Y1*Z2)*Z2Z2);const S2=mod(mod(Y2*Z1)*Z1Z1);const H=mod(U2-U1);const r=mod(S2-S1);if(H===_0n){if(r===_0n){return this.double()}else{return JacobianPoint.ZERO}}const HH=mod(H**_2n);const HHH=mod(H*HH);const V=mod(U1*HH);const X3=mod(r**_2n-HHH-_2n*V);const Y3=mod(r*(V-X3)-S1*HHH);const Z3=mod(Z1*Z2*H);return new JacobianPoint(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}multiplyUnsafe(scalar){const P0=JacobianPoint.ZERO;if(typeof scalar==="bigint"&&scalar===_0n)return P0;let n=normalizeScalar(scalar);if(n===_1n)return this;if(!USE_ENDOMORPHISM){let p=P0;let d=this;while(n>_0n){if(n&_1n)p=p.add(d);d=d.double();n>>=_1n}return p}let{k1neg,k1,k2neg,k2}=splitScalarEndo(n);let k1p=P0;let k2p=P0;let d=this;while(k1>_0n||k2>_0n){if(k1&_1n)k1p=k1p.add(d);if(k2&_1n)k2p=k2p.add(d);d=d.double();k1>>=_1n;k2>>=_1n}if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new JacobianPoint(mod(k2p.x*CURVE.beta),k2p.y,k2p.z);return k1p.add(k2p)}precomputeWindow(W){const windows=USE_ENDOMORPHISM?128/W+1:256/W+1;const points=[];let p=this;let base=p;for(let window=0;window>=shiftBy;if(wbits>windowSize){wbits-=maxNumber;n+=_1n}if(wbits===0){let pr=precomputes[offset];if(window%2)pr=pr.negate();f=f.add(pr)}else{let cached=precomputes[offset+Math.abs(wbits)-1];if(wbits<0)cached=cached.negate();p=p.add(cached)}}return{p:p,f:f}}multiply(scalar,affinePoint){let n=normalizeScalar(scalar);let point;let fake;if(USE_ENDOMORPHISM){const{k1neg,k1,k2neg,k2}=splitScalarEndo(n);let{p:k1p,f:f1p}=this.wNAF(k1,affinePoint);let{p:k2p,f:f2p}=this.wNAF(k2,affinePoint);if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new JacobianPoint(mod(k2p.x*CURVE.beta),k2p.y,k2p.z);point=k1p.add(k2p);fake=f1p.add(f2p)}else{const{p,f}=this.wNAF(n,affinePoint);point=p;fake=f}return JacobianPoint.normalizeZ([point,fake])[0]}toAffine(invZ=invert(this.z)){const{x,y,z}=this;const iz1=invZ;const iz2=mod(iz1*iz1);const iz3=mod(iz2*iz1);const ax=mod(x*iz2);const ay=mod(y*iz3);const zz=mod(z*iz1);if(zz!==_1n)throw new Error("invZ was invalid");return new Point(ax,ay)}}JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n);JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);const pointPrecomputes=new WeakMap;class Point{constructor(x,y){this.x=x;this.y=y}_setWindowSize(windowSize){this._WINDOW_SIZE=windowSize;pointPrecomputes.delete(this)}static fromCompressedHex(bytes){const isShort=bytes.length===32;const x=bytesToNumber(isShort?bytes:bytes.subarray(1));if(!isValidFieldElement(x))throw new Error("Point is not on curve");const y2=weistrass(x);let y=sqrtMod(y2);const isYOdd=(y&_1n)===_1n;if(isShort){if(isYOdd)y=mod(-y)}else{const isFirstByteOdd=(bytes[0]&1)===1;if(isFirstByteOdd!==isYOdd)y=mod(-y)}const point=new Point(x,y);point.assertValidity();return point}static fromUncompressedHex(bytes){const x=bytesToNumber(bytes.subarray(1,33));const y=bytesToNumber(bytes.subarray(33,65));const point=new Point(x,y);point.assertValidity();return point}static fromHex(hex){const bytes=ensureBytes(hex);const len=bytes.length;const header=bytes[0];if(len===32||len===33&&(header===2||header===3)){return this.fromCompressedHex(bytes)}if(len===65&&header===4)return this.fromUncompressedHex(bytes);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`)}static fromPrivateKey(privateKey){return Point.BASE.multiply(normalizePrivateKey(privateKey))}static fromSignature(msgHash,signature,recovery){msgHash=ensureBytes(msgHash);const h=truncateHash(msgHash);const{r,s}=normalizeSignature(signature);if(recovery!==0&&recovery!==1){throw new Error("Cannot recover signature: invalid recovery bit")}const prefix=recovery&1?"03":"02";const R=Point.fromHex(prefix+numTo32bStr(r));const{n}=CURVE;const rinv=invert(r,n);const u1=mod(-h*rinv,n);const u2=mod(s*rinv,n);const Q=Point.BASE.multiplyAndAddUnsafe(R,u1,u2);if(!Q)throw new Error("Cannot recover signature: point at infinify");Q.assertValidity();return Q}toRawBytes(isCompressed=false){return hexToBytes(this.toHex(isCompressed))}toHex(isCompressed=false){const x=numTo32bStr(this.x);if(isCompressed){const prefix=this.y&_1n?"03":"02";return`${prefix}${x}`}else{return`04${x}${numTo32bStr(this.y)}`}}toHexX(){return this.toHex(true).slice(2)}toRawX(){return this.toRawBytes(true).slice(1)}assertValidity(){const msg="Point is not on elliptic curve";const{x,y}=this;if(!isValidFieldElement(x)||!isValidFieldElement(y))throw new Error(msg);const left=mod(y*y);const right=weistrass(x);if(mod(left-right)!==_0n)throw new Error(msg)}equals(other){return this.x===other.x&&this.y===other.y}negate(){return new Point(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(other){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine()}subtract(other){return this.add(other.negate())}multiply(scalar){return JacobianPoint.fromAffine(this).multiply(scalar,this).toAffine()}multiplyAndAddUnsafe(Q,a,b){const P=JacobianPoint.fromAffine(this);const aP=a===_0n||a===_1n||this!==Point.BASE?P.multiplyUnsafe(a):P.multiply(a);const bQ=JacobianPoint.fromAffine(Q).multiplyUnsafe(b);const sum=aP.add(bQ);return sum.equals(JacobianPoint.ZERO)?undefined:sum.toAffine()}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy);Point.ZERO=new Point(_0n,_0n);function sliceDER(s){return Number.parseInt(s[0],16)>=8?"00"+s:s}function parseDERInt(data){if(data.length<2||data[0]!==2){throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`)}const len=data[1];const res=data.subarray(2,len+2);if(!len||res.length!==len){throw new Error(`Invalid signature integer: wrong length`)}if(res[0]===0&&res[1]<=127){throw new Error("Invalid signature integer: trailing length")}return{data:bytesToNumber(res),left:data.subarray(len+2)}}function parseDERSignature(data){if(data.length<2||data[0]!=48){throw new Error(`Invalid signature tag: ${bytesToHex(data)}`)}if(data[1]!==data.length-2){throw new Error("Invalid signature: incorrect length")}const{data:r,left:sBytes}=parseDERInt(data.subarray(2));const{data:s,left:rBytesLeft}=parseDERInt(sBytes);if(rBytesLeft.length){throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`)}return{r:r,s:s}}class Signature$1{constructor(r,s){this.r=r;this.s=s;this.assertValidity()}static fromCompact(hex){const arr=isUint8a(hex);const name="Signature.fromCompact";if(typeof hex!=="string"&&!arr)throw new TypeError(`${name}: Expected string or Uint8Array`);const str=arr?bytesToHex(hex):hex;if(str.length!==128)throw new Error(`${name}: Expected 64-byte hex`);return new Signature$1(hexToNumber(str.slice(0,64)),hexToNumber(str.slice(64,128)))}static fromDER(hex){const arr=isUint8a(hex);if(typeof hex!=="string"&&!arr)throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);const{r,s}=parseDERSignature(arr?hex:hexToBytes(hex));return new Signature$1(r,s)}static fromHex(hex){return this.fromDER(hex)}assertValidity(){const{r,s}=this;if(!isWithinCurveOrder(r))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(s))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const HALF=CURVE.n>>_1n;return this.s>HALF}normalizeS(){return this.hasHighS()?new Signature$1(this.r,CURVE.n-this.s):this}toDERRawBytes(isCompressed=false){return hexToBytes(this.toDERHex(isCompressed))}toDERHex(isCompressed=false){const sHex=sliceDER(numberToHexUnpadded(this.s));if(isCompressed)return sHex;const rHex=sliceDER(numberToHexUnpadded(this.r));const rLen=numberToHexUnpadded(rHex.length/2);const sLen=numberToHexUnpadded(sHex.length/2);const length=numberToHexUnpadded(rHex.length/2+sHex.length/2+4);return`30${length}02${rLen}${rHex}02${sLen}${sHex}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}}function concatBytes(...arrays){if(!arrays.every(isUint8a))throw new Error("Uint8Array list expected");if(arrays.length===1)return arrays[0];const length=arrays.reduce((a,arr)=>a+arr.length,0);const result=new Uint8Array(length);for(let i=0,pad=0;ii.toString(16).padStart(2,"0"));function bytesToHex(uint8a){if(!(uint8a instanceof Uint8Array))throw new Error("Expected Uint8Array");let hex="";for(let i=0;iPOW_2_256)throw new Error("Expected number < 2^256");return num.toString(16).padStart(64,"0")}function numTo32b(num){return hexToBytes(numTo32bStr(num))}function numberToHexUnpadded(num){const hex=num.toString(16);return hex.length&1?`0${hex}`:hex}function hexToNumber(hex){if(typeof hex!=="string"){throw new TypeError("hexToNumber: expected string, got "+typeof hex)}return BigInt(`0x${hex}`)}function hexToBytes(hex){if(typeof hex!=="string"){throw new TypeError("hexToBytes: expected string, got "+typeof hex)}if(hex.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+hex.length);const array=new Uint8Array(hex.length/2);for(let i=0;i0)return BigInt(num);if(typeof num==="bigint"&&isWithinCurveOrder(num))return num;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(a,b=CURVE.P){const result=a%b;return result>=_0n?result:b+result}function pow2(x,power){const{P}=CURVE;let res=x;while(power-- >_0n){res*=res;res%=P}return res}function sqrtMod(x){const{P}=CURVE;const _6n=BigInt(6);const _11n=BigInt(11);const _22n=BigInt(22);const _23n=BigInt(23);const _44n=BigInt(44);const _88n=BigInt(88);const b2=x*x*x%P;const b3=b2*b2*x%P;const b6=pow2(b3,_3n)*b3%P;const b9=pow2(b6,_3n)*b3%P;const b11=pow2(b9,_2n)*b2%P;const b22=pow2(b11,_11n)*b11%P;const b44=pow2(b22,_22n)*b22%P;const b88=pow2(b44,_44n)*b44%P;const b176=pow2(b88,_88n)*b88%P;const b220=pow2(b176,_44n)*b44%P;const b223=pow2(b220,_3n)*b3%P;const t1=pow2(b223,_23n)*b22%P;const t2=pow2(t1,_6n)*b2%P;return pow2(t2,_2n)}function invert(number,modulo=CURVE.P){if(number===_0n||modulo<=_0n){throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`)}let a=mod(number,modulo);let b=modulo;let x=_0n,y=_1n,u=_1n,v=_0n;while(a!==_0n){const q=b/a;const r=b%a;const m=x-u*q;const n=y-v*q;b=a,a=r,x=u,y=v,u=m,v=n}const gcd=b;if(gcd!==_1n)throw new Error("invert: does not exist");return mod(x,modulo)}function invertBatch(nums,p=CURVE.P){const scratch=new Array(nums.length);const lastMultiplied=nums.reduce((acc,num,i)=>{if(num===_0n)return acc;scratch[i]=acc;return mod(acc*num,p)},_1n);const inverted=invert(lastMultiplied,p);nums.reduceRight((acc,num,i)=>{if(num===_0n)return acc;scratch[i]=mod(acc*scratch[i],p);return mod(acc*num,p)},inverted);return scratch}const divNearest=(a,b)=>(a+b/_2n)/b;const POW_2_128=_2n**BigInt(128);function splitScalarEndo(k){const{n}=CURVE;const a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15");const b1=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3");const a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");const b2=a1;const c1=divNearest(b2*k,n);const c2=divNearest(-b1*k,n);let k1=mod(k-c1*a1-c2*a2,n);let k2=mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128;const k2neg=k2>POW_2_128;if(k1neg)k1=n-k1;if(k2neg)k2=n-k2;if(k1>POW_2_128||k2>POW_2_128){throw new Error("splitScalarEndo: Endomorphism failed, k="+k)}return{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}}function truncateHash(hash){const{n}=CURVE;const byteLength=hash.length;const delta=byteLength*8-256;let h=bytesToNumber(hash);if(delta>0)h=h>>BigInt(delta);if(h>=n)h-=n;return h}class HmacDrbg{constructor(){this.v=new Uint8Array(32).fill(1);this.k=new Uint8Array(32).fill(0);this.counter=0}hmac(...values){return utils.hmacSha256(this.k,...values)}hmacSync(...values){if(typeof utils.hmacSha256Sync!=="function")throw new Error("utils.hmacSha256Sync is undefined, you need to set it");const res=utils.hmacSha256Sync(this.k,...values);if(res instanceof Promise)throw new Error("To use sync sign(), ensure utils.hmacSha256 is sync");return res}incr(){if(this.counter>=1e3){throw new Error("Tried 1,000 k values for sign(), all were invalid")}this.counter+=1}async reseed(seed=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),seed);this.v=await this.hmac(this.v);if(seed.length===0)return;this.k=await this.hmac(this.v,Uint8Array.from([1]),seed);this.v=await this.hmac(this.v)}reseedSync(seed=new Uint8Array){this.k=this.hmacSync(this.v,Uint8Array.from([0]),seed);this.v=this.hmacSync(this.v);if(seed.length===0)return;this.k=this.hmacSync(this.v,Uint8Array.from([1]),seed);this.v=this.hmacSync(this.v)}async generate(){this.incr();this.v=await this.hmac(this.v);return this.v}generateSync(){this.incr();this.v=this.hmacSync(this.v);return this.v}}function isWithinCurveOrder(num){return _0n0){num=BigInt(key)}else if(typeof key==="string"){if(key.length!==64)throw new Error("Expected 32 bytes of private key");num=hexToNumber(key)}else if(isUint8a(key)){if(key.length!==32)throw new Error("Expected 32 bytes of private key");num=bytesToNumber(key)}else{throw new TypeError("Expected valid private key")}if(!isWithinCurveOrder(num))throw new Error("Expected private key: 0 < key < n");return num}function normalizePublicKey(publicKey){if(publicKey instanceof Point){publicKey.assertValidity();return publicKey}else{return Point.fromHex(publicKey)}}function normalizeSignature(signature){if(signature instanceof Signature$1){signature.assertValidity();return signature}try{return Signature$1.fromDER(signature)}catch(error){return Signature$1.fromCompact(signature)}}function getPublicKey(privateKey,isCompressed=false){return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed)}function recoverPublicKey(msgHash,signature,recovery,isCompressed=false){return Point.fromSignature(msgHash,signature,recovery).toRawBytes(isCompressed)}function isPub(item){const arr=isUint8a(item);const str=typeof item==="string";const len=(arr||str)&&item.length;if(arr)return len===33||len===65;if(str)return len===66||len===130;if(item instanceof Point)return true;return false}function getSharedSecret(privateA,publicB,isCompressed=false){if(isPub(privateA))throw new TypeError("getSharedSecret: first arg must be private key");if(!isPub(publicB))throw new TypeError("getSharedSecret: second arg must be public key");const b=normalizePublicKey(publicB);b.assertValidity();return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed)}function bits2int(bytes){const slice=bytes.length>32?bytes.slice(0,32):bytes;return bytesToNumber(slice)}function bits2octets(bytes){const z1=bits2int(bytes);const z2=mod(z1,CURVE.n);return int2octets(z2<_0n?z1:z2)}function int2octets(num){if(typeof num!=="bigint")throw new Error("Expected bigint");const hex=numTo32bStr(num);return hexToBytes(hex)}function initSigArgs(msgHash,privateKey,extraEntropy){if(msgHash==null)throw new Error(`sign: expected valid message hash, not "${msgHash}"`);const h1=ensureBytes(msgHash);const d=normalizePrivateKey(privateKey);const seedArgs=[int2octets(d),bits2octets(h1)];if(extraEntropy!=null){if(extraEntropy===true)extraEntropy=utils.randomBytes(32);const e=ensureBytes(extraEntropy);if(e.length!==32)throw new Error("sign: Expected 32 bytes of extra data");seedArgs.push(e)}const seed=concatBytes(...seedArgs);const m=bits2int(h1);return{seed:seed,m:m,d:d}}function finalizeSig(recSig,opts){let{sig,recovery}=recSig;const{canonical,der,recovered}=Object.assign({canonical:true,der:true},opts);if(canonical&&sig.hasHighS()){sig=sig.normalizeS();recovery^=1}const hashed=der?sig.toDERRawBytes():sig.toCompactRawBytes();return recovered?[hashed,recovery]:hashed}async function sign(msgHash,privKey,opts={}){const{seed,m,d}=initSigArgs(msgHash,privKey,opts.extraEntropy);let sig;const drbg=new HmacDrbg;await drbg.reseed(seed);while(!(sig=kmdToSig(await drbg.generate(),m,d)))await drbg.reseed();return finalizeSig(sig,opts)}function signSync(msgHash,privKey,opts={}){const{seed,m,d}=initSigArgs(msgHash,privKey,opts.extraEntropy);let sig;const drbg=new HmacDrbg;drbg.reseedSync(seed);while(!(sig=kmdToSig(drbg.generateSync(),m,d)))drbg.reseedSync();return finalizeSig(sig,opts)}const vopts={strict:true};function verify(signature,msgHash,publicKey,opts=vopts){let sig;try{sig=normalizeSignature(signature);msgHash=ensureBytes(msgHash)}catch(error){return false}const{r,s}=sig;if(opts.strict&&sig.hasHighS())return false;const h=truncateHash(msgHash);let P;try{P=normalizePublicKey(publicKey)}catch(error){return false}const{n}=CURVE;const sinv=invert(s,n);const u1=mod(h*sinv,n);const u2=mod(r*sinv,n);const R=Point.BASE.multiplyAndAddUnsafe(P,u1,u2);if(!R)return false;const v=mod(R.x,n);return v===r}function finalizeSchnorrChallenge(ch){return mod(bytesToNumber(ch),CURVE.n)}function hasEvenY(point){return(point.y&_1n)===_0n}class SchnorrSignature{constructor(r,s){this.r=r;this.s=s;this.assertValidity()}static fromHex(hex){const bytes=ensureBytes(hex);if(bytes.length!==64)throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);const r=bytesToNumber(bytes.subarray(0,32));const s=bytesToNumber(bytes.subarray(32,64));return new SchnorrSignature(r,s)}assertValidity(){const{r,s}=this;if(!isValidFieldElement(r)||!isWithinCurveOrder(s))throw new Error("Invalid signature")}toHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}toRawBytes(){return hexToBytes(this.toHex())}}function schnorrGetPublicKey(privateKey){return Point.fromPrivateKey(privateKey).toRawX()}function initSchnorrSigArgs(message,privateKey,auxRand){if(message==null)throw new TypeError(`sign: Expected valid message, not "${message}"`);const m=ensureBytes(message);const d0=normalizePrivateKey(privateKey);const rand=ensureBytes(auxRand);if(rand.length!==32)throw new TypeError("sign: Expected 32 bytes of aux randomness");const P=Point.fromPrivateKey(d0);const px=P.toRawX();const d=hasEvenY(P)?d0:CURVE.n-d0;return{m:m,P:P,px:px,d:d,rand:rand}}function initSchnorrNonce(d,t0h){return numTo32b(d^bytesToNumber(t0h))}function finalizeSchnorrNonce(k0h){const k0=mod(bytesToNumber(k0h),CURVE.n);if(k0===_0n)throw new Error("sign: Creation of signature failed. k is zero");const R=Point.fromPrivateKey(k0);const rx=R.toRawX();const k=hasEvenY(R)?k0:CURVE.n-k0;return{R:R,rx:rx,k:k}}function finalizeSchnorrSig(R,k,e,d){return new SchnorrSignature(R.x,mod(k+e*d,CURVE.n)).toRawBytes()}async function schnorrSign(message,privateKey,auxRand=utils.randomBytes()){const{m,px,d,rand}=initSchnorrSigArgs(message,privateKey,auxRand);const t=initSchnorrNonce(d,await utils.taggedHash(TAGS.aux,rand));const{R,rx,k}=finalizeSchnorrNonce(await utils.taggedHash(TAGS.nonce,t,px,m));const e=finalizeSchnorrChallenge(await utils.taggedHash(TAGS.challenge,rx,px,m));const sig=finalizeSchnorrSig(R,k,e,d);const isValid=await schnorrVerify(sig,m,px);if(!isValid)throw new Error("sign: Invalid signature produced");return sig}function schnorrSignSync(message,privateKey,auxRand=utils.randomBytes()){const{m,px,d,rand}=initSchnorrSigArgs(message,privateKey,auxRand);const t=initSchnorrNonce(d,utils.taggedHashSync(TAGS.aux,rand));const{R,rx,k}=finalizeSchnorrNonce(utils.taggedHashSync(TAGS.nonce,t,px,m));const e=finalizeSchnorrChallenge(utils.taggedHashSync(TAGS.challenge,rx,px,m));const sig=finalizeSchnorrSig(R,k,e,d);const isValid=schnorrVerifySync(sig,m,px);if(!isValid)throw new Error("sign: Invalid signature produced");return sig}function initSchnorrVerify(signature,message,publicKey){const raw=signature instanceof SchnorrSignature;const sig=raw?signature:SchnorrSignature.fromHex(signature);if(raw)sig.assertValidity();return{...sig,m:ensureBytes(message),P:normalizePublicKey(publicKey)}}function finalizeSchnorrVerify(r,P,s,e){const R=Point.BASE.multiplyAndAddUnsafe(P,normalizePrivateKey(s),mod(-e,CURVE.n));if(!R||!hasEvenY(R)||R.x!==r)return false;return true}async function schnorrVerify(signature,message,publicKey){try{const{r,s,m,P}=initSchnorrVerify(signature,message,publicKey);const e=finalizeSchnorrChallenge(await utils.taggedHash(TAGS.challenge,numTo32b(r),P.toRawX(),m));return finalizeSchnorrVerify(r,P,s,e)}catch(error){return false}}function schnorrVerifySync(signature,message,publicKey){try{const{r,s,m,P}=initSchnorrVerify(signature,message,publicKey);const e=finalizeSchnorrChallenge(utils.taggedHashSync(TAGS.challenge,numTo32b(r),P.toRawX(),m));return finalizeSchnorrVerify(r,P,s,e)}catch(error){return false}}const schnorr={Signature:SchnorrSignature,getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,signSync:schnorrSignSync,verifySync:schnorrVerifySync};Point.BASE._setWindowSize(8);const crypto={node:nodeCrypto,web:typeof self==="object"&&"crypto"in self?self.crypto:undefined};const TAGS={challenge:"BIP0340/challenge",aux:"BIP0340/aux",nonce:"BIP0340/nonce"};const TAGGED_HASH_PREFIXES={};const utils={isValidPrivateKey(privateKey){try{normalizePrivateKey(privateKey);return true}catch(error){return false}},privateAdd:(privateKey,tweak)=>{const p=normalizePrivateKey(privateKey);const t=normalizePrivateKey(tweak);return numTo32b(mod(p+t,CURVE.n))},privateNegate:privateKey=>{const p=normalizePrivateKey(privateKey);return numTo32b(CURVE.n-p)},pointAddScalar:(p,tweak,isCompressed)=>{const P=Point.fromHex(p);const t=normalizePrivateKey(tweak);const Q=Point.BASE.multiplyAndAddUnsafe(P,t,_1n);if(!Q)throw new Error("Tweaked point at infinity");return Q.toRawBytes(isCompressed)},pointMultiply:(p,tweak,isCompressed)=>{const P=Point.fromHex(p);const t=bytesToNumber(ensureBytes(tweak));return P.multiply(t).toRawBytes(isCompressed)},hashToPrivateKey:hash=>{hash=ensureBytes(hash);if(hash.length<40||hash.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");const num=mod(bytesToNumber(hash),CURVE.n-_1n)+_1n;return numTo32b(num)},randomBytes:(bytesLength=32)=>{if(crypto.web){return crypto.web.getRandomValues(new Uint8Array(bytesLength))}else if(crypto.node){const{randomBytes}=crypto.node;return Uint8Array.from(randomBytes(bytesLength))}else{throw new Error("The environment doesn't have randomBytes function")}},randomPrivateKey:()=>{return utils.hashToPrivateKey(utils.randomBytes(40))},bytesToHex:bytesToHex,hexToBytes:hexToBytes,concatBytes:concatBytes,mod:mod,invert:invert,sha256:async(...messages)=>{if(crypto.web){const buffer=await crypto.web.subtle.digest("SHA-256",concatBytes(...messages));return new Uint8Array(buffer)}else if(crypto.node){const{createHash}=crypto.node;const hash=createHash("sha256");messages.forEach(m=>hash.update(m));return Uint8Array.from(hash.digest())}else{throw new Error("The environment doesn't have sha256 function")}},hmacSha256:async(key,...messages)=>{if(crypto.web){const ckey=await crypto.web.subtle.importKey("raw",key,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);const message=concatBytes(...messages);const buffer=await crypto.web.subtle.sign("HMAC",ckey,message);return new Uint8Array(buffer)}else if(crypto.node){const{createHmac}=crypto.node;const hash=createHmac("sha256",key);messages.forEach(m=>hash.update(m));return Uint8Array.from(hash.digest())}else{throw new Error("The environment doesn't have hmac-sha256 function")}},sha256Sync:undefined,hmacSha256Sync:undefined,taggedHash:async(tag,...messages)=>{let tagP=TAGGED_HASH_PREFIXES[tag];if(tagP===undefined){const tagH=await utils.sha256(Uint8Array.from(tag,c=>c.charCodeAt(0)));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag]=tagP}return utils.sha256(tagP,...messages)},taggedHashSync:(tag,...messages)=>{if(typeof utils.sha256Sync!=="function")throw new Error("utils.sha256Sync is undefined, you need to set it");let tagP=TAGGED_HASH_PREFIXES[tag];if(tagP===undefined){const tagH=utils.sha256Sync(Uint8Array.from(tag,c=>c.charCodeAt(0)));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag]=tagP}return utils.sha256Sync(tagP,...messages)},precompute(windowSize=8,point=Point.BASE){const cached=point===Point.BASE?point:new Point(point.x,point.y);cached._setWindowSize(windowSize);cached.multiply(_3n);return cached}};const ZeroAddress="0x0000000000000000000000000000000000000000";const ZeroHash="0x0000000000000000000000000000000000000000000000000000000000000000";const NegativeOne=BigInt(-1);const Zero=BigInt(0);const One=BigInt(1);const Two=BigInt(2);const N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const WeiPerEther=BigInt("1000000000000000000");const MaxUint256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const MinInt256=BigInt("0x8000000000000000000000000000000000000000000000000000000000000000")*NegativeOne;const MaxInt256=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const EtherSymbol="Ξ";const MessagePrefix="Ethereum Signed Message:\n";const BN_0$2=BigInt(0);const BN_1$3=BigInt(1);const BN_2$3=BigInt(2);const BN_27$1=BigInt(27);const BN_28$1=BigInt(28);const BN_35$1=BigInt(35);const _guard$2={};class Signature{#props;get r(){return getStore(this.#props,"r")}set r(value){if(dataLength(value)!==32){logger.throwArgumentError("invalid r","value",value)}setStore(this.#props,"r",hexlify(value))}get s(){return getStore(this.#props,"s")}set s(value){if(dataLength(value)!==32){logger.throwArgumentError("invalid r","value",value)}else if(logger.getBytes(value)[0]&128){logger.throwArgumentError("non-canonical s","value",value)}setStore(this.#props,"s",hexlify(value))}get v(){return getStore(this.#props,"v")}set v(value){const v=logger.getNumber(value,"value");if(v!==27&&v!==28){throw new Error("@TODO")}setStore(this.#props,"v",v)}get networkV(){return getStore(this.#props,"networkV")}get legacyChainId(){const v=this.networkV;if(v==null){return null}return Signature.getChainId(v)}get yParity(){if(this.v===27){return 0}return 1}get yParityAndS(){const yParityAndS=logger.getBytes(this.s);if(this.yParity){yParityAndS[0]|=128}return hexlify(yParityAndS)}get compactSerialized(){return concat([this.r,this.yParityAndS])}get serialized(){return concat([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(guard,r,s,v){logger.assertPrivate(guard,_guard$2,"Signature");this.#props={r:r,s:s,v:v,networkV:null}}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const clone=new Signature(_guard$2,this.r,this.s,this.v);if(this.networkV){setStore(clone.#props,"networkV",this.networkV)}return clone}freeze(){Object.freeze(this.#props);return this}isFrozen(){return Object.isFrozen(this.#props)}toJSON(){const networkV=this.networkV;return{_type:"signature",networkV:networkV!=null?networkV.toString():null,r:this.r,s:this.s,v:this.v}}static create(){return new Signature(_guard$2,ZeroHash,ZeroHash,27)}static getChainId(v){const bv=logger.getBigInt(v,"v");if(bv==BN_27$1||bv==BN_28$1){return BN_0$2}if(bv{return logger.throwArgumentError(message,"signature",sig)};if(typeof sig==="string"){const bytes=logger.getBytes(sig,"signature");if(bytes.length===64){const r=hexlify(bytes.slice(0,32));const s=bytes.slice(32,64);const v=s[0]&128?28:27;s[0]&=127;return new Signature(_guard$2,r,hexlify(s),v)}if(dataLength(sig)!==65){const r=hexlify(sig.slice(0,32));const s=bytes.slice(32,64);if(s[0]&128){throwError("non-canonical s")}const v=Signature.getNormalizedV(bytes[64]);return new Signature(_guard$2,r,hexlify(s),v)}return throwError("invlaid raw signature length")}if(sig instanceof Signature){return sig.clone()}const r=sig.r;if(r==null){throwError("missing r")}if(!isHexString(r,32)){throwError("invalid r")}const s=function(s,yParityAndS){if(s!=null){if(!isHexString(s,32)){throwError("invalid s")}return s}if(yParityAndS!=null){if(!isHexString(yParityAndS,32)){throwError("invalid yParityAndS")}const bytes=logger.getBytes(yParityAndS);bytes[0]&=127;return hexlify(bytes)}return throwError("missing s")}(sig.s,sig.yParityAndS);if(logger.getBytes(s)[0]&128){throwError("non-canonical s")}const{networkV,v}=function(_v,yParityAndS,yParity){if(_v!=null){const v=logger.getBigInt(_v);return{networkV:v>=BN_35$1?v:undefined,v:Signature.getNormalizedV(v)}}if(yParityAndS!=null){if(!isHexString(yParityAndS,32)){throwError("invalid yParityAndS")}return{v:logger.getBytes(yParityAndS)[0]&128?28:27}}if(yParity!=null){switch(yParity){case 0:return{v:27};case 1:return{v:28}}return throwError("invalid yParity")}return throwError("missing v")}(sig.v,sig.yParityAndS,sig.yParity);const result=new Signature(_guard$2,r,s,v);if(networkV){setStore(result.#props,"networkV",networkV)}if("yParity"in sig&&sig.yParity!==result.yParity){throwError("yParity mismatch")}else if("yParityAndS"in sig&&sig.yParityAndS!==result.yParityAndS){throwError("yParityAndS mismatch")}return result}}utils.hmacSha256Sync=function(key,...messages){return logger.getBytes(computeHmac("sha256",key,concat(messages)))};class SigningKey{#privateKey;constructor(privateKey){this.#privateKey=hexlify(privateKey)}get privateKey(){return this.#privateKey}get publicKey(){return SigningKey.computePublicKey(this.#privateKey)}get compressedPublicKey(){return SigningKey.computePublicKey(this.#privateKey,true)}sign(digest){const[sigDer,recid]=signSync(logger.getBytesCopy(digest),logger.getBytesCopy(this.#privateKey),{recovered:true,canonical:true});const sig=Signature$1.fromHex(sigDer);return Signature.from({r:toHex("0x"+sig.r.toString(16),32),s:toHex("0x"+sig.s.toString(16),32),v:recid?28:27}).freeze()}computeShardSecret(other){const pubKey=SigningKey.computePublicKey(other);return hexlify(getSharedSecret(logger.getBytesCopy(this.#privateKey),pubKey))}static computePublicKey(key,compressed){let bytes=logger.getBytes(key,"key");if(bytes.length===32){const pubKey=getPublicKey(bytes,!!compressed);return hexlify(pubKey)}if(bytes.length===64){const pub=new Uint8Array(65);pub[0]=4;pub.set(bytes,1);bytes=pub}const point=Point.fromHex(bytes);return hexlify(point.toRawBytes(compressed))}static recoverPublicKey(digest,signature){const sig=Signature.from(signature);const der=Signature$1.fromCompact(logger.getBytesCopy(concat([sig.r,sig.s]))).toDERRawBytes();const pubKey=recoverPublicKey(logger.getBytesCopy(digest),der,sig.yParity);if(pubKey!=null){return hexlify(pubKey)}return logger.throwArgumentError("invalid signautre for digest","signature",signature)}static _addPoints(p0,p1,compressed){const pub0=Point.fromHex(SigningKey.computePublicKey(p0).substring(2));const pub1=Point.fromHex(SigningKey.computePublicKey(p1).substring(2));return"0x"+pub0.add(pub1).toHex(!!compressed)}}function lock(){computeHmac.lock();keccak256.lock();pbkdf2.lock();randomBytes.lock();ripemd160.lock();scrypt.lock();scryptSync.lock();sha256.lock();sha512.lock()}function id(value){return keccak256(toUtf8Bytes(value))}function ens_normalize(name){return name}const Zeros=new Uint8Array(32);Zeros.fill(0);function checkComponent(comp){if(comp.length===0){throw new Error("invalid ENS name; empty component")}return comp}function ensNameSplit(name){const bytes=toUtf8Bytes(ens_normalize(name));const comps=[];if(name.length===0){return comps}let last=0;for(let i=0;i=bytes.length){throw new Error("invalid ENS name; empty component")}comps.push(checkComponent(bytes.slice(last)));return comps}function ensNormalize(name){return ensNameSplit(name).map(comp=>toUtf8String(comp)).join(".")}function isValidName(name){try{return ensNameSplit(name).length!==0}catch(error){}return false}function namehash(name){if(typeof name!=="string"){logger.throwArgumentError("invalid ENS name; not a string","name",name)}let result=Zeros;const comps=ensNameSplit(name);while(comps.length){result=keccak256(concat([result,keccak256(comps.pop())]))}return hexlify(result)}function dnsEncode(name){return hexlify(concat(ensNameSplit(name).map(comp=>{if(comp.length>63){throw new Error("invalid DNS encoded entry; length exceeds 63 bytes")}const bytes=new Uint8Array(comp.length+1);bytes.set(comp,1);bytes[0]=bytes.length-1;return bytes})))+"00"}function hashMessage(message){if(typeof message==="string"){message=toUtf8Bytes(message)}return keccak256(concat([toUtf8Bytes(MessagePrefix),toUtf8Bytes(String(message.length)),message]))}const regexBytes=new RegExp("^bytes([0-9]+)$");const regexNumber=new RegExp("^(u?int)([0-9]*)$");const regexArray=new RegExp("^(.*)\\[([0-9]*)\\]$");function _pack(type,value,isArray){switch(type){case"address":if(isArray){return logger.getBytes(zeroPadValue(value,32))}return logger.getBytes(value);case"string":return toUtf8Bytes(value);case"bytes":return logger.getBytes(value);case"bool":value=!!value?"0x01":"0x00";if(isArray){return logger.getBytes(zeroPadValue(value,32))}return logger.getBytes(value)}let match=type.match(regexNumber);if(match){let size=parseInt(match[2]||"256");if(match[2]&&String(size)!==match[2]||size%8!==0||size===0||size>256){return logger.throwArgumentError("invalid number type","type",type)}if(isArray){size=256}value=toTwos(value,size);return logger.getBytes(zeroPadValue(toArray(value),size/8))}match=type.match(regexBytes);if(match){const size=parseInt(match[1]);if(String(size)!==match[1]||size===0||size>32){return logger.throwArgumentError("invalid bytes type","type",type)}if(dataLength(value)!==size){return logger.throwArgumentError(`invalid value for ${type}`,"value",value)}if(isArray){return logger.getBytes(zeroPadBytes(value,32))}return value}match=type.match(regexArray);if(match&&Array.isArray(value)){const baseType=match[1];const count=parseInt(match[2]||String(value.length));if(count!=value.length){logger.throwArgumentError(`invalid array length for ${type}`,"value",value)}const result=[];value.forEach(function(value){result.push(_pack(baseType,value,true))});return logger.getBytes(concat(result))}return logger.throwArgumentError("invalid type","type",type)}function solidityPacked(types,values){if(types.length!=values.length){logger.throwArgumentError("wrong number of values; expected ${ types.length }","values",values)}const tight=[];types.forEach(function(type,index){tight.push(_pack(type,values[index]))});return hexlify(concat(tight))}function solidityPackedKeccak256(types,values){return keccak256(solidityPacked(types,values))}function test(foo){}function solidityPackedSha256(types,values){return sha256(solidityPacked(types,values))}const padding=new Uint8Array(32);padding.fill(0);const BN__1=BigInt(-1);const BN_0$1=BigInt(0);const BN_1$2=BigInt(1);const BN_MAX_UINT256$1=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function hexPadRight(value){const bytes=logger.getBytes(value);const padOffset=bytes.length%32;if(padOffset){return concat([bytes,padding.slice(padOffset)])}return hexlify(bytes)}const hexTrue=toHex(BN_1$2,32);const hexFalse=toHex(BN_0$1,32);const domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"};const domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(key){return function(value){if(typeof value!=="string"){logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`,`domain.${key}`,value)}return value}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(value){return logger.getBigInt(value,"domain.chainId")},verifyingContract:function(value){try{return getAddress(value).toLowerCase()}catch(error){}return logger.throwArgumentError(`invalid domain value "verifyingContract"`,"domain.verifyingContract",value)},salt:function(value){const bytes=logger.getBytes(value,"domain.salt");if(bytes.length!==32){logger.throwArgumentError(`invalid domain value "salt"`,"domain.salt",value)}return hexlify(bytes)}};function getBaseEncoder(type){{const match=type.match(/^(u?)int(\d*)$/);if(match){const signed=match[1]==="";const width=parseInt(match[2]||"256");if(width%8!==0||width>256||match[2]&&match[2]!==String(width)){logger.throwArgumentError("invalid numeric width","type",type)}const boundsUpper=mask(BN_MAX_UINT256$1,signed?width-1:width);const boundsLower=signed?(boundsUpper+BN_1$2)*BN__1:BN_0$1;return function(_value){const value=logger.getBigInt(_value,"value");if(valueboundsUpper){logger.throwArgumentError(`value out-of-bounds for ${type}`,"value",value)}return toHex(toTwos(value,256),32)}}}{const match=type.match(/^bytes(\d+)$/);if(match){const width=parseInt(match[1]);if(width===0||width>32||match[1]!==String(width)){logger.throwArgumentError("invalid bytes width","type",type)}return function(value){const bytes=logger.getBytes(value);if(bytes.length!==width){logger.throwArgumentError(`invalid length for ${type}`,"value",value)}return hexPadRight(value)}}}switch(type){case"address":return function(value){return zeroPadValue(getAddress(value),32)};case"bool":return function(value){return!value?hexFalse:hexTrue};case"bytes":return function(value){return keccak256(value)};case"string":return function(value){return id(value)}}return null}function encodeType(name,fields){return`${name}(${fields.map(({name,type})=>type+" "+name).join(",")})`}class TypedDataEncoder{primaryType;#types;get types(){return JSON.parse(this.#types)}#fullTypes;#encoderCache;constructor(types){this.#types=JSON.stringify(types);this.#fullTypes=new Map;this.#encoderCache=new Map;const links=new Map;const parents=new Map;const subtypes=new Map;Object.keys(types).forEach(type=>{links.set(type,new Set);parents.set(type,[]);subtypes.set(type,new Set)});for(const name in types){const uniqueNames=new Set;for(const field of types[name]){if(uniqueNames.has(field.name)){logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`,"types",types)}uniqueNames.add(field.name);const baseType=field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]||null;if(baseType===name){logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`,"types",types)}const encoder=getBaseEncoder(baseType);if(encoder){continue}if(!parents.has(baseType)){logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`,"types",types)}parents.get(baseType).push(name);links.get(name).add(baseType)}}const primaryTypes=Array.from(parents.keys()).filter(n=>parents.get(n).length===0);if(primaryTypes.length===0){logger.throwArgumentError("missing primary type","types",types)}else if(primaryTypes.length>1){logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map(t=>JSON.stringify(t)).join(", ")}`,"types",types)}defineProperties(this,{primaryType:primaryTypes[0]});function checkCircular(type,found){if(found.has(type)){logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`,"types",types)}found.add(type);for(const child of links.get(type)){if(!parents.has(child)){continue}checkCircular(child,found);for(const subtype of found){subtypes.get(subtype).add(child)}}found.delete(type)}checkCircular(this.primaryType,new Set);for(const[name,set]of subtypes){const st=Array.from(set);st.sort();this.#fullTypes.set(name,encodeType(name,types[name])+st.map(t=>encodeType(t,types[t])).join(""))}}getEncoder(type){let encoder=this.#encoderCache.get(type);if(!encoder){encoder=this.#getEncoder(type);this.#encoderCache.set(type,encoder)}return encoder}#getEncoder(type){{const encoder=getBaseEncoder(type);if(encoder){return encoder}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1];const subEncoder=this.getEncoder(subtype);const length=parseInt(match[3]);return value=>{if(length>=0&&value.length!==length){logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",value)}let result=value.map(subEncoder);if(this.#fullTypes.has(subtype)){result=result.map(keccak256)}return keccak256(concat(result))}}const fields=this.types[type];if(fields){const encodedType=id(this.#fullTypes.get(type));return value=>{const values=fields.map(({name,type})=>{const result=this.getEncoder(type)(value[name]);if(this.#fullTypes.has(type)){return keccak256(result)}return result});values.unshift(encodedType);return concat(values)}}return logger.throwArgumentError(`unknown type: ${type}`,"type",type)}encodeType(name){const result=this.#fullTypes.get(name);if(!result){return logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`,"name",name)}return result}encodeData(type,value){return this.getEncoder(type)(value)}hashStruct(name,value){return keccak256(this.encodeData(name,value))}encode(value){return this.encodeData(this.primaryType,value)}hash(value){return this.hashStruct(this.primaryType,value)}_visit(type,value,callback){{const encoder=getBaseEncoder(type);if(encoder){return callback(type,value)}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1];const length=parseInt(match[3]);if(length>=0&&value.length!==length){logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",value)}return value.map(v=>this._visit(subtype,v,callback))}const fields=this.types[type];if(fields){return fields.reduce((accum,{name,type})=>{accum[name]=this._visit(type,value[name],callback);return accum},{})}return logger.throwArgumentError(`unknown type: ${type}`,"type",type)}visit(value,callback){return this._visit(this.primaryType,value,callback)}static from(types){return new TypedDataEncoder(types)}static getPrimaryType(types){return TypedDataEncoder.from(types).primaryType}static hashStruct(name,types,value){return TypedDataEncoder.from(types).hashStruct(name,value)}static hashDomain(domain){const domainFields=[];for(const name in domain){const type=domainFieldTypes[name];if(!type){logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`,"domain",domain)}domainFields.push({name:name,type:type})}domainFields.sort((a,b)=>{return domainFieldNames.indexOf(a.name)-domainFieldNames.indexOf(b.name)});return TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:domainFields},domain)}static encode(domain,types,value){return concat(["0x1901",TypedDataEncoder.hashDomain(domain),TypedDataEncoder.from(types).hash(value)])}static hash(domain,types,value){return keccak256(TypedDataEncoder.encode(domain,types,value))}static async resolveNames(domain,types,value,resolveName){domain=Object.assign({},domain);const ensCache={};if(domain.verifyingContract&&!isHexString(domain.verifyingContract,20)){ensCache[domain.verifyingContract]="0x"}const encoder=TypedDataEncoder.from(types);encoder.visit(value,(type,value)=>{if(type==="address"&&!isHexString(value,20)){ensCache[value]="0x"}return value});for(const name in ensCache){ensCache[name]=await resolveName(name)}if(domain.verifyingContract&&ensCache[domain.verifyingContract]){domain.verifyingContract=ensCache[domain.verifyingContract]}value=encoder.visit(value,(type,value)=>{if(type==="address"&&ensCache[value]){return ensCache[value]}return value});return{domain:domain,value:value}}static getPayload(domain,types,value){TypedDataEncoder.hashDomain(domain);const domainValues={};const domainTypes=[];domainFieldNames.forEach(name=>{const value=domain[name];if(value==null){return}domainValues[name]=domainChecks[name](value);domainTypes.push({name:name,type:domainFieldTypes[name]})});const encoder=TypedDataEncoder.from(types);const typesWithDomain=Object.assign({},types);if(typesWithDomain.EIP712Domain){logger.throwArgumentError("types must not contain EIP712Domain type","types.EIP712Domain",types)}else{typesWithDomain.EIP712Domain=domainTypes}encoder.encode(value);return{types:typesWithDomain,domain:domainValues,primaryType:encoder.primaryType,message:encoder.visit(value,(type,value)=>{if(type.match(/^bytes(\d*)/)){return hexlify(logger.getBytes(value))}if(type.match(/^u?int/)){return logger.getBigInt(value).toString()}switch(type){case"address":return value.toLowerCase();case"bool":return!!value;case"string":if(typeof value!=="string"){logger.throwArgumentError(`invalid string`,"value",value)}return value}return logger.throwArgumentError("unsupported type","type",type)})}}}class LogDescription{fragment;name;signature;topic;args;constructor(fragment,topic,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,signature:signature,topic:topic,args:args})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(fragment,selector,args,value){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector,value:value})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(fragment,selector,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector})}}class Indexed{hash;_isIndexed;static isIndexed(value){return!!(value&&value._isIndexed)}constructor(hash){defineProperties(this,{hash:hash,_isIndexed:true})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"};const BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:message=>{return`reverted with reason string ${JSON.stringify(message)}`}},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:code=>{let reason="unknown panic code";if(code>=0&&code<=255&&PanicReasons[code.toString()]){reason=PanicReasons[code.toString()]}return`reverted with panic code 0x${code.toString(16)} (${reason})`}}};class Interface{fragments;deploy;#errors;#events;#functions;#abiCoder;constructor(fragments){let abi=[];if(typeof fragments==="string"){abi=JSON.parse(fragments)}else{abi=fragments}this.#functions=new Map;this.#errors=new Map;this.#events=new Map;defineProperties(this,{fragments:Object.freeze(abi.map(f=>Fragment.from(f)).filter(f=>f!=null))});this.#abiCoder=this.getAbiCoder();this.fragments.forEach(fragment=>{let bucket;switch(fragment.type){case"constructor":if(this.deploy){logger.warn("duplicate definition - constructor");return}defineProperties(this,{deploy:fragment});return;case"function":bucket=this.#functions;break;case"event":bucket=this.#events;break;case"error":bucket=this.#errors;break;default:return}const signature=fragment.format();if(bucket.has(signature)){logger.warn("duplicate definition - "+signature);return}bucket.set(signature,fragment)});if(!this.deploy){defineProperties(this,{deploy:ConstructorFragment.fromString("constructor()")})}}format(format){if(!format){format=FormatType.full}if(format===FormatType.sighash){logger.throwArgumentError("interface does not support formatting sighash","format",format)}const abi=this.fragments.map(f=>f.format(format));if(format===FormatType.json){return JSON.stringify(abi.map(j=>JSON.parse(j)))}return abi}getAbiCoder(){return defaultAbiCoder}#getFunction(key,values,forceUnique){if(isHexString(key)){const selector=key.toLowerCase();for(const fragment of this.#functions.values()){if(selector===this.getSelector(fragment)){return fragment}}logger.throwArgumentError("no matching function","selector",key)}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#functions){if(name.split("(")[0]===key){matching.push(fragment)}}if(values){const lastValue=values.length>0?values[values.length-1]:null;let valueLength=values.length;let allowOptions=true;if(Typed.isTyped(lastValue)&&lastValue.type==="overrides"){allowOptions=false;valueLength--}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs.length;if(inputs!==valueLength&&(!allowOptions||inputs!==valueLength-1)){matching.splice(i,1)}}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs;for(let j=0;j=inputs.length){if(values[j].type==="overrides"){continue}matching.splice(i,1);break}if(values[j].type!==inputs[j].baseType){matching.splice(i,1);break}}}}if(matching.length===1&&values&&values.length!==matching[0].inputs.length){const lastArg=values[values.length-1];if(lastArg==null||Array.isArray(lastArg)||typeof lastArg!=="object"){matching.splice(0,1)}}if(matching.length===0){logger.throwArgumentError("no matching function","name",key)}else if(matching.length>1&&forceUnique){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");logger.throwArgumentError(`multiple matching functions (i.e. ${matchStr})`,"name",key)}return matching[0]}const result=this.#functions.get(FunctionFragment.fromString(key).format());if(result){return result}return logger.throwArgumentError("no matching function","signature",key)}getFunctionName(key){return this.#getFunction(key,null,false).name}getFunction(key,values){return this.#getFunction(key,values||null,true)}#getEvent(key,values,forceUnique){if(isHexString(key)){const eventTopic=key.toLowerCase();for(const fragment of this.#events.values()){if(eventTopic===this.getEventTopic(fragment)){return fragment}}logger.throwArgumentError("no matching event","eventTopic",key)}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#events){if(name.split("(")[0]===key){matching.push(fragment)}}if(values){for(let i=matching.length-1;i>=0;i--){if(matching[i].inputs.length=0;i--){const inputs=matching[i].inputs;for(let j=0;j1&&forceUnique){logger.throwArgumentError("multiple matching events","name",key)}return matching[0]}const result=this.#events.get(EventFragment.fromString(key).format());if(result){return result}return logger.throwArgumentError("no matching event","signature",key)}getEventName(key){return this.#getEvent(key,null,false).name}getEvent(key,values){return this.#getEvent(key,values||null,true)}getError(key,values){if(isHexString(key)){const selector=key.toLowerCase();if(BuiltinErrors[selector]){return ErrorFragment.fromString(BuiltinErrors[selector].signature)}for(const fragment of this.#errors.values()){if(selector===this.getSelector(fragment)){return fragment}}logger.throwArgumentError("no matching error","selector",key)}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#errors){if(name.split("(")[0]===key){matching.push(fragment)}}if(matching.length===0){if(key==="Error"){return ErrorFragment.fromString("error Error(string)")}if(key==="Panic"){return ErrorFragment.fromString("error Panic(uint256)")}logger.throwArgumentError("no matching error","name",key)}else if(matching.length>1){logger.throwArgumentError("multiple matching errors","name",key)}return matching[0]}key=ErrorFragment.fromString(key).format();if(key==="Error(string)"){return ErrorFragment.fromString("error Error(string)")}if(key==="Panic(uint256)"){return ErrorFragment.fromString("error Panic(uint256)")}const result=this.#errors.get(key);if(result){return result}return logger.throwArgumentError("no matching error","signature",key)}getSelector(fragment){return dataSlice(id(fragment.format()),0,4)}getEventTopic(fragment){return id(fragment.format())}_decodeParams(params,data){return this.#abiCoder.decode(params,data)}_encodeParams(params,values){return this.#abiCoder.encode(params,values)}encodeDeploy(values){return this._encodeParams(this.deploy.inputs,values||[])}decodeErrorResult(fragment,data){if(typeof fragment==="string"){fragment=this.getError(fragment)}if(dataSlice(data,0,4)!==this.getSelector(fragment)){logger.throwArgumentError(`data signature does not match error ${fragment.name}.`,"data",data)}return this._decodeParams(fragment.inputs,dataSlice(data,4))}encodeErrorResult(fragment,values){if(typeof fragment==="string"){fragment=this.getError(fragment)}return concat([this.getSelector(fragment),this._encodeParams(fragment.inputs,values||[])])}decodeFunctionData(fragment,data){if(typeof fragment==="string"){fragment=this.getFunction(fragment)}if(dataSlice(data,0,4)!==this.getSelector(fragment)){logger.throwArgumentError(`data signature does not match function ${fragment.name}.`,"data",data)}return this._decodeParams(fragment.inputs,dataSlice(data,4))}encodeFunctionData(fragment,values){if(typeof fragment==="string"){fragment=this.getFunction(fragment)}return concat([this.getSelector(fragment),this._encodeParams(fragment.inputs,values||[])])}decodeFunctionResult(fragment,data){if(typeof fragment==="string"){fragment=this.getFunction(fragment)}let message="invalid length for result data";const bytes=logger.getBytesCopy(data);if(bytes.length%32===0){try{return this.#abiCoder.decode(fragment.outputs,bytes)}catch(error){message="could not decode result data"}}return logger.throwError(message,"BAD_DATA",{value:hexlify(bytes),info:{method:fragment.name,signature:fragment.format()}})}makeError(fragment,_data,tx){if(typeof fragment==="string"){fragment=this.getFunction(fragment)}const data=logger.getBytes(_data);let args=undefined;if(tx){try{args=this.#abiCoder.decode(fragment.inputs,tx.data||"0x")}catch(error){console.log(error)}}let errorArgs=undefined;let errorName=undefined;let errorSignature=undefined;let reason="unknown reason";if(data.length===0){reason="missing error reason"}else if(data.length%32===4){const selector=hexlify(data.slice(0,4));const builtin=BuiltinErrors[selector];if(builtin){try{errorName=builtin.name;errorSignature=builtin.signature;errorArgs=this.#abiCoder.decode(builtin.inputs,data.slice(4));reason=builtin.reason(...errorArgs)}catch(error){console.log(error)}}else{reason="unknown custom error";try{const error=this.getError(selector);errorName=error.name;errorSignature=error.format();reason=`custom error: ${errorSignature}`;try{errorArgs=this.#abiCoder.decode(error.inputs,data.slice(4))}catch(error){reason=`custom error: ${errorSignature} (coult not decode error data)`}}catch(error){console.log(error)}}}return logger.makeError("call revert exception","CALL_EXCEPTION",{data:hexlify(data),transaction:null,method:fragment.name,signature:fragment.format(),args:args,errorArgs:errorArgs,errorName:errorName,errorSignature:errorSignature,reason:reason})}encodeFunctionResult(functionFragment,values){if(typeof functionFragment==="string"){functionFragment=this.getFunction(functionFragment)}return hexlify(this.#abiCoder.encode(functionFragment.outputs,values||[]))}encodeFilterTopics(eventFragment,values){if(typeof eventFragment==="string"){eventFragment=this.getEvent(eventFragment)}if(values.length>eventFragment.inputs.length){logger.throwError("too many arguments for "+eventFragment.format(),"UNEXPECTED_ARGUMENT",{count:values.length,expectedCount:eventFragment.inputs.length})}const topics=[];if(!eventFragment.anonymous){topics.push(this.getEventTopic(eventFragment))}const encodeTopic=(param,value)=>{if(param.type==="string"){return id(value)}else if(param.type==="bytes"){return keccak256(hexlify(value))}if(param.type==="bool"&&typeof value==="boolean"){value=value?"0x01":"0x00"}if(param.type.match(/^u?int/)){value=toHex(value)}if(param.type==="address"){this.#abiCoder.encode(["address"],[value])}return zeroPadValue(hexlify(value),32)};values.forEach((value,index)=>{const param=eventFragment.inputs[index];if(!param.indexed){if(value!=null){logger.throwArgumentError("cannot filter non-indexed parameters; must be null","contract."+param.name,value)}return}if(value==null){topics.push(null)}else if(param.baseType==="array"||param.baseType==="tuple"){logger.throwArgumentError("filtering with tuples or arrays not supported","contract."+param.name,value)}else if(Array.isArray(value)){topics.push(value.map(value=>encodeTopic(param,value)))}else{topics.push(encodeTopic(param,value))}});while(topics.length&&topics[topics.length-1]===null){topics.pop()}return topics}encodeEventLog(eventFragment,values){if(typeof eventFragment==="string"){eventFragment=this.getEvent(eventFragment)}const topics=[];const dataTypes=[];const dataValues=[];if(!eventFragment.anonymous){topics.push(this.getEventTopic(eventFragment))}if(values.length!==eventFragment.inputs.length){logger.throwArgumentError("event arguments/values mismatch","values",values)}eventFragment.inputs.forEach((param,index)=>{const value=values[index];if(param.indexed){if(param.type==="string"){topics.push(id(value))}else if(param.type==="bytes"){topics.push(keccak256(value))}else if(param.baseType==="tuple"||param.baseType==="array"){throw new Error("not implemented")}else{topics.push(this.#abiCoder.encode([param.type],[value]))}}else{dataTypes.push(param);dataValues.push(value)}});return{data:this.#abiCoder.encode(dataTypes,dataValues),topics:topics}}decodeEventLog(eventFragment,data,topics){if(typeof eventFragment==="string"){eventFragment=this.getEvent(eventFragment)}if(topics!=null&&!eventFragment.anonymous){const eventTopic=this.getEventTopic(eventFragment);if(!isHexString(topics[0],32)||topics[0].toLowerCase()!==eventTopic){logger.throwArgumentError("fragment/topic mismatch","topics[0]",topics[0])}topics=topics.slice(1)}const indexed=[];const nonIndexed=[];const dynamic=[];eventFragment.inputs.forEach((param,index)=>{if(param.indexed){if(param.type==="string"||param.type==="bytes"||param.baseType==="tuple"||param.baseType==="array"){indexed.push(ParamType.fromObject({type:"bytes32",name:param.name}));dynamic.push(true)}else{indexed.push(param);dynamic.push(false)}}else{nonIndexed.push(param);dynamic.push(false)}});const resultIndexed=topics!=null?this.#abiCoder.decode(indexed,concat(topics)):null;const resultNonIndexed=this.#abiCoder.decode(nonIndexed,data,true);const values=[];const keys=[];let nonIndexedIndex=0,indexedIndex=0;eventFragment.inputs.forEach((param,index)=>{let value=null;if(param.indexed){if(resultIndexed==null){value=new Indexed(null)}else if(dynamic[index]){value=new Indexed(resultIndexed[indexedIndex++])}else{try{value=resultIndexed[indexedIndex++]}catch(error){value=error}}}else{try{value=resultNonIndexed[nonIndexedIndex++]}catch(error){value=error}}values.push(value);keys.push(param.name||null)});return Result.fromItems(values,keys)}parseTransaction(tx){const data=logger.getBytes(tx.data,"tx.data");const value=logger.getBigInt(tx.value!=null?tx.value:0,"tx.value");const fragment=this.getFunction(hexlify(data.slice(0,4)));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,data.slice(4));return new TransactionDescription(fragment,this.getSelector(fragment),args,value)}parseLog(log){const fragment=this.getEvent(log.topics[0]);if(!fragment||fragment.anonymous){return null}return new LogDescription(fragment,this.getEventTopic(fragment),this.decodeEventLog(fragment,log.data,log.topics))}parseError(data){const hexData=hexlify(data);const fragment=this.getError(dataSlice(hexData,0,4));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,dataSlice(hexData,4));return new ErrorDescription(fragment,this.getSelector(fragment),args)}static from(value){if(value instanceof Interface){return value}if(typeof value==="string"){return new Interface(JSON.parse(value))}if(typeof value.format==="function"){return new Interface(value.format(FormatType.json))}return new Interface(value)}}function accessSetify(addr,storageKeys){return{address:getAddress(addr),storageKeys:(storageKeys||[]).map((storageKey,index)=>{if(dataLength(storageKey)!==32){throw new Error("")}return storageKey.toLowerCase()})}}function accessListify(value){if(Array.isArray(value)){return value.map((set,index)=>{if(Array.isArray(set)){if(set.length>2){throw new Error("")}return accessSetify(set[0],set[1])}return accessSetify(set.address,set.storageKeys)})}const result=Object.keys(value).map(addr=>{const storageKeys=value[addr].reduce((accum,storageKey)=>{accum[storageKey]=true;return accum},{});return accessSetify(addr,Object.keys(storageKeys).sort())});result.sort((a,b)=>a.address.localeCompare(b.address));return result}function computeAddress(key){const publicKey=SigningKey.computePublicKey(key,false);return getAddress(keccak256("0x"+publicKey.substring(4)).substring(26))}function recoverAddress(digest,signature){return computeAddress(SigningKey.recoverPublicKey(digest,signature))}const BN_0=BigInt(0);const BN_2$2=BigInt(2);const BN_27=BigInt(27);const BN_28=BigInt(28);const BN_35=BigInt(35);const BN_MAX_UINT=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function handleAddress(value){if(value==="0x"){return null}return getAddress(value)}function handleData(value,param){try{return hexlify(value)}catch(error){return logger.throwArgumentError("invalid data",param,value)}}function handleAccessList(value,param){try{return accessListify(value)}catch(error){return logger.throwArgumentError("invalid accessList",param,value)}}function handleNumber(_value,param){if(_value==="0x"){return 0}return logger.getNumber(_value,param)}function handleUint(_value,param){if(_value==="0x"){return BN_0}const value=logger.getBigInt(_value,param);if(value>BN_MAX_UINT){logger.throwArgumentError("value exceeds uint size",param,value)}return value}function formatNumber(_value,name){const value=logger.getBigInt(_value,"value");const result=toArray(value);if(result.length>32){logger.throwArgumentError(`value too large`,`tx.${name}`,value)}return result}function formatAccessList(value){return accessListify(value).map(set=>[set.address,set.storageKeys])}function _parseLegacy(data){const fields=decodeRlp(data);if(!Array.isArray(fields)||fields.length!==9&&fields.length!==6){return logger.throwArgumentError("invalid field count for legacy transaction","data",data)}const tx={type:0,nonce:handleNumber(fields[0],"nonce"),gasPrice:handleUint(fields[1],"gasPrice"),gasLimit:handleUint(fields[2],"gasLimit"),to:handleAddress(fields[3]),value:handleUint(fields[4],"value"),data:handleData(fields[5],"dta"),chainId:BN_0};if(fields.length===6){return tx}const v=handleUint(fields[6],"v");const r=handleUint(fields[7],"r");const s=handleUint(fields[8],"s");if(r===BN_0&&s===BN_0){tx.chainId=v}else{let chainId=(v-BN_35)/BN_2$2;if(chainIdBN_28)){logger.throwArgumentError("non-canonical legacy v","v",fields[6])}tx.signature=Signature.from({r:zeroPadValue(fields[7],32),s:zeroPadValue(fields[8],32),v:v});tx.hash=keccak256(data)}return tx}function _serializeLegacy(tx,sig){const fields=[formatNumber(tx.nonce||0,"nonce"),formatNumber(tx.gasPrice||0,"gasPrice"),formatNumber(tx.gasLimit||0,"gasLimit"),tx.to!=null?getAddress(tx.to):"0x",formatNumber(tx.value||0,"value"),tx.data||"0x"];let chainId=BN_0;if(tx.chainId!=null){chainId=logger.getBigInt(tx.chainId,"tx.chainId");if(sig&&sig.networkV!=null&&sig.legacyChainId!==chainId){logger.throwArgumentError("tx.chainId/sig.v mismatch","sig",sig)}}else if(sig){const legacy=sig.legacyChainId;if(legacy!=null){chainId=legacy}}if(!sig){if(chainId!==BN_0){fields.push(toArray(chainId));fields.push("0x");fields.push("0x")}return encodeRlp(fields)}let v=BigInt(27+sig.yParity);if(chainId!==BN_0){v=Signature.getChainIdV(chainId,sig.v)}else if(BigInt(sig.v)!==v){logger.throwArgumentError("tx.chainId/sig.v mismatch","sig",sig)}fields.push(toArray(v));fields.push(toArray(sig.r));fields.push(toArray(sig.s));return encodeRlp(fields)}function _parseEipSignature(tx,fields,serialize){let yParity;try{yParity=handleNumber(fields[0],"yParity");if(yParity!==0&&yParity!==1){throw new Error("bad yParity")}}catch(error){return logger.throwArgumentError("invalid yParity","yParity",fields[0])}const r=zeroPadValue(fields[1],32);const s=zeroPadValue(fields[2],32);const signature=Signature.from({r:r,s:s,yParity:yParity});tx.signature=signature}function _parseEip1559(data){const fields=decodeRlp(logger.getBytes(data).slice(1));if(!Array.isArray(fields)||fields.length!==9&&fields.length!==12){logger.throwArgumentError("invalid field count for transaction type: 2","data",hexlify(data))}const maxPriorityFeePerGas=handleUint(fields[2],"maxPriorityFeePerGas");const maxFeePerGas=handleUint(fields[3],"maxFeePerGas");const tx={type:2,chainId:handleUint(fields[0],"chainId"),nonce:handleNumber(fields[1],"nonce"),maxPriorityFeePerGas:maxPriorityFeePerGas,maxFeePerGas:maxFeePerGas,gasPrice:null,gasLimit:handleUint(fields[4],"gasLimit"),to:handleAddress(fields[5]),value:handleUint(fields[6],"value"),data:handleData(fields[7],"data"),accessList:handleAccessList(fields[8],"accessList")};if(fields.length===9){return tx}tx.hash=keccak256(data);_parseEipSignature(tx,fields.slice(9),_serializeEip1559);return tx}function _serializeEip1559(tx,sig){const fields=[formatNumber(tx.chainId||0,"chainId"),formatNumber(tx.nonce||0,"nonce"),formatNumber(tx.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(tx.maxFeePerGas||0,"maxFeePerGas"),formatNumber(tx.gasLimit||0,"gasLimit"),tx.to!=null?getAddress(tx.to):"0x",formatNumber(tx.value||0,"value"),tx.data||"0x",formatAccessList(tx.accessList||[])];if(sig){fields.push(formatNumber(sig.yParity,"yParity"));fields.push(toArray(sig.r));fields.push(toArray(sig.s))}return concat(["0x02",encodeRlp(fields)])}function _parseEip2930(data){const fields=decodeRlp(logger.getBytes(data).slice(1));if(!Array.isArray(fields)||fields.length!==8&&fields.length!==11){logger.throwArgumentError("invalid field count for transaction type: 1","data",hexlify(data))}const tx={type:1,chainId:handleUint(fields[0],"chainId"),nonce:handleNumber(fields[1],"nonce"),gasPrice:handleUint(fields[2],"gasPrice"),gasLimit:handleUint(fields[3],"gasLimit"),to:handleAddress(fields[4]),value:handleUint(fields[5],"value"),data:handleData(fields[6],"data"),accessList:handleAccessList(fields[7],"accessList")};if(fields.length===8){return tx}tx.hash=keccak256(data);_parseEipSignature(tx,fields.slice(8),_serializeEip2930);return tx}function _serializeEip2930(tx,sig){const fields=[formatNumber(tx.chainId||0,"chainId"),formatNumber(tx.nonce||0,"nonce"),formatNumber(tx.gasPrice||0,"gasPrice"),formatNumber(tx.gasLimit||0,"gasLimit"),tx.to!=null?getAddress(tx.to):"0x",formatNumber(tx.value||0,"value"),tx.data||"0x",formatAccessList(tx.accessList||[])];if(sig){fields.push(formatNumber(sig.yParity,"recoveryParam"));fields.push(toArray(sig.r));fields.push(toArray(sig.s))}return concat(["0x01",encodeRlp(fields)])}class Transaction{#props;get type(){return getStore(this.#props,"type")}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559"}return null}set type(value){switch(value){case null:setStore(this.#props,"type",null);break;case 0:case"legacy":setStore(this.#props,"type",0);break;case 1:case"berlin":case"eip-2930":setStore(this.#props,"type",1);break;case 2:case"london":case"eip-1559":setStore(this.#props,"type",2);break;default:throw new Error(`unsupported transaction type`)}}get to(){return getStore(this.#props,"to")}set to(value){setStore(this.#props,"to",value==null?null:getAddress(value))}get nonce(){return getStore(this.#props,"nonce")}set nonce(value){setStore(this.#props,"nonce",logger.getNumber(value,"value"))}get gasLimit(){return getStore(this.#props,"gasLimit")}set gasLimit(value){setStore(this.#props,"gasLimit",logger.getBigInt(value))}get gasPrice(){const value=getStore(this.#props,"gasPrice");if(value==null&&(this.type===0||this.type===1)){return BN_0}return value}set gasPrice(value){setStore(this.#props,"gasPrice",value==null?null:logger.getBigInt(value,"gasPrice"))}get maxPriorityFeePerGas(){const value=getStore(this.#props,"maxPriorityFeePerGas");if(value==null&&this.type===2){return BN_0}return value}set maxPriorityFeePerGas(value){setStore(this.#props,"maxPriorityFeePerGas",value==null?null:logger.getBigInt(value,"maxPriorityFeePerGas"))}get maxFeePerGas(){const value=getStore(this.#props,"maxFeePerGas");if(value==null&&this.type===2){return BN_0}return value}set maxFeePerGas(value){setStore(this.#props,"maxFeePerGas",value==null?null:logger.getBigInt(value,"maxFeePerGas"))}get data(){return getStore(this.#props,"data")}set data(value){setStore(this.#props,"data",hexlify(value))}get value(){return getStore(this.#props,"value")}set value(value){setStore(this.#props,"value",logger.getBigInt(value,"value"))}get chainId(){return getStore(this.#props,"chainId")}set chainId(value){setStore(this.#props,"chainId",logger.getBigInt(value))}get signature(){return getStore(this.#props,"sig")||null}set signature(value){setStore(this.#props,"sig",value==null?null:Signature.from(value))}get accessList(){const value=getStore(this.#props,"accessList")||null;if(value==null&&(this.type===1||this.type===2)){return[]}return value}set accessList(value){setStore(this.#props,"accessList",value==null?null:accessListify(value))}constructor(){this.#props={type:null,to:null,nonce:0,gasLimit:BigInt(0),gasPrice:null,maxPriorityFeePerGas:null,maxFeePerGas:null,data:"0x",value:BigInt(0),chainId:BigInt(0),sig:null,accessList:null}}get hash(){if(this.signature==null){throw new Error("cannot hash unsigned transaction; maybe you meant .unsignedHash")}return keccak256(this.serialized)}get unsignedHash(){return keccak256(this.unsignedSerialized)}get from(){if(this.signature==null){return null}return recoverAddress(this.unsignedSerialized,this.signature)}get fromPublicKey(){if(this.signature==null){return null}return""}isSigned(){return this.signature!=null}get serialized(){if(this.signature==null){throw new Error("cannot serialize unsigned transaction; maybe you meant .unsignedSerialized")}const types=this.inferTypes();if(types.length!==1){throw new Error("cannot determine transaction type; specify type manually")}switch(types[0]){case 0:return _serializeLegacy(this,this.signature);case 1:return _serializeEip2930(this,this.signature);case 2:return _serializeEip1559(this,this.signature)}throw new Error("unsupported type")}get unsignedSerialized(){const types=this.inferTypes();if(types.length!==1){throw new Error("cannot determine transaction type; specify type manually")}switch(types[0]){case 0:return _serializeLegacy(this);case 1:return _serializeEip2930(this);case 2:return _serializeEip1559(this)}throw new Error("unsupported type")}inferTypes(){const hasGasPrice=this.gasPrice!=null;const hasFee=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null;const hasAccessList=this.accessList!=null;if(this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null){if(this.maxFeePerGas{Object.freeze(set.storageKeys);return Object.freeze(set)}))}Object.freeze(this.#props);return this}isFrozen(){return Object.isFrozen(this.#props)}static from(tx){if(typeof tx==="string"){const payload=logger.getBytes(tx);if(payload[0]>=127){return Transaction.from(_parseLegacy(payload))}switch(payload[0]){case 1:return Transaction.from(_parseEip2930(payload));case 2:return Transaction.from(_parseEip1559(payload))}throw new Error("unsupported transaction type")}const result=new Transaction;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.gasPrice!=null){result.gasPrice=tx.gasPrice}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.hash!=null){if(result.isSigned()){if(result.hash!==tx.hash){throw new Error("hash mismatch")}}else{throw new Error("unsigned transaction cannot have a hashs")}}if(tx.from!=null){if(result.isSigned()){if(result.from.toLowerCase()!==(tx.from||"").toLowerCase()){throw new Error("from mismatch")}}else{throw new Error("unsigned transaction cannot have a from")}}return result}}class AbstractSigner{provider;constructor(provider){defineProperties(this,{provider:provider||null})}#checkProvider(operation){if(this.provider){return this.provider}return logger.throwError("missing provider","UNSUPPORTED_OPERATION",{operation:operation})}async getNonce(blockTag){return this.#checkProvider("getTransactionCount").getTransactionCount(await this.getAddress(),blockTag)}async#populate(op,tx){const provider=this.#checkProvider(op);let pop=Object.assign({},tx);if(pop.to!=null){pop.to=provider.resolveName(pop.to).then(to=>{if(to==null){return logger.throwArgumentError("transaction to ENS name not configured","tx.to",pop.to)}return to})}if(pop.from!=null){const from=pop.from;pop.from=Promise.all([this.getAddress(),this.resolveName(from)]).then(([address,from])=>{if(!from||address.toLowerCase()!==from.toLowerCase()){return logger.throwArgumentError("transaction from mismatch","tx.from",from)}return address})}return pop}async populateCall(tx){const pop=await this.#populate("populateCall",tx);return pop}async populateTransaction(tx){const pop=await this.#populate("populateTransaction",tx);if(pop.nonce==null){pop.nonce=await this.getNonce("pending")}if(pop.gasLimit==null){pop.gasLimit=await this.estimateGas(pop)}return await resolveProperties(pop)}async estimateGas(tx){return this.#checkProvider("estimateGas").estimateGas(await this.populateCall(tx))}async call(tx){return this.#checkProvider("call").call(await this.populateCall(tx))}async resolveName(name){const provider=this.#checkProvider("resolveName");return await provider.resolveName(name)}async sendTransaction(tx){const provider=this.#checkProvider("sendTransaction");const txObj=Transaction.from(await this.populateTransaction(tx));return await provider.broadcastTransaction(await this.signTransaction(txObj))}}class VoidSigner extends AbstractSigner{address;constructor(address,provider){super(provider);defineProperties(this,{address:address})}async getAddress(){return this.address}connect(provider){return new VoidSigner(this.address,provider)}#throwUnsupported(suffix,operation){return logger.throwError(`VoidSigner cannot sign ${suffix}`,"UNSUPPORTED_OPERATION",{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")}}class WrappedSigner extends AbstractSigner{#signer;constructor(signer){super(signer.provider);this.#signer=signer}async getAddress(){return await this.#signer.getAddress()}connect(provider){return new WrappedSigner(this.#signer.connect(provider))}async getNonce(blockTag){return await this.#signer.getNonce(blockTag)}async populateCall(tx){return await this.#signer.populateCall(tx)}async populateTransaction(tx){return await this.#signer.populateTransaction(tx)}async estimateGas(tx){return await this.#signer.estimateGas(tx)}async call(tx){return await this.#signer.call(tx)}async resolveName(name){return this.#signer.resolveName(name)}async signTransaction(tx){return await this.#signer.signTransaction(tx)}async sendTransaction(tx){return await this.#signer.sendTransaction(tx)}async signMessage(message){return await this.#signer.signMessage(message)}async signTypedData(domain,types,value){return await this.#signer.signTypedData(domain,types,value)}}function getValue(value){if(value==null){return null}return value}function toJson(value){if(value==null){return null}return value.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(gasPrice,maxFeePerGas,maxPriorityFeePerGas){defineProperties(this,{gasPrice:getValue(gasPrice),maxFeePerGas:getValue(maxFeePerGas),maxPriorityFeePerGas:getValue(maxPriorityFeePerGas)})}toJSON(){const{gasPrice,maxFeePerGas,maxPriorityFeePerGas}=this;return{_type:"FeeData",gasPrice:toJson(gasPrice),maxFeePerGas:toJson(maxFeePerGas),maxPriorityFeePerGas:toJson(maxPriorityFeePerGas)}}}function copyRequest$1(req){const result={};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 in bigIntKeys){if(!(key in req)||req[key]==null){continue}result[key]=logger.getBigInt(req[key],`request.${key}`)}const numberKeys="type,nonce".split(/,/);for(const key in numberKeys){if(!(key in req)||req[key]==null){continue}result[key]=logger.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.enableCcipReadEnabled=!!req.enableCcipRead}if("customData"in req){result.customData=req.customData}return result}class Block{provider;number;hash;timestamp;parentHash;nonce;difficulty;gasLimit;gasUsed;miner;extraData;baseFeePerGas;#transactions;constructor(block,provider){if(provider==null){provider=dummyProvider}this.#transactions=Object.freeze(block.transactions.map(tx=>{if(typeof tx!=="string"&&tx.provider!==provider){throw new Error("provider mismatch")}return tx}));defineProperties(this,{provider: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)})}get transactions(){return this.#transactions}toJSON(){const{baseFeePerGas,difficulty,extraData,gasLimit,gasUsed,hash,miner,nonce,number,parentHash,timestamp,transactions}=this;return{_type:"Block",baseFeePerGas:toJson(baseFeePerGas),difficulty:toJson(difficulty),extraData:extraData,gasLimit:toJson(gasLimit),gasUsed:toJson(gasUsed),hash:hash,miner:miner,nonce:nonce,number:number,parentHash:parentHash,timestamp:timestamp,transactions:transactions}}[Symbol.iterator](){let index=0;return{next:()=>{if(index{if(provider!==log.provider){throw new Error("provider mismatch")}return log}));defineProperties(this,{provider: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:tx.effectiveGasPrice||tx.gasPrice,byzantium:tx.byzantium,status:tx.status,root:tx.root})}get logs(){return this.#logs}toJSON(){const{to,from,contractAddress,hash,index,blockHash,blockNumber,logsBloom,logs,byzantium,status,root}=this;return{_type:"TransactionReceipt",blockHash:blockHash,blockNumber:blockNumber,byzantium:byzantium,contractAddress:contractAddress,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:from,gasPrice:toJson(this.gasPrice),gasUsed:toJson(this.gasUsed),hash:hash,index:index,logs:logs,logsBloom:logsBloom,root:root,status:status,to:to}}get length(){return this.logs.length}[Symbol.iterator](){let index=0;return{next:()=>{if(indexthis.hash(t));return new Block(params,provider)}blockWithTransactions(value,provider){throw new Error}transactionRequest(value,provider){return this.#format.transactionRequest(value)}transactionResponse(value,provider){value=Object.assign({},value);if(value.data==null&&value.input!=null){value.data=value.input}if(value.gasLimit==null&&value.gas){value.gasLimit=value.gas}value=this.#format.transactionResponse(value);const sig=Signature.from({r:value.r,s:value.s,v:value.v});value.signature=sig;if(value.chainId==null){value.chainId=sig.legacyChainId}return new TransactionResponse(value,provider)}log(value,provider){const log=this.object({address:this.address,blockHash:this.hash,blockNumber:this.number,data:this.data,index:this.number,removed:this.boolean,topics:this.topics,transactionHash:this.hash,transactionIndex:this.number},{index:["logIndex"]})(value);return new Log(log,provider)}receipt(value,provider){const receipt=this.object({blockHash:this.hash,blockNumber:this.number,contractAddress:this.allowNull(this.address),cumulativeGasUsed:this.bigNumber,from:this.address,gasUsed:this.bigNumber,logs:this.arrayOf(v=>this.log(v,provider)),logsBloom:this.data,root:this.allowNull(this.data),status:this.allowNull(this.number),to:this.address,gasPrice:this.allowNull(this.bigNumber),hash:this.hash,index:this.number,type:this.allowNull(this.number,0)},{hash:["transactionHash"],gasPrice:["effectiveGasPrice"],index:["transactionIndex"]})(value);if(receipt.root!=null){if(receipt.root.length<=4){const value=parseInt(receipt.root);if(value===0||value===1){if(receipt.status!=null&&receipt.status!==value){return logger.throwError("alt-root-status/status mismatch","BAD_DATA",{value:{root:receipt.root,status:receipt.status}})}receipt.status=value;delete receipt.root}else{return logger.throwError("invalid alt-root-status","BAD_DATA",{value:receipt.root})}}else if(!isHexString(receipt.root,32)){return logger.throwError("invalid receipt root hash","BAD_DATA",{value:receipt.root})}}return new TransactionReceipt(receipt,provider)}topics(value){return this.#format.topics(value)}filter(value){return this.#format.filter(value)}filterLog(value){console.log("ME",value);return null}transaction(value){throw new Error}accessList(value){return accessListify(value)}allowFalsish(format,ifFalse){return value=>{if(!value){return ifFalse}return format.call(this,value)}}allowNull(format,ifNull){return value=>{if(value==null){return ifNull}return format.call(this,value)}}arrayOf(format){return array=>{if(!Array.isArray(array)){throw new Error("not an array")}return array.map(i=>format.call(this,i))}}bigNumber(value){return logger.getBigInt(value,"value")}uint256(value){const result=this.bigNumber(value);if(result<0||result>BN_MAX_UINT256){logger.throwArgumentError("invalid uint256","value",value)}return result}boolean(value){switch(value){case true:case"true":return true;case false:case"false":return false}return logger.throwArgumentError(`invalid boolean; ${JSON.stringify(value)}`,"value",value)}_hexstring(dataOrLength){if(dataOrLength==null){dataOrLength=false}return function(value){if(isHexString(value,dataOrLength)){return value.toLowerCase()}throw new Error("bad hexstring")}}data(value){if(dataLength(value)==null){logger.throwArgumentError("","value",value)}return value}hash(value){if(dataLength(value)!==32){logger.throwArgumentError("","value",value)}return this.#format.data(value)}number(value){return logger.getNumber(value)}object(format,altNames){return value=>{const result={};for(const key in format){let srcKey=key;if(altNames&&key in altNames&&!(srcKey in value)){for(const altKey of altNames[key]){if(altKey in value){srcKey=altKey;break}}}try{const nv=format[key].call(this,value[srcKey]);if(nv!==undefined){result[key]=nv}}catch(error){const message=error instanceof Error?error.message:"not-an-error";logger.throwError(`invalid value for value.${key} (${message})`,"BAD_DATA",{value:value})}}return result}}}const EnsAddress="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";class NetworkPlugin{name;constructor(name){defineProperties(this,{name:name})}clone(){return new NetworkPlugin(this.name)}validate(network){return this}}class GasCostPlugin extends NetworkPlugin{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(effectiveBlock=0,costs){super(`org.ethers.network-plugins.gas-cost#${effectiveBlock||0}`);const props={effectiveBlock:effectiveBlock};function set(name,nullish){let value=(costs||{})[name];if(value==null){value=nullish}if(typeof value!=="number"){logger.throwArgumentError(`invalud value for ${name}`,"costs",costs)}props[name]=value}set("txBase",21e3);set("txCreate",32e3);set("txDataZero",4);set("txDataNonzero",16);set("txAccessListStorageKey",1900);set("txAccessListAddress",2400);defineProperties(this,props)}clone(){return new GasCostPlugin(this.effectiveBlock,this)}}class EnsPlugin extends NetworkPlugin{address;targetNetwork;constructor(address,targetNetwork){super("org.ethers.network-plugins.ens");defineProperties(this,{address:address||EnsAddress,targetNetwork:targetNetwork==null?1:targetNetwork})}clone(){return new EnsPlugin(this.address,this.targetNetwork)}validate(network){network.formatter.address(this.address);return this}}class FeeDataNetworkPlugin extends NetworkPlugin{#feeDataFunc;get feeDataFunc(){return this.#feeDataFunc}constructor(feeDataFunc){super("org.ethers.network-plugins.fee-data");this.#feeDataFunc=feeDataFunc}async getFeeData(provider){return await this.#feeDataFunc(provider)}clone(){return new FeeDataNetworkPlugin(this.#feeDataFunc)}}const BN_1$1=BigInt(1);const Empty=new Uint8Array([]);function parseBytes(result,start){if(result==="0x"){return null}const offset=toNumber(dataSlice(result,start,start+32));const length=toNumber(dataSlice(result,offset,offset+32));return dataSlice(result,offset+32,offset+32+length)}function parseString(result,start){try{const bytes=parseBytes(result,start);if(bytes!=null){return toUtf8String(bytes)}}catch(error){}return null}function numPad$1(value){const result=toArray(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$1(value){if(value.length%32===0){return value}const result=new Uint8Array(Math.ceil(value.length/32)*32);result.set(value);return result}function encodeBytes$1(datas){const result=[];let byteCount=0;for(let i=0;i{return logger.getBigInt(result)===BN_1$1}).catch(error=>{if(error.code==="CALL_EXCEPTION"){return false}this.#supports2544=null;throw error})}return await this.#supports2544}async _fetch(selector,parameters="0x"){const addrData=concat([selector,namehash(this.name),parameters]);const tx={to:this.address,enableCcipRead:true,data:addrData};let wrapped=false;if(await this.supportsWildcard()){wrapped=true;tx.data=concat(["0x9061b923",encodeBytes$1([dnsEncode(this.name),addrData])])}try{let data=await this.provider.call(tx);if(logger.getBytes(data).length%32===4){return logger.throwError("resolver threw error","CALL_EXCEPTION",{transaction:tx,data:data})}if(wrapped){return parseBytes(data,0)}return data}catch(error){if(error.code!=="CALL_EXCEPTION"){throw error}}return null}async getAddress(coinType=60){if(coinType===60){try{const result=await this._fetch("0x3b3b57de");if(result==="0x"||result===ZeroHash){return null}const network=await this.provider.getNetwork();return network.formatter.callAddress(result)}catch(error){if(error.code==="CALL_EXCEPTION"){return null}throw error}}let coinPlugin=null;for(const plugin of this.provider.plugins){if(!(plugin instanceof MulticoinProviderPlugin)){continue}if(plugin.supportsCoinType(coinType)){coinPlugin=plugin;break}}if(coinPlugin==null){return null}const data=parseBytes(await this._fetch("0xf1cb7e06",numPad$1(coinType))||"0x",0);if(data==null||data==="0x"){return null}const address=await coinPlugin.encodeAddress(coinType,data);if(address!=null){return address}return logger.throwError(`invalid coin data`,"UNSUPPORTED_OPERATION",{operation:`getAddress(${coinType})`,info:{coinType:coinType,data:data}})}async getText(key){let keyBytes=toUtf8Bytes(key);const calldata=logger.getBytes(concat([numPad$1(64),numPad$1(keyBytes.length),keyBytes]));const hexBytes=parseBytes(await this._fetch("0x59d1d43c",bytesPad$1(calldata))||"0x",0);if(hexBytes==null||hexBytes==="0x"){return null}return toUtf8String(hexBytes)}async getContentHash(){const hexBytes=parseBytes(await this._fetch("0xbc1c58d1")||"0x",0);if(hexBytes==null||hexBytes==="0x"){return null}const ipfs=hexBytes.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(ipfs){const scheme=ipfs[1]==="e3010170"?"ipfs":"ipns";const length=parseInt(ipfs[4],16);if(ipfs[5].length===length*2){return`${scheme}:/\/${encodeBase58("0x"+ipfs[2])}`}}const swarm=hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(swarm&&swarm[1].length===64){return`bzz:/\/${swarm[1]}`}return logger.throwError(`invalid or unsupported content hash data`,"UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:hexBytes}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const linkage=[{type:"name",value:this.name}];try{const avatar=await this.getText("avatar");if(avatar==null){linkage.push({type:"!avatar",value:""});throw new Error("!avatar")}linkage.push({type:"avatar",value:avatar});for(let i=0;ip.name.split("#")[0]===basename)}clone(){const clone=new Network(this.name,this.chainId,this.formatter);this.plugins.forEach(plugin=>{clone.attachPlugin(plugin.clone())});return clone}freeze(){Object.freeze(this.#props);return this}isFrozen(){return Object.isFrozen(this.#props)}computeIntrinsicGas(tx){const costs=this.getPlugin("org.ethers.gas-cost")||new GasCostPlugin;let gas=costs.txBase;if(tx.to==null){gas+=costs.txCreate}if(tx.data){for(let i=2;i{this._poll(blockNumber,this.#provider)}}async _poll(blockNumber,provider){throw new Error("sub-classes must override this")}start(){this.#poll(-2);this.#provider.on("block",this.#poll)}stop(){this.#provider.off("block",this.#poll)}pause(dropWhilePaused){this.stop()}resume(){this.start()}}class PollingOrphanSubscriber extends OnBlockSubscriber{#filter;constructor(provider,filter){super(provider);this.#filter=copy$2(filter)}async _poll(blockNumber,provider){throw new Error("@TODO");console.log(this.#filter)}}class PollingTransactionSubscriber extends OnBlockSubscriber{#hash;constructor(provider,hash){super(provider);this.#hash=hash}async _poll(blockNumber,provider){const tx=await provider.getTransactionReceipt(this.#hash);if(tx){provider.emit(this.#hash,tx)}}}class PollingEventSubscriber{#provider;#filter;#poller;#blockNumber;constructor(provider,filter){this.#provider=provider;this.#filter=copy$2(filter);this.#poller=this.#poll.bind(this);this.#blockNumber=-2}async#poll(blockNumber){if(this.#blockNumber===-2){return}const filter=copy$2(this.#filter);filter.fromBlock=this.#blockNumber+1;filter.toBlock=blockNumber;const logs=await this.#provider.getLogs(filter);if(logs.length===0){if(this.#blockNumber{this.#blockNumber=blockNumber})}this.#provider.on("block",this.#poller)}stop(){this.#provider.off("block",this.#poller)}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}const BN_2$1=BigInt(2);const MAX_CCIP_REDIRECTS=10;function getTag(prefix,value){return prefix+":"+JSON.stringify(value,(k,v)=>{if(typeof v==="bigint"){return`bigint:${v.toString()}`}if(typeof v==="string"){return v.toLowerCase()}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})}class UnmanagedSubscriber{name;constructor(name){defineProperties(this,{name:name})}start(){}stop(){}pause(dropWhilePaused){}resume(){}}function copy$1(value){return JSON.parse(JSON.stringify(value))}function concisify$1(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")}if(Array.isArray(_event)){_event={topics:_event}}if(typeof _event==="string"){switch(_event){case"block":case"pending":case"debug":case"network":{return{type:_event,tag:_event}}}}if(isHexString(_event,32)){const hash=_event.toLowerCase();return{type:"transaction",tag:getTag("tx",{hash:hash}),hash:hash}}if(_event.orphan){const event=_event;return{type:"orphan",tag:getTag("orphan",event),filter:copy$1(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$1(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$1(addresses.map(a=>a.toLowerCase()))}return{filter:filter,tag:getTag("event",filter),type:"event"}}return logger.throwArgumentError("unknown ProviderEvent","event",_event)}function getTime$1(){return(new Date).getTime()}function copyRequest(tx){return tx}class AbstractProvider{#subs;#plugins;#pausedState;#networkPromise;#anyNetwork;#performCache;#nextTimer;#timers;#disableCcipRead;constructor(_network){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.#performCache=new Map;this.#subs=new Map;this.#plugins=new Map;this.#pausedState=null;this.#nextTimer=0;this.#timers=new Map;this.#disableCcipRead=false}get provider(){return this}get plugins(){return Array.from(this.#plugins.values())}attachPlugin(plugin){if(this.#plugins.get(plugin.name)){throw new Error(`cannot replace existing plugin: ${plugin.name} `)}this.#plugins.set(plugin.name,plugin.validate(this));return this}getPlugin(name){return this.#plugins.get(name)||null}set disableCcipRead(value){this.#disableCcipRead=!!value}get disableCcipRead(){return this.#disableCcipRead}async#perform(req){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)}},250)}return await perform}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=400&&resp.statusCode<500){return logger.throwError(`response not found during CCIP fetch: ${errorMessage}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:tx,info:{url:url,errorMessage:errorMessage}})}errorMessages.push(errorMessage)}return logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map(m=>JSON.stringify(m)).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:tx,info:{urls:urls,errorMessages:errorMessages}})}_wrapTransaction(tx,hash,blockNumber){return tx}_detectNetwork(){return logger.throwError("sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(req){return logger.throwError(`unsupported method: ${req.method}`,"UNSUPPORTED_OPERATION",{operation:req.method,info:req})}async getBlockNumber(){return logger.getNumber(await this.#perform({method:"getBlockNumber"}),"%response")}_getAddress(address){return resolveAddress(address,this)}_getBlockTag(blockTag){if(blockTag==null){return"latest"}switch(blockTag){case"earliest":return"0x0";case"latest":case"pending":case"safe":case"finalized":return blockTag}if(isHexString(blockTag)){if(dataLength(blockTag)===32){return blockTag}return toQuantity(blockTag)}if(typeof blockTag==="number"){if(blockTag>=0){return toQuantity(blockTag)}return this.getBlockNumber().then(b=>toQuantity(b+blockTag))}return logger.throwArgumentError("invalid blockTag","blockTag",blockTag)}async getNetwork(){if(this.#networkPromise==null){const detectNetwork=this._detectNetwork().then(network=>{this.emit("network",network,null);return network},error=>{if(this.#networkPromise===detectNetwork){this.#networkPromise=null}throw error});this.#networkPromise=detectNetwork;return await detectNetwork}const networkPromise=this.#networkPromise;const[expected,actual]=await Promise.all([networkPromise,this._detectNetwork()]);if(expected.chainId!==actual.chainId){if(this.#anyNetwork){this.emit("network",actual,expected);if(this.#networkPromise===networkPromise){this.#networkPromise=Promise.resolve(actual)}}else{logger.throwError(`network changed: ${expected.chainId} => ${actual.chainId} `,"NETWORK_ERROR",{event:"changed"})}}return expected.clone().freeze()}async getFeeData(){const{block,gasPrice}=await resolveProperties({block:this.getBlock("latest"),gasPrice:(async()=>{try{const gasPrice=await this.#perform({method:"getGasPrice"});return logger.getBigInt(gasPrice,"%response")}catch(error){}return null})()});let maxFeePerGas=null,maxPriorityFeePerGas=null;if(block&&block.baseFeePerGas){maxPriorityFeePerGas=BigInt("1500000000");maxFeePerGas=block.baseFeePerGas*BN_2$1+maxPriorityFeePerGas}return new FeeData(gasPrice,maxFeePerGas,maxPriorityFeePerGas)}async _getTransaction(_request){const network=await this.getNetwork();const request=Object.assign({},_request,await resolveProperties({to:_request.to?resolveAddress(_request.to,this):undefined,from:_request.from?resolveAddress(_request.from,this):undefined}));return network.formatter.transactionRequest(request)}async estimateGas(_tx){const transaction=await this._getTransaction(_tx);return logger.getBigInt(await this.#perform({method:"estimateGas",transaction:transaction}),"%response")}async#call(tx,blockTag,attempt){if(attempt>=MAX_CCIP_REDIRECTS){logger.throwError("CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},tx,{blockTag:blockTag,enableCcipRead:true})})}const transaction=copyRequest(tx);try{return hexlify(await this._perform({method:"call",transaction:transaction,blockTag:blockTag}))}catch(error){if(!this.disableCcipRead&&isCallException(error)&&attempt>=0&&blockTag==="latest"&&transaction.to!=null&&dataSlice(error.data,0,4)==="0x556f1830"){const data=error.data;const txSender=await resolveAddress(transaction.to,this);let ccipArgs;try{ccipArgs=parseOffchainLookup(dataSlice(error.data,4))}catch(error){return logger.throwError(error.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:transaction,info:{data:data}})}if(ccipArgs.sender.toLowerCase()!==txSender.toLowerCase()){return logger.throwError("CCIP Read sender mismatch","CALL_EXCEPTION",{data:data,transaction:transaction,errorSignature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",errorName:"OffchainLookup",errorArgs:ccipArgs.errorArgs})}const ccipResult=await this.ccipReadFetch(transaction,ccipArgs.calldata,ccipArgs.urls);if(ccipResult==null){return logger.throwError("CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:transaction,info:{data:error.data,errorArgs:ccipArgs.errorArgs}})}return this.#call({to:txSender,data:concat([ccipArgs.selector,encodeBytes([ccipResult,ccipArgs.extraData])])},blockTag,attempt+1)}throw error}}async call(_tx){const[tx,blockTag]=await Promise.all([this._getTransaction(_tx),this._getBlockTag(_tx.blockTag)]);return this.#call(tx,blockTag,_tx.enableCcipRead?0:-1)}async#getAccountValue(request,_address,_blockTag){let address=this._getAddress(_address);let blockTag=this._getBlockTag(_blockTag);if(typeof address!=="string"||typeof blockTag!=="string"){[address,blockTag]=await Promise.all([address,blockTag])}return await this.#perform(Object.assign(request,{address:address,blockTag:blockTag}))}async getBalance(address,blockTag){return logger.getBigInt(await this.#getAccountValue({method:"getBalance"},address,blockTag),"%response")}async getTransactionCount(address,blockTag){return logger.getNumber(await this.#getAccountValue({method:"getTransactionCount"},address,blockTag),"%response")}async getCode(address,blockTag){return hexlify(await this.#getAccountValue({method:"getCode"},address,blockTag))}async getStorageAt(address,_position,blockTag){const position=logger.getBigInt(_position,"position");return hexlify(await this.#getAccountValue({method:"getStorageAt",position:position},address,blockTag))}async broadcastTransaction(signedTx){throw new Error;return{}}async#getBlock(block,includeTransactions){if(isHexString(block,32)){return await this.#perform({method:"getBlock",blockHash:block,includeTransactions:includeTransactions})}let blockTag=this._getBlockTag(block);if(typeof blockTag!=="string"){blockTag=await blockTag}return await this.#perform({method:"getBlock",blockTag:blockTag,includeTransactions:includeTransactions})}async getBlock(block){const[network,params]=await Promise.all([this.getNetwork(),this.#getBlock(block,false)]);if(params==null){return null}return network.formatter.block(params,this)}async getBlockWithTransactions(block){const format=(await this.getNetwork()).formatter;const params=this.#getBlock(block,true);if(params==null){return null}return format.blockWithTransactions(params,this)}async getTransaction(hash){const format=(await this.getNetwork()).formatter;const params=await this.#perform({method:"getTransaction",hash:hash});return format.transactionResponse(params,this)}async getTransactionReceipt(hash){const format=(await this.getNetwork()).formatter;const receipt=await this.#perform({method:"getTransactionReceipt",hash:hash});if(receipt==null){return null}if(receipt.gasPrice==null&&receipt.effectiveGasPrice==null){const tx=await this.#perform({method:"getTransaction",hash:hash});receipt.effectiveGasPrice=tx.gasPrice}return format.receipt(receipt,this)}async getTransactionResult(hash){const result=await this.#perform({method:"getTransactionResult",hash:hash});if(result==null){return null}return hexlify(result)}_getFilter(filter){const topics=(filter.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify$1(t.map(t=>t.toLowerCase()))}return t.toLowerCase()});const blockHash="blockHash"in filter?filter.blockHash:undefined;const resolve=(_address,fromBlock,toBlock)=>{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}return filter};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.fromBlock)}let toBlock=undefined;if("toBlock"in filter){toBlock=this._getBlockTag(filter.toBlock)}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 resolve(result[0],result[1],result[2])})}return resolve(address,fromBlock,toBlock)}async getLogs(_filter){const{network,filter}=await resolveProperties({network:this.getNetwork(),filter:this._getFilter(_filter)});return(await this.#perform({method:"getLogs",filter:filter})).map(l=>{return network.formatter.log(l,this)})}_getProvider(chainId){return logger.throwError("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){throw new Error}async waitForTransaction(hash,confirms=1,timeout){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(logger.makeError("timeout","TIMEOUT",{reason:"timeout"}))},timeout)}listener(await this.getBlockNumber())})}async waitForBlock(blockTag){throw new Error}_clearTimeout(timerId){const timer=this.#timers.get(timerId);if(!timer){return}if(timer.timer){clearTimeout(timer.timer)}this.#timers.delete(timerId)}_setTimeout(_func,timeout=0){const timerId=this.#nextTimer++;const func=()=>{this.#timers.delete(timerId);_func()};if(this.paused){this.#timers.set(timerId,{timer:null,func:func,time:timeout})}else{const timer=setTimeout(func,timeout);this.#timers.set(timerId,{timer:timer,func:func,time:getTime$1()})}return timerId}_forEachSubscriber(func){for(const sub of this.#subs.values()){func(sub.subscriber)}}_getSubscriber(sub){switch(sub.type){case"debug":case"network":return new UnmanagedSubscriber(sub.type);case"block":return new PollingBlockSubscriber(this);case"event":return new PollingEventSubscriber(this,sub.filter);case"transaction":return new PollingTransactionSubscriber(this,sub.hash);case"orphan":return new PollingOrphanSubscriber(this,sub.filter)}throw new Error(`unsupported event: ${sub.type}`)}_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);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);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:subscriber,tag:tag,addressableMap:addressableMap,nameMap: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: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: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(!sub){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});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}async addListener(event,listener){return await this.on(event,listener)}async removeListener(event,listener){return this.off(event,listener)}async shutdown(){this.removeAllListeners();for(const timerId of this.#timers.keys()){this._clearTimeout(timerId)}}get paused(){return this.#pausedState!=null}set paused(pause){if(!!pause===this.paused){return}if(this.paused){this.resume()}else{this.pause(false)}}pause(dropWhilePaused){if(this.#pausedState!=null){if(this.#pausedState==!!dropWhilePaused){return}return logger.throwError("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()){if(timer.timer){clearTimeout(timer.timer)}timer.time=getTime$1()-timer.time}}resume(){if(this.#pausedState==null){return}this._forEachSubscriber(s=>s.resume());this.#pausedState=null;for(const timer of this.#timers.values()){let timeout=timer.time;if(timeout<0){timeout=0}timer.time=getTime$1();setTimeout(timer.func,timeout)}}}function _parseString(result,start){try{const bytes=_parseBytes(result,start);if(bytes){return toUtf8String(bytes)}}catch(error){}return null}function _parseBytes(result,start){if(result==="0x"){return null}try{const offset=logger.getNumber(dataSlice(result,start,start+32));const length=logger.getNumber(dataSlice(result,offset,offset+32));return dataSlice(result,offset+32,offset+32+length)}catch(error){}return null}function numPad(value){const result=toArray(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){if(value.length%32===0){return value}const result=new Uint8Array(Math.ceil(value.length/32)*32);result.set(value);return result}const empty=new Uint8Array([]);function encodeBytes(datas){const result=[];let byteCount=0;for(let i=0;iresult[k]);return result}if(false){console.log(isHexString,isError)}const defaultApiKey$2="9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB";const EtherscanPluginId="org.ethers.plugins.etherscan";class EtherscanPlugin extends NetworkPlugin{baseUrl;communityApiKey;constructor(baseUrl,communityApiKey){super(EtherscanPluginId);defineProperties(this,{baseUrl:baseUrl,communityApiKey:communityApiKey})}clone(){return new EtherscanPlugin(this.baseUrl,this.communityApiKey)}}class EtherscanProvider extends AbstractProvider{network;apiKey;constructor(_network,apiKey){super();const network=Network.from(_network);if(apiKey==null){const plugin=network.getPlugin(EtherscanPluginId);if(plugin){apiKey=plugin.communityApiKey}else{apiKey=defaultApiKey$2}}defineProperties(this,{apiKey:apiKey,network:network});this.getBaseUrl()}getBaseUrl(){const plugin=this.network.getPlugin(EtherscanPluginId);if(plugin){return plugin.baseUrl}switch(this.network.name){case"homestead":return"https://api.etherscan.io";case"ropsten":return"https://api-ropsten.etherscan.io";case"rinkeby":return"https://api-rinkeby.etherscan.io";case"kovan":return"https://api-kovan.etherscan.io";case"goerli":return"https://api-goerli.etherscan.io";default:}return logger.throwArgumentError("unsupported network","network",this.network)}getUrl(module,params){const query=Object.keys(params).reduce((accum,key)=>{const value=params[key];if(value!=null){accum+=`&${key}=${value}`}return accum},"");const apiKey=this.apiKey?`&apikey=${this.apiKey}`:"";return`${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`}getPostUrl(){return`${this.getBaseUrl()}/api`}getPostData(module,params){params.module=module;params.apikey=this.apiKey;return params}async detectNetwork(){return this.network}async fetch(module,params,post){const url=post?this.getPostUrl():this.getUrl(module,params);const payload=post?this.getPostData(module,params):null;const request=new FetchRequest(url);request.processFunc=async(request,response)=>{const result=response.hasBody()?JSON.parse(toUtf8String(response.body)):{};const throttle=(typeof result.result==="string"?result.result:"").toLowerCase().indexOf("rate limit")>=0;if(module==="proxy"){if(result&&result.status==0&&result.message=="NOTOK"&&throttle){response.throwThrottleError(result.result)}}else{if(throttle){response.throwThrottleError(result.result)}}return response};if(payload){request.setHeader("content-type","application/x-www-form-urlencoded; charset=UTF-8");request.body=Object.keys(payload).map(k=>`${k}=${payload[k]}`).join("&")}const response=await request.send();response.assertOk();if(!response.hasBody()){throw new Error}const result=JSON.parse(toUtf8String(response.body));if(module==="proxy"){if(result.jsonrpc!="2.0"){const error=new Error("invalid response");error.result=JSON.stringify(result);throw error}if(result.error){const error=new Error(result.error.message||"unknown error");if(result.error.code){error.code=result.error.code}if(result.error.data){error.data=result.error.data}throw error}return result.result}else{if(result.status==0&&(result.message==="No records found"||result.message==="No transactions found")){return result.result}if(result.status!=1||result.message!="OK"){const error=new Error("invalid response");error.result=JSON.stringify(result);throw error}return result.result}}_getTransactionPostData(transaction){const result={};for(let key in transaction){if(transaction[key]==null){continue}let value=transaction[key];if(key==="type"&&value===0){continue}if({type:true,gasLimit:true,gasPrice:true,maxFeePerGs:true,maxPriorityFeePerGas:true,nonce:true,value:true}[key]){value=toQuantity(hexlify(value))}else if(key==="accessList"){value="["+this.network.formatter.accessList(value).map(set=>{return`{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`}).join(",")+"]"}else{value=hexlify(value)}result[key]=value}return result}_checkError(req,error,transaction){throw error}async _detectNetwork(){return this.network}async _perform(req){switch(req.method){case"chainId":return this.network.chainId;case"getBlockNumber":return this.fetch("proxy",{action:"eth_blockNumber"});case"getGasPrice":return this.fetch("proxy",{action:"eth_gasPrice"});case"getBalance":return this.fetch("account",{action:"balance",address:req.address,tag:req.blockTag});case"getTransactionCount":return this.fetch("proxy",{action:"eth_getTransactionCount",address:req.address,tag:req.blockTag});case"getCode":return this.fetch("proxy",{action:"eth_getCode",address:req.address,tag:req.blockTag});case"getStorageAt":return this.fetch("proxy",{action:"eth_getStorageAt",address:req.address,position:req.position,tag:req.blockTag});case"broadcastTransaction":return this.fetch("proxy",{action:"eth_sendRawTransaction",hex:req.signedTransaction},true).catch(error=>{return this._checkError(req,error,req.signedTransaction)});case"getBlock":if("blockTag"in req){return this.fetch("proxy",{action:"eth_getBlockByNumber",tag:req.blockTag,boolean:req.includeTransactions?"true":"false"})}return logger.throwError("getBlock by blockHash not supported by Etherscan","UNSUPPORTED_OPERATION",{operation:"getBlock(blockHash)"});case"getTransaction":return this.fetch("proxy",{action:"eth_getTransactionByHash",txhash:req.hash});case"getTransactionReceipt":return this.fetch("proxy",{action:"eth_getTransactionReceipt",txhash:req.hash});case"call":{if(req.blockTag!=="latest"){throw new Error("EtherscanProvider does not support blockTag for call")}const postData=this._getTransactionPostData(req.transaction);postData.module="proxy";postData.action="eth_call";try{return await this.fetch("proxy",postData,true)}catch(error){return this._checkError(req,error,req.transaction)}}case"estimateGas":{const postData=this._getTransactionPostData(req.transaction);postData.module="proxy";postData.action="eth_estimateGas";try{return await this.fetch("proxy",postData,true)}catch(error){return this._checkError(req,error,req.transaction)}}default:break}return super._perform(req)}async getNetwork(){return this.network}async getEtherPrice(){if(this.network.name!=="homestead"){return 0}return parseFloat((await this.fetch("stats",{action:"ethprice"})).ethusd)}isCommunityResource(){const plugin=this.network.getPlugin(EtherscanPluginId);if(plugin){return plugin.communityApiKey===this.apiKey}return defaultApiKey$2===this.apiKey}}function injectCommonNetworks(){function registerEth(name,chainId,options){const func=function(){const network=new Network(name,chainId);if(options.ensNetwork!=null){network.attachPlugin(new EnsPlugin(null,options.ensNetwork))}if(options.priorityFee){}if(options.etherscan){const{url,apiKey}=options.etherscan;network.attachPlugin(new EtherscanPlugin(url,apiKey))}network.attachPlugin(new GasCostPlugin);return network};Network.register(name,func);Network.register(chainId,func);if(options.altNames){options.altNames.forEach(name=>{Network.register(name,func)})}}registerEth("homestead",1,{ensNetwork:1,altNames:["mainnet"]});registerEth("ropsten",3,{ensNetwork:3});registerEth("rinkeby",4,{ensNetwork:4});registerEth("goerli",5,{ensNetwork:5});registerEth("kovan",42,{ensNetwork:42});registerEth("classic",61,{});registerEth("classicKotti",6,{});registerEth("xdai",100,{ensNetwork:1});registerEth("matic",137,{ensNetwork:1,etherscan:{apiKey:"W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7",url:"https://api.polygonscan.com/"}});registerEth("maticMumbai",80001,{etherscan:{apiKey:"W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7",url:"https://api-testnet.polygonscan.com/"}});registerEth("bnb",56,{ensNetwork:1,etherscan:{apiKey:"EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9",url:"http://api.bscscan.com"}});registerEth("bnbt",97,{etherscan:{apiKey:"EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9",url:"http://api-testnet.bscscan.com"}})}injectCommonNetworks();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$2(duration){return new Promise(resolve=>{setTimeout(resolve,duration)})}function getTime(){return(new Date).getTime()}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};async function waitForSync(config,blockNumber){while(config.blockNumber<0||config.blockNumber{const blockNumber=await config.provider.getBlockNumber();if(blockNumber>config.blockNumber){config.blockNumber=blockNumber}config._updateNumber=null})()}await config._updateNumber;config.outOfSync++}}function normalize(network,value,req){switch(req.method){case"chainId":return logger.getBigInt(value).toString();case"getBlockNumber":return logger.getNumber(value).toString();case"getGasPrice":return logger.getBigInt(value).toString();case"getBalance":return logger.getBigInt(value).toString();case"getTransactionCount":return logger.getNumber(value).toString();case"getCode":return hexlify(value);case"getStorageAt":return hexlify(value);case"getBlock":if(req.includeTransactions){return JSON.stringify(network.formatter.blockWithTransactions(value))}return JSON.stringify(network.formatter.block(value));case"getTransaction":return JSON.stringify(network.formatter.transactionResponse(value));case"getTransactionReceipt":return JSON.stringify(network.formatter.receipt(value));case"call":return hexlify(value);case"estimateGas":return logger.getBigInt(value).toString();case"getLogs":return JSON.stringify(value.map(v=>network.formatter.log(v)))}return logger.throwError("unsupported method","UNSUPPORTED_OPERATION",{operation:`_perform(${JSON.stringify(req.method)})`})}function checkQuorum(quorum,results){const tally=new Map;for(const{result,normal,weight}of results){const t=tally.get(normal)||{result:result,weight:0};t.weight+=weight;tally.set(normal,t)}let bestWeight=0;let bestResult=undefined;for(const{weight,result}of tally.values()){if(weight>=quorum&&weight>bestWeight){bestWeight=weight;bestResult=result}}return bestResult}function getMedian(results){const values=results.map(r=>BigInt(r.result));values.sort((a,b)=>aa?1:0);const mid=values.length/2;if(values.length%2){return values[mid]}return(values[mid-1]+values[mid]+BN_1)/BN_2}function getFuzzyMode(quorum,results){if(quorum===1){return logger.getNumber(getMedian(results),"%internal")}const tally=new Map;const add=(result,weight)=>{const t=tally.get(result)||{result:result,weight:0};t.weight+=weight;tally.set(result,t)};for(const{weight,result}of results){const r=logger.getNumber(result);add(r-1,weight);add(r,weight);add(r+1,weight)}let bestWeight=0;let bestResult=undefined;for(const{weight,result}of tally.values()){if(weight>=quorum&&(weight>bestWeight||bestResult!=null&&weight===bestWeight&&result>bestResult)){bestWeight=weight;bestResult=result}}return bestResult}class FallbackProvider extends AbstractProvider{quorum;eventQuorum;eventWorkers;#configs;#height;#initialSyncPromise;constructor(providers,network){super(network);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;this.quorum=2;this.eventQuorum=1;this.eventWorkers=1;if(this.quorum>this.#configs.reduce((a,c)=>a+c.weight,0)){logger.throwArgumentError("quorum exceed provider wieght","quorum",this.quorum)}}get providerConfigs(){return this.#configs.slice()}async _detectNetwork(){return Network.from(logger.getBigInt(await this._perform({method:"chainId"}))).freeze()}#getNextConfig(configs){const allConfigs=this.#configs.slice();shuffle(allConfigs);allConfigs.sort((a,b)=>b.priority-a.priority);for(const config of allConfigs){if(configs.indexOf(config)===-1){return config}}return null}#addRunner(running,req){const config=this.#getNextConfig(Array.from(running).map(r=>r.config));if(config==null){return null}const result={};const runner={config:config,result:result,didBump:false,done:false,perform:null,staller:null};const now=getTime();runner.perform=(async()=>{try{config.requests++;result.result=await config.provider._perform(req)}catch(error){config.errorResponses++;result.error=error}if(runner.done){config.lateResponses++}const dt=getTime()-now;config._totalTime+=dt;config.rollingDuration=.95*config.rollingDuration+.05*dt;runner.perform=null})();runner.staller=(async()=>{await stall$2(config.stallTimeout);runner.staller=null})();running.add(runner);return runner}async#initialSync(){let initialSync=this.#initialSyncPromise;if(!initialSync){const promises=[];this.#configs.forEach(config=>{promises.push(waitForSync(config,0));promises.push((async()=>{config._network=await config.provider.getNetwork()})())});this.#initialSyncPromise=initialSync=(async()=>{await Promise.all(promises);let chainId=null;for(const config of this.#configs){const network=config._network;if(chainId==null){chainId=network.chainId}else if(network.chainId!==chainId){logger.throwError("cannot mix providers on different networks","UNSUPPORTED_OPERATION",{operation:"new FallbackProvider"})}}})()}await initialSync}async#checkQuorum(running,req){const results=[];for(const runner of running){if("result"in runner.result){const result=runner.result.result;results.push({result:result,normal:normalize(runner.config._network,result,req),weight:runner.config.weight})}}if(results.reduce((a,r)=>a+r.weight,0)({result:c.blockNumber,normal:logger.getNumber(c.blockNumber).toString(),weight:c.weight}))),"%internal"));this.#height=height}const mode=getFuzzyMode(this.quorum,results);if(mode===undefined){return undefined}if(mode>this.#height){this.#height=mode}return this.#height}case"getGasPrice":case"estimateGas":return getMedian(results);case"getBlock":if("blockTag"in req&&req.blockTag==="pending"){return results[0].result}return checkQuorum(this.quorum,results);case"chainId":case"getBalance":case"getTransactionCount":case"getCode":case"getStorageAt":case"getTransaction":case"getTransactionReceipt":case"getLogs":return checkQuorum(this.quorum,results);case"call":return checkQuorum(this.quorum,results);case"broadcastTransaction":throw new Error("TODO")}return logger.throwError("unsupported method","UNSUPPORTED_OPERATION",{operation:`_perform(${JSON.stringify(req.method)})`})}async#waitForQuorum(running,req){if(running.size===0){throw new Error("no runners?!")}const interesting=[];let newRunners=0;for(const runner of running){if(runner.perform){interesting.push(runner.perform)}if(runner.staller){interesting.push(runner.staller);continue}if(runner.didBump){continue}runner.didBump=true;newRunners++}const value=await this.#checkQuorum(running,req);if(value!==undefined){if(value instanceof Error){throw value}return value}for(let i=0;i{this.#provider.send("eth_uninstallFilter",[filterId])})}}start(){this.#poll(-2)}stop(){this.#teardown();this.#provider.off("block",this.#poller)}pause(dropWhilePaused){if(dropWhilePaused){this.#teardown()}this.#provider.off("block",this.#poller)}resume(){this.start()}}class FilterIdEventSubscriber extends FilterIdSubscriber{#event;constructor(provider,filter){super(provider);this.#event=copy(filter)}_recover(provider){return new PollingEventSubscriber(provider,this.#event)}async _subscribe(provider){const filterId=await provider.send("eth_newFilter",[this.#event]);console.log("____SUB",filterId);return filterId}async _emitResults(provider,results){const network=await provider.getNetwork();for(const result of results){const log=network.formatter.log(result,provider);provider.emit(this.#event,log)}}}class FilterIdPendingSubscriber extends FilterIdSubscriber{async _subscribe(provider){return await provider.send("eth_newPendingTransactionFilter",[])}async _emitResults(provider,results){const network=await provider.getNetwork();for(const result of results){provider.emit("pending",network.formatter.hash(result))}}}const Primitive="bigint,boolean,function,number,string,symbol".split(/,/g);function deepCopy(value){if(value==null||Primitive.indexOf(typeof value)>=0){return value}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 getLowerCase(value){if(value){return value.toLowerCase()}return value}function isPollable(value){return value&&typeof value.pollingInterval==="number"}const defaultOptions={polling:false,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100};class JsonRpcSigner extends AbstractSigner{address;constructor(provider,address){super(provider);defineProperties(this,{address:address})}connect(provider){return logger.throwError("cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(tx){return await this.populateCall(tx)}async sendUncheckedTransaction(_tx){const tx=deepCopy(_tx);const promises=[];if(tx.from){const _from=tx.from;promises.push((async()=>{const from=await resolveAddress(_from,this.provider);if(from==null||from.toLowerCase()!==this.address.toLowerCase()){logger.throwArgumentError("from address mismatch","transaction",_tx)}tx.from=from})())}else{tx.from=this.address}if(tx.gasLimit==null){promises.push((async()=>{tx.gasLimit=await this.provider.estimateGas({...tx,from:this.address})})())}if(tx.to!=null){const _to=tx.to;promises.push((async()=>{tx.to=await resolveAddress(_to,this.provider)})())}if(promises.length){await Promise.all(promises)}const hexTx=this.provider.getRpcTransaction(tx);return this.provider.send("eth_sendTransaction",[hexTx])}async sendTransaction(tx){const blockNumber=await this.provider.getBlockNumber();const hash=await this.sendUncheckedTransaction(tx);return await new Promise((resolve,reject)=>{const timeouts=[1e3,100];const checkTx=async()=>{const tx=await this.provider.getTransaction(hash);if(tx!=null){resolve(this.provider._wrapTransaction(tx,hash,blockNumber));return}this.provider._setTimeout(()=>{checkTx()},timeouts.pop()||4e3)};checkTx()})}async signTransaction(_tx){const tx=deepCopy(_tx);if(tx.from){const from=await resolveAddress(tx.from,this.provider);if(from==null||from.toLowerCase()!==this.address.toLowerCase()){return logger.throwArgumentError("from address mismatch","transaction",_tx)}tx.from=from}else{tx.from=this.address}const hexTx=this.provider.getRpcTransaction(tx);return await this.provider.send("eth_sign_Transaction",[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);const populated=await TypedDataEncoder.resolveNames(domain,types,value,async value=>{const address=await resolveAddress(value);if(address==null){return logger.throwArgumentError("TypedData does not support null address","value",value)}return address});return await this.provider.send("eth_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])}async _legacySignMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("eth_sign",[this.address.toLowerCase(),hexlify(message)])}}class JsonRpcApiProvider extends AbstractProvider{#options;#nextId;#payloads;#drainTimer;constructor(network,options){super(network);this.#nextId=1;this.#options=Object.assign({},defaultOptions,options||{});this.#payloads=[];this.#drainTimer=null;const staticNetwork=this._getOption("staticNetwork");if(staticNetwork&&staticNetwork!==network){logger.throwArgumentError("staticNetwork MUST match network object","options",options)}}_getOption(key){return this.#options[key]}#scheduleDrain(){if(this.#drainTimer){return}this.#drainTimer=setTimeout(()=>{this.#drainTimer=null;const payloads=this.#payloads;this.#payloads=[];while(payloads.length){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}}(async()=>{const payload=batch.length===1?batch[0].payload:batch.map(p=>p.payload);this.emit("debug",{action:"sendRpcPayload",payload:payload});try{const result=await this._send(payload);this.emit("debug",{action:"receiveRpcResult",result:result});for(const{resolve,reject,payload}of batch){const resp=result.filter(r=>r.id===payload.id)[0];if(resp==null){return reject(new Error("@TODO: no result"))}if("error"in resp){return reject(this.getRpcError(payload,resp))}resolve(resp.result)}}catch(error){this.emit("debug",{action:"receiveRpcError",error:error});for(const{reject}of batch){reject(error)}}})()}},this.#options.batchStallTime)}send(method,params){const id=this.#nextId++;const promise=new Promise((resolve,reject)=>{this.#payloads.push({resolve:resolve,reject:reject,payload:{method:method,params:params,id:id,jsonrpc:"2.0"}})});this.#scheduleDrain();return promise}_send(payload){return logger.throwError("sub-classes must override _send","UNSUPPORTED_OPERATION",{operation:"jsonRpcApiProvider._send"})}async getSigner(address=0){const accountsPromise=this.send("eth_accounts",[]);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[network,accounts]=await Promise.all([this.getNetwork(),accountsPromise]);address=network.formatter.address(address);for(const account of accounts){if(network.formatter.address(account)===account){return new JsonRpcSigner(this,account)}}throw new Error("invalid account")}async _detectNetwork(){const network=this._getOption("staticNetwork");if(network){return network}return Network.from(logger.getBigInt(await this._perform({method:"chainId"})))}_getSubscriber(sub){if(sub.type==="pending"){return new FilterIdPendingSubscriber(this)}if(sub.type==="event"){return new FilterIdEventSubscriber(this,sub.filter)}if(sub.type==="orphan"&&sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("orphan")}return super._getSubscriber(sub)}getRpcTransaction(tx){const result={};["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(logger.getBigInt(tx[key],`tx.${key}`))});["from","to","data"].forEach(key=>{if(tx[key]==null){return}result[key]=hexlify(tx[key])});if(tx.accessList){result["accessList"]=accessListify(tx.accessList)}return result}getRpcRequest(req){switch(req.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getBalance":return{method:"eth_getBalance",args:[getLowerCase(req.address),req.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[getLowerCase(req.address),req.blockTag]};case"getCode":return{method:"eth_getCode",args:[getLowerCase(req.address),req.blockTag]};case"getStorageAt":return{method:"eth_getStorageAt",args:[getLowerCase(req.address),"0x"+req.position.toString(16),req.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[req.signedTransaction]};case"getBlock":if("blockTag"in req){return{method:"eth_getBlockByNumber",args:[req.blockTag,!!req.includeTransactions]}}else if("blockHash"in req){return{method:"eth_getBlockByHash",args:[req.blockHash,!!req.includeTransactions]}}break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[req.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[req.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(req.transaction),req.blockTag]};case"estimateGas":{return{method:"eth_estimateGas",args:[this.getRpcTransaction(req.transaction)]}}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:"eth_getLogs",args:[req.filter]}}return null}getRpcError(payload,error){console.log("getRpcError",payload,error);return new Error(`JSON-RPC badness; @TODO: ${error}`)}async _perform(req){if(req.method==="call"||req.method==="estimateGas"){let tx=req.transaction;if(tx&&tx.type!=null&&logger.getBigInt(tx.type)){if(tx.maxFeePerGas==null&&tx.maxPriorityFeePerGas==null){const feeData=await this.getFeeData();if(feeData.maxFeePerGas==null&&feeData.maxPriorityFeePerGas==null){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)}return super._perform(req)}}class JsonRpcProvider extends JsonRpcApiProvider{#connect;#pollingInterval;constructor(url,network,options){if(url==null){url="http://localhost:8545"}super(network,options);if(typeof url==="string"){this.#connect=new FetchRequest(url)}else{this.#connect=url.clone()}this.#pollingInterval=4e3}async _send(payload){const request=this.#connect.clone();request.body=JSON.stringify(payload);const response=await request.send();response.assertOk();let resp=response.bodyJson;if(!Array.isArray(resp)){resp=[resp]}return resp}get pollingInterval(){return this.#pollingInterval}set pollingInterval(value){if(!Number.isInteger(value)||value<0){throw new Error("invalid interval")}this.#pollingInterval=value;this._forEachSubscriber(sub=>{if(isPollable(sub)){sub.pollingInterval=this.#pollingInterval}})}}const shown=new Set;function showThrottleMessage(service){if(shown.has(service)){return}shown.add(service);console.log("========= NOTICE =========");console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`);console.log("");console.log("The default API keys for each service are provided as a highly-throttled,");console.log("community resource for low-traffic projects and early prototyping.");console.log("");console.log("While your application will continue to function, we highly recommended");console.log("signing up for your own API keys to improve performance, increase your");console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");console.log("");console.log("For more details: https://docs.ethers.io/api-keys/");console.log("==========================")}const defaultApiKey$1="_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";function getHost$2(name){switch(name){case"homestead":return"eth-mainnet.alchemyapi.io";case"ropsten":return"eth-ropsten.alchemyapi.io";case"rinkeby":return"eth-rinkeby.alchemyapi.io";case"goerli":return"eth-goerli.alchemyapi.io";case"kovan":return"eth-kovan.alchemyapi.io";case"matic":return"polygon-mainnet.g.alchemy.com";case"maticmum":return"polygon-mumbai.g.alchemy.com";case"arbitrum":return"arb-mainnet.g.alchemy.com";case"arbitrum-rinkeby":return"arb-rinkeby.g.alchemy.com";case"optimism":return"opt-mainnet.g.alchemy.com";case"optimism-kovan":return"opt-kovan.g.alchemy.com"}return logger.throwArgumentError("unsupported network","network",name)}class AlchemyProvider extends JsonRpcProvider{apiKey;constructor(_network="homestead",apiKey){const network=Network.from(_network);if(apiKey==null){apiKey=defaultApiKey$1}const request=AlchemyProvider.getRequest(network,apiKey);super(request,network,{staticNetwork:network});defineProperties(this,{apiKey:apiKey})}_getProvider(chainId){try{return new AlchemyProvider(chainId,this.apiKey)}catch(error){}return super._getProvider(chainId)}async _perform(req){if(req.method==="getTransactionResult"){const trace=await this.send("trace_transaction",[req.hash]);if(trace==null){return null}let data;let error=false;try{data=trace[0].result.output;error=trace[0].error==="Reverted"}catch(error){}if(data){if(error){logger.throwError("an error occurred during transaction executions","CALL_EXCEPTION",{data:data})}return data}return logger.throwError("could not parse trace result","BAD_DATA",{value:trace})}return await super._perform(req)}isCommunityResource(){return this.apiKey===defaultApiKey$1}static getRequest(network,apiKey){if(apiKey==null){apiKey=defaultApiKey$1}const request=new FetchRequest(`https:/\/${getHost$2(network.name)}/v2/${apiKey}`);request.allowGzip=true;if(apiKey===defaultApiKey$1){request.retryFunc=async(request,response,attempt)=>{showThrottleMessage("alchemy");return true}}return request}}const defaultApiKey="9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";function getHost$1(name){switch(name){case"homestead":return"rpc.ankr.com/eth";case"ropsten":return"rpc.ankr.com/eth_ropsten";case"rinkeby":return"rpc.ankr.com/eth_rinkeby";case"goerli":return"rpc.ankr.com/eth_goerli";case"matic":return"rpc.ankr.com/polygon";case"arbitrum":return"rpc.ankr.com/arbitrum"}return logger.throwArgumentError("unsupported network","network",name)}class AnkrProvider extends JsonRpcProvider{apiKey;constructor(_network="homestead",apiKey){const network=Network.from(_network);if(apiKey==null){apiKey=defaultApiKey}const options={polling:true,staticNetwork:network};const request=AnkrProvider.getRequest(network,apiKey);super(request,network,options);defineProperties(this,{apiKey:apiKey})}_getProvider(chainId){try{return new AnkrProvider(chainId,this.apiKey)}catch(error){}return super._getProvider(chainId)}static getRequest(network,apiKey){if(apiKey==null){apiKey=defaultApiKey}const request=new FetchRequest(`https:/\/${getHost$1(network.name)}/${apiKey}`);request.allowGzip=true;if(apiKey===defaultApiKey){request.retryFunc=async(request,response,attempt)=>{showThrottleMessage("AnkrProvider");return true}}return request}isCommunityResource(){return this.apiKey===defaultApiKey}}class CloudflareProvider extends JsonRpcProvider{constructor(_network="homestead"){const network=Network.from(_network);if(network.name!=="homestead"){return logger.throwArgumentError("unsupported network","network",_network)}super("https://cloudflare-eth.com/",network,{staticNetwork:network})}}const defaultProjectId="84842078b09946638c03157f83405213";function getHost(name){switch(name){case"homestead":return"mainnet.infura.io";case"ropsten":return"ropsten.infura.io";case"rinkeby":return"rinkeby.infura.io";case"kovan":return"kovan.infura.io";case"goerli":return"goerli.infura.io";case"matic":return"polygon-mainnet.infura.io";case"maticmum":return"polygon-mumbai.infura.io";case"optimism":return"optimism-mainnet.infura.io";case"optimism-kovan":return"optimism-kovan.infura.io";case"arbitrum":return"arbitrum-mainnet.infura.io";case"arbitrum-rinkeby":return"arbitrum-rinkeby.infura.io"}return logger.throwArgumentError("unsupported network","network",name)}class InfuraProvider extends JsonRpcProvider{projectId;projectSecret;constructor(_network="homestead",projectId,projectSecret){const network=Network.from(_network);if(projectId==null){projectId=defaultProjectId}if(projectSecret==null){projectSecret=null}const request=InfuraProvider.getRequest(network,projectId,projectSecret);super(request,network,{staticNetwork:network});defineProperties(this,{projectId:projectId,projectSecret:projectSecret})}_getProvider(chainId){try{return new InfuraProvider(chainId,this.projectId,this.projectSecret)}catch(error){}return super._getProvider(chainId)}static getRequest(network,projectId,projectSecret){if(projectId==null){projectId=defaultProjectId}if(projectSecret==null){projectSecret=null}const request=new FetchRequest(`https:/\/${getHost(network.name)}/v3/${projectId}`);request.allowGzip=true;if(projectSecret){request.setCredentials("",projectSecret)}if(projectId===defaultProjectId){request.retryFunc=async(request,response,attempt)=>{showThrottleMessage("InfuraProvider");return true}}return request}isCommunityResource(){return this.projectId===defaultProjectId}}const IpcSocketProvider=undefined;class SocketSubscriber{#provider;#filter;get filter(){return JSON.parse(this.#filter)}#filterId;#paused;#emitPromise;constructor(provider,filter){this.#provider=provider;this.#filter=JSON.stringify(filter);this.#filterId=null;this.#paused=null;this.#emitPromise=null}start(){this.#filterId=this.#provider.send("eth_subscribe",this.filter).then(filterId=>{this.#provider._register(filterId,this);return filterId})}stop(){this.#filterId.then(filterId=>{this.#provider.send("eth_unsubscribe",[filterId])});this.#filterId=null}pause(dropWhilePaused){if(!dropWhilePaused){logger.throwError("preserve logs while paused not supported by SocketSubscriber yet","UNSUPPORTED_OPERATION",{operation:"pause(false)"})}this.#paused=!!dropWhilePaused}resume(){this.#paused=null}_handleMessage(message){if(this.#filterId==null){return}if(this.#paused===null){let emitPromise=this.#emitPromise;if(emitPromise==null){emitPromise=this._emit(this.#provider,message)}else{emitPromise=emitPromise.then(async()=>{await this._emit(this.#provider,message)})}this.#emitPromise=emitPromise.then(()=>{if(this.#emitPromise===emitPromise){this.#emitPromise=null}})}}async _emit(provider,message){throw new Error("sub-classes must implemente this; _emit")}}class SocketBlockSubscriber extends SocketSubscriber{constructor(provider){super(provider,["newHeads"])}async _emit(provider,message){provider.emit("block",parseInt(message.number))}}class SocketPendingSubscriber extends SocketSubscriber{constructor(provider){super(provider,["newPendingTransactions"])}async _emit(provider,message){provider.emit("pending",message)}}class SocketEventSubscriber extends SocketSubscriber{#logFilter;get logFilter(){return JSON.parse(this.#logFilter)}#formatter;constructor(provider,filter){super(provider,["logs",filter]);this.#logFilter=JSON.stringify(filter);this.#formatter=provider.getNetwork().then(network=>network.formatter)}async _emit(provider,message){const formatter=await this.#formatter;provider.emit(this.#logFilter,formatter.log(message,provider))}}class SocketProvider extends JsonRpcApiProvider{#callbacks;#ready;#subs;#pending;constructor(network){super(network,{batchMaxCount:1});this.#callbacks=new Map;this.#ready=false;this.#subs=new Map;this.#pending=new Map}_getSubscriber(sub){switch(sub.type){case"close":return new UnmanagedSubscriber("close");case"block":return new SocketBlockSubscriber(this);case"pending":return new SocketPendingSubscriber(this);case"event":return new SocketEventSubscriber(this,sub.filter);case"orphan":if(sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("drop-log")}}return super._getSubscriber(sub)}_register(filterId,subscriber){this.#subs.set(filterId,subscriber);const pending=this.#pending.get(filterId);if(pending){for(const message of pending){subscriber._handleMessage(message)}this.#pending.delete(filterId)}}async _send(payload){assertArgument(!Array.isArray(payload),"WebSocket does not support batch send","payload",payload);const promise=new Promise((resolve,reject)=>{this.#callbacks.set(payload.id,{payload:payload,resolve:resolve,reject:reject})});if(this.#ready){await this._write(JSON.stringify(payload))}return[await promise]}async _start(){if(this.#ready){return}this.#ready=true;for(const{payload}of this.#callbacks.values()){await this._write(JSON.stringify(payload))}}async _processMessage(message){const result=JSON.parse(message);if("id"in result){const callback=this.#callbacks.get(result.id);if(callback==null){console.log("Weird... Response for not a thing we sent");return}this.#callbacks.delete(result.id);if("error"in result){const{message,code,data}=result.error;const error=logger.makeError(message||"unkonwn error","SERVER_ERROR",{request:`ws:${JSON.stringify(callback.payload)}`,info:{code:code,data:data}});callback.reject(error)}else{callback.resolve(result.result)}}else if(result.method==="eth_subscription"){const filterId=result.params.subscription;const subscriber=this.#subs.get(filterId);if(subscriber){subscriber._handleMessage(result.params.result)}else{let pending=this.#pending.get(filterId);if(pending==null){pending=[];this.#pending.set(filterId,pending)}pending.push(result.params.result)}}}async _write(message){throw new Error("sub-classes must override this")}}function getGlobal(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const _WebSocket=getGlobal().WebSocket;class WebSocketProvider extends SocketProvider{url;#websocket;get websocket(){return this.#websocket}constructor(url,network){super(network);if(typeof url==="string"){this.#websocket=new _WebSocket(url)}else{this.#websocket=url}this.websocket.onopen=()=>{this._start()};this.websocket.onmessage=message=>{this._processMessage(message.data)}}async _write(message){this.websocket.send(message)}}class EventLog extends Log{interface;fragment;args;constructor(log,iface,fragment){super(log,log.provider);const args=iface.decodeEventLog(fragment,log.data,log.topics);defineProperties(this,{args:args,fragment:fragment,interface:iface})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class ContractTransactionReceipt extends TransactionReceipt{#interface;constructor(iface,provider,tx){super(tx,provider);this.#interface=iface}get logs(){return super.logs.map(log=>{const fragment=log.topics.length?this.#interface.getEvent(log.topics[0]):null;if(fragment){return new EventLog(log,this.#interface,fragment)}else{return log}})}}class ContractTransactionResponse extends TransactionResponse{#interface;constructor(iface,provider,tx){super(tx,provider);this.#interface=iface}async wait(confirms){const receipt=await super.wait();if(receipt==null){return null}return new ContractTransactionReceipt(this.#interface,this.provider,receipt)}}class ContractEventPayload extends EventPayload{fragment;log;args;constructor(contract,listener,filter,fragment,_log){super(contract,listener,filter);const log=new EventLog(_log,contract.interface,fragment);const args=contract.interface.decodeEventLog(fragment,log.data,log.topics);defineProperties(this,{args:args,fragment:fragment,log:log})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}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 concisify(items){items=Array.from(new Set(items).values());items.sort();return items}class PreparedTopicFilter{#filter;fragment;constructor(contract,fragment,args){defineProperties(this,{fragment:fragment});if(fragment.inputs.length{return param.walkAsync(args[index],(type,value)=>{if(type==="address"){return resolveAddress(value,resolver)}return value})}));return contract.interface.encodeFilterTopics(fragment,resolvedArgs)}()}getTopicFilter(){return this.#filter}}function _WrappedMethodBase(){return Function}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}async function copyOverrides(arg){const overrides=copyRequest$1(Typed.dereference(arg,"overrides"));if(overrides.to){logger.throwArgumentError("cannot override to","overrides.to",overrides.to)}else if(overrides.data){logger.throwArgumentError("cannot override data","overrides.data",overrides.data)}if(overrides.from){overrides.from=await resolveAddress(overrides.from)}return overrides}async function resolveArgs(_runner,inputs,args){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)=>{if(type==="address"){return resolveAddress(value,resolver)}return value})}))}class WrappedMethod extends _WrappedMethodBase(){name="";_contract;_key;constructor(contract,key){super();defineProperties(this,{name:contract.interface.getFunctionName(key),_contract:contract,_key:key});const proxy=new Proxy(this,{apply:async(target,thisArg,args)=>{const fragment=target.getFragment(...args);if(fragment.constant){return await target.staticCall(...args)}return await target.send(...args)}});return proxy}get fragment(){return this._contract.interface.getFunction(this._key)}getFragment(...args){return this._contract.interface.getFunction(this._key,args)}async populateTransaction(...args){const fragment=this.getFragment(...args);let overrides={};if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop())}if(fragment.inputs.length!==args.length){throw new Error("internal error: fragment inputs doesn't match arguments; should not happen")}const resolvedArgs=await resolveArgs(this._contract.runner,fragment.inputs,args);return Object.assign({},overrides,await resolveProperties({to:this._contract.getAddress(),data:this._contract.interface.encodeFunctionData(fragment,resolvedArgs)}))}async staticCall(...args){const result=await this.staticCallResult(...args);if(result.length===1){return result[0]}return result}async send(...args){const runner=this._contract.runner;if(!canSend(runner)){return logger.throwError("contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"})}const tx=await runner.sendTransaction(await this.populateTransaction(...args));const provider=getProvider(this._contract.runner);return new ContractTransactionResponse(this._contract.interface,provider,tx)}async estimateGas(...args){const runner=getRunner(this._contract.runner,"estimateGas");if(!canEstimate(runner)){return logger.throwError("contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"})}return await runner.estimateGas(await this.populateTransaction(...args))}async staticCallResult(...args){const runner=getRunner(this._contract.runner,"call");if(!canCall(runner)){return logger.throwError("contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"})}const fragment=this.getFragment(...args);const tx=await this.populateTransaction(...args);let result="0x";try{result=await runner.call(tx)}catch(error){if(isCallException(error)){throw this._contract.interface.makeError(fragment,error.data,tx)}throw error}return this._contract.interface.decodeFunctionResult(fragment,result)}}function _WrappedEventBase(){return Function}class WrappedEvent extends _WrappedEventBase(){name="";_contract;_key;constructor(contract,key){super();defineProperties(this,{name:contract.interface.getEventName(key),_contract:contract,_key:key});return new Proxy(this,{apply:async(target,thisArg,args)=>{return new PreparedTopicFilter(contract,target.getFragment(...args),args)}})}get fragment(){return this._contract.interface.getEvent(this._key)}getFragment(...args){return this._contract.interface.getEvent(this._key,args)}}const internal=Symbol.for("_ethersInternal_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 getSubTag(contract,event){let fragment;let topics;if(Array.isArray(event)){fragment=contract.interface.getEvent(event[0]);topics=event}else if(typeof event==="string"){fragment=contract.interface.getEvent(event);topics=[contract.interface.getEventTopic(fragment)]}else if(isDeferred(event)){fragment=event.fragment;topics=await event.getTopicFilter()}else if("fragment"in event){fragment=event.fragment;topics=[contract.interface.getEventTopic(fragment)]}else{console.log(event);throw new Error("TODO")}topics=topics.map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify(t.map(t=>t.toLowerCase()))}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:fragment,tag:tag,topics:topics}}async function hasSub(contract,event){const{subs}=getInternal(contract);return subs.get((await getSubTag(contract,event)).tag)||null}async function getSub(contract,event){const provider=getProvider(contract.runner);if(!provider){return logger.throwError("contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:"on"})}const{fragment,tag,topics}=await getSubTag(contract,event);const{addr,subs}=getInternal(contract);let sub=subs.get(tag);if(!sub){const address=addr?addr:contract;const filter={address:address,topics:topics};const listener=log=>{const payload=new ContractEventPayload(contract,null,event,fragment,log);emit(contract,event,payload.args,payload)};let started=false;const start=()=>{if(started){return}provider.on(filter,listener);started=true};const stop=()=>{if(!started){return}provider.off(filter,listener);started=false};sub={tag:tag,listeners:[],start:start,stop:stop};subs.set(tag,sub)}return sub}let lastEmit=Promise.resolve();async function _emit(contract,event,args,payload){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=args.slice();if(payload){passArgs.push(new ContractEventPayload(contract,once?null:listener,event,payload.fragment,payload.log))}try{listener.call(contract,...passArgs)}catch(error){}return!once});return count>0}async function emit(contract,event,args,payload){try{await lastEmit}catch(error){}const resultPromise=_emit(contract,event,args,payload);lastEmit=resultPromise;return await resultPromise}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];constructor(target,abi,runner=null,_deployTx){const iface=Interface.from(abi);defineProperties(this,{target:target,runner:runner,interface:iface});Object.defineProperty(this,internal,{value:{}});let addrPromise;let addr=null;let deployTx=null;if(_deployTx){const provider=getProvider(runner);deployTx=new ContractTransactionResponse(this.interface,provider,_deployTx)}let subs=new Map;if(typeof target==="string"){if(isHexString(target)){addr=target;addrPromise=Promise.resolve(target)}else{const resolver=getRunner(runner,"resolveName");if(!canResolve(resolver)){throw logger.makeError("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"})}addrPromise=resolver.resolveName(target).then(addr=>{if(addr==null){throw new Error("TODO")}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})}setInternal(this,{addrPromise:addrPromise,addr:addr,deployTx:deployTx,subs:subs});const filters=new Proxy({},{get:(target,_prop,receiver)=>{if(passProperties.indexOf(_prop)>=0){return Reflect.get(target,_prop,receiver)}const prop=String(_prop);const result=this.getEvent(prop);if(result){return result}throw new Error(`unknown contract event: ${prop}`)}});defineProperties(this,{filters:filters});return new Proxy(this,{get:(target,_prop,receiver)=>{if(_prop in target||passProperties.indexOf(_prop)>=0){return Reflect.get(target,_prop,receiver)}const prop=String(_prop);const result=target.getFunction(prop);if(result){return result}throw new Error(`unknown contract method: ${prop}`)}})}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const provider=getProvider(this.runner);if(!provider){return logger.throwError("runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"})}const code=await provider.getCode(await this.getAddress());if(code==="0x"){return null}return code}async waitForDeployment(){const deployTx=this.deploymentTransaction();if(deployTx){await deployTx.wait();return this}const code=await this.getDeployedCode();if(code!=null){return this}const provider=getProvider(this.runner);if(provider==null){return logger.throwError("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()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(key){if(typeof key!=="string"){key=key.format()}return new WrappedMethod(this,key)}getEvent(key){if(typeof key!=="string"){key=key.format()}return new WrappedEvent(this,key)}async queryTransaction(hash){throw new Error("@TODO")}async queryFilter(event,fromBlock=0,toBlock="latest"){const{addr,addrPromise}=getInternal(this);const address=addr?addr:await addrPromise;const{fragment,topics}=await getSubTag(this,event);const filter={address:address,topics:topics,fromBlock:fromBlock,toBlock:toBlock};const provider=getProvider(this.runner);if(!provider){return logger.throwError("contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"})}return(await provider.getLogs(filter)).map(log=>{return new EventLog(log,this.interface,fragment)})}async on(event,listener){const sub=await getSub(this,event);sub.listeners.push({listener:listener,once:false});sub.start();return this}async once(event,listener){const sub=await getSub(this,event);sub.listeners.push({listener:listener,once:true});sub.start();return this}async emit(event,...args){return await emit(this,event,args,null)}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}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}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}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}async addListener(event,listener){return await this.on(event,listener)}async removeListener(event,listener){return await this.off(event,listener)}static buildClass(abi){class CustomContract extends BaseContract{constructor(address,runner=null){super(address,abi,runner)}}return CustomContract}static from(target,abi,runner=null){const contract=new this(target,abi,runner);return contract}}function _ContractBase(){return BaseContract}class Contract extends _ContractBase(){}class ContractFactory{interface;bytecode;runner;constructor(abi,bytecode,runner){const iface=Interface.from(abi);if(bytecode instanceof Uint8Array){bytecode=hexlify(logger.getBytes(bytecode))}else{if(typeof bytecode==="object"){bytecode=bytecode.object}if(bytecode.substring(0,2)!=="0x"){bytecode="0x"+bytecode}bytecode=hexlify(logger.getBytes(bytecode))}defineProperties(this,{bytecode:bytecode,interface:iface,runner:runner||null})}async getDeployTransaction(...args){let overrides={};const fragment=this.interface.deploy;if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop())}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({},overrides,{data:data})}async deploy(...args){const tx=await this.getDeployTransaction(...args);if(!this.runner||typeof this.runner.sendTransaction!=="function"){return logger.throwError("factory runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"})}const sentTx=await this.runner.sendTransaction(tx);const address=getCreateAddress(sentTx);return new BaseContract(address,this.interface,this.runner,sentTx)}connect(runner){return new ContractFactory(this.interface,this.bytecode,runner)}static fromSolidity(output,runner){if(output==null){logger.throwArgumentError("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)}}const subsChrs=" !#$%&'()*+,-./<=>?@[]^_`{|}~";const Word=/^[a-z]*$/i;function unfold(words,sep){let initial=97;return words.reduce((accum,word)=>{if(word===sep){initial++}else if(word.match(Word)){accum.push(String.fromCharCode(initial)+word)}else{initial=97;accum.push(word)}return accum},[])}function decode(data,subs){for(let i=subsChrs.length-1;i>=0;i--){data=data.split(subsChrs[i]).join(subs.substring(2*i,2*i+2))}const clumps=[];const leftover=data.replace(/(:|([0-9])|([A-Z][a-z]*))/g,(all,item,semi,word)=>{if(semi){for(let i=parseInt(semi);i>=0;i--){clumps.push(";")}}else{clumps.push(item.toLowerCase())}return""});if(leftover){throw new Error(`leftovers: ${JSON.stringify(leftover)}`)}return unfold(unfold(clumps,";"),":")}function decodeOwl(data){assertArgument(data[0]==="0","unsupported auwl data","data",data);return decode(data.substring(1+2*subsChrs.length),data.substring(1,1+2*subsChrs.length))}class Wordlist{locale;constructor(locale){defineProperties(this,{locale:locale})}split(mnemonic){return mnemonic.toLowerCase().split(/ +/g)}join(words){return words.join(" ")}}class WordlistOwl extends Wordlist{#data;#checksum;constructor(locale,data,checksum){super(locale);this.#data=data;this.#checksum=checksum;this.#words=null}get _data(){return this.#data}_decodeWords(){return decodeOwl(this.#data)}#words;#loadWords(){if(this.#words==null){const words=this._decodeWords();const checksum=id(words.join("\n")+"\n");if(checksum!==this.#checksum){throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`)}this.#words=words}return this.#words}getWord(index){const words=this.#loadWords();if(index<0||index>=words.length){logger.throwArgumentError(`invalid word index: ${index}`,"index",index)}return words[index]}getWordIndex(word){return this.#loadWords().indexOf(word)}}const words="0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzy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ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO";const checksum="0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60";class LangEn extends WordlistOwl{constructor(){super("en",words,checksum)}}const langEn=new LangEn;function getUpperMask(bits){return(1<24){logger.throwArgumentError("invalid mnemonic length","mnemonic","[ REDACTED ]")}const entropy=new Uint8Array(Math.ceil(11*words.length/8));let offset=0;for(let i=0;i>3]|=1<<7-offset%8}offset++}}const entropyBits=32*words.length/3;const checksumBits=words.length/3;const checksumMask=getUpperMask(checksumBits);const checksum=logger.getBytes(sha256(entropy.slice(0,entropyBits/8)))[0]&checksumMask;if(checksum!==(entropy[entropy.length-1]&checksumMask)){logger.throwArgumentError("invalid mnemonic checksum","mnemonic","[ REDACTED ]")}return hexlify(entropy.slice(0,entropyBits/8))}function entropyToMnemonic(entropy,wordlist=langEn){if(entropy.length%4||entropy.length<16||entropy.length>32){logger.throwArgumentError("invalid entropy size","entropy","[ REDACTED ]")}if(wordlist==null){wordlist=langEn}const indices=[0];let remainingBits=11;for(let i=0;i8){indices[indices.length-1]<<=8;indices[indices.length-1]|=entropy[i];remainingBits-=8}else{indices[indices.length-1]<<=remainingBits;indices[indices.length-1]|=entropy[i]>>8-remainingBits;indices.push(entropy[i]&getLowerMask(8-remainingBits));remainingBits+=3}}const checksumBits=entropy.length/4;const checksum=parseInt(sha256(entropy).substring(2,4),16)&getUpperMask(checksumBits);indices[indices.length-1]<<=checksumBits;indices[indices.length-1]|=checksum>>8-checksumBits;return wordlist.join(indices.map(index=>wordlist.getWord(index)))}const _guard$1={};class Mnemonic{phrase;password;wordlist;entropy;constructor(guard,entropy,phrase,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=langEn}logger.assertPrivate(guard,_guard$1,"Mnemonic");defineProperties(this,{phrase:phrase,password:password,wordlist:wordlist,entropy:entropy})}computeSeed(){const salt=toUtf8Bytes("mnemonic"+this.password,"NFKD");return pbkdf2(toUtf8Bytes(this.phrase,"NFKD"),salt,2048,64,"sha512")}static fromPhrase(phrase,password,wordlist){const entropy=mnemonicToEntropy(phrase,wordlist);phrase=entropyToMnemonic(logger.getBytes(entropy),wordlist);return new Mnemonic(_guard$1,entropy,phrase,password,wordlist)}static fromEntropy(_entropy,password,wordlist){const entropy=logger.getBytes(_entropy,"entropy");const phrase=entropyToMnemonic(entropy,wordlist);return new Mnemonic(_guard$1,hexlify(entropy),phrase,password,wordlist)}static entropyToPhrase(_entropy,wordlist){const entropy=logger.getBytes(_entropy,"entropy");return entropyToMnemonic(entropy,wordlist)}static phraseToEntropy(phrase,wordlist){return mnemonicToEntropy(phrase,wordlist)}static isValidMnemonic(phrase,wordlist){try{mnemonicToEntropy(phrase,wordlist);return true}catch(error){}return false}}class BaseWallet extends AbstractSigner{address;#signingKey;constructor(privateKey,provider){super(provider);this.#signingKey=privateKey;const address=computeAddress(this.signingKey.publicKey);defineProperties(this,{address:address})}get signingKey(){return this.#signingKey}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(provider){return new BaseWallet(this.#signingKey,provider)}async signTransaction(_tx){const tx=Object.assign({},_tx,await resolveProperties({to:_tx.to?resolveAddress(_tx.to,this.provider):undefined,from:_tx.from?resolveAddress(_tx.from,this.provider):undefined}));if(tx.from!=null){if(getAddress(tx.from)!==this.address){logger.throwArgumentError("transaction from address mismatch","tx.from",_tx.from)}delete tx.from}const btx=Transaction.from(tx);btx.signature=this.signingKey.sign(btx.unsignedHash);return btx.serialized}async signMessage(message){return this.signingKey.sign(hashMessage(message)).serialized}async signTypedData(domain,types,value){const populated=await TypedDataEncoder.resolveNames(domain,types,value,async name=>{if(this.provider==null){return logger.throwError("cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:name}})}const address=await this.provider.resolveName(name);if(address==null){return logger.throwError("unconfigured ENS name","UNCONFIGURED_NAME",{value:name})}return address});return this.signingKey.sign(TypedDataEncoder.hash(populated.domain,types,populated.value)).serialized}}const defaultPath$1="m/44'/60'/0'/0/0";const MasterSecret=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]);const HardenedBit=2147483648;const N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const Nibbles="0123456789abcdef";function zpad$1(value,length){let result="";while(value){result=Nibbles[value%16]+result;value=Math.trunc(value/16)}while(result.length=0;i-=8){data[33+(i>>3)]=index>>24-i&255}const I=logger.getBytes(computeHmac("sha512",chainCode,data));return{IL:I.slice(0,32),IR:I.slice(32)}}function derivePath(node,path){const components=path.split("/");if(components.length===0||components[0]==="m"&&node.depth!==0){throw new Error("invalid path - "+path)}if(components[0]==="m"){components.shift()}let result=node;for(let i=0;i=HardenedBit){throw new Error("invalid path index - "+component)}result=result.deriveChild(HardenedBit+index)}else if(component.match(/^[0-9]+$/)){const index=parseInt(component);if(index>=HardenedBit){throw new Error("invalid path index - "+component)}result=result.deriveChild(index)}else{throw new Error("invalid path component - "+component)}}return result}class HDNodeWallet extends BaseWallet{publicKey;fingerprint;parentFingerprint;mnemonic;chainCode;path;index;depth;constructor(guard,signingKey,parentFingerprint,chainCode,path,index,depth,mnemonic,provider){super(signingKey,provider);logger.assertPrivate(guard,_guard,"HDNodeWallet");defineProperties(this,{publicKey:signingKey.compressedPublicKey});const fingerprint=dataSlice(ripemd160(sha256(this.publicKey)),0,4);defineProperties(this,{parentFingerprint:parentFingerprint,fingerprint:fingerprint,chainCode:chainCode,path:path,index:index,depth:depth});defineProperties(this,{mnemonic:mnemonic})}connect(provider){return new HDNodeWallet(_guard,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,provider)}get extendedKey(){if(this.depth>=256){throw new Error("Depth too large!")}return encodeBase58Check(concat(["0x0488ADE4",zpad$1(this.depth,1),this.parentFingerprint,zpad$1(this.index,4),this.chainCode,concat(["0x00",this.privateKey])]))}hasPath(){return this.path!=null}neuter(){return new HDNodeVoidWallet(_guard,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(_index){const index=logger.getNumber(_index,"index");if(index>4294967295){throw new Error("invalid index - "+String(index))}let path=this.path;if(path){path+="/"+(index&~HardenedBit);if(index&HardenedBit){path+="'"}}const{IR,IL}=ser_I(index,this.chainCode,this.publicKey,this.privateKey);const ki=new SigningKey(toHex((toBigInt(IL)+BigInt(this.privateKey))%N,32));return new HDNodeWallet(_guard,ki,this.fingerprint,hexlify(IR),path,index,this.depth+1,this.mnemonic,this.provider)}derivePath(path){return derivePath(this,path)}static#fromSeed(_seed,mnemonic){const seed=logger.getBytes(_seed,"seed");if(seed.length<16||seed.length>64){throw new Error("invalid seed")}const I=logger.getBytes(computeHmac("sha512",MasterSecret,seed));const signingKey=new SigningKey(hexlify(I.slice(0,32)));return new HDNodeWallet(_guard,signingKey,"0x00000000",hexlify(I.slice(32)),"m",0,0,mnemonic,null)}static fromSeed(seed){return HDNodeWallet.#fromSeed(seed,null)}static fromPhrase(phrase,password="",path=defaultPath$1,wordlist=langEn){if(!path){path=defaultPath$1}const mnemonic=Mnemonic.fromPhrase(phrase,password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromMnemonic(mnemonic,path=defaultPath$1){if(!path){path=defaultPath$1}return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromExtendedKey(extendedKey){const bytes=logger.getBytes(decodeBase58(extendedKey));if(bytes.length!==82||encodeBase58Check(bytes.slice(0,78))!==extendedKey){logger.throwArgumentError("invalid extended key","extendedKey","[ REDACTED ]")}const depth=bytes[4];const parentFingerprint=hexlify(bytes.slice(5,9));const index=parseInt(hexlify(bytes.slice(9,13)).substring(2),16);const chainCode=hexlify(bytes.slice(13,45));const key=bytes.slice(45,78);switch(hexlify(bytes.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const publicKey=hexlify(key);return new HDNodeVoidWallet(_guard,computeAddress(publicKey),publicKey,parentFingerprint,chainCode,null,index,depth,null)}case"0x0488ade4":case"0x04358394 ":if(key[0]!==0){break}return new HDNodeWallet(_guard,new SigningKey(key.slice(1)),parentFingerprint,chainCode,null,index,depth,null,null)}return logger.throwArgumentError("invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(password="",path=defaultPath$1,wordlist=langEn){if(!path){path=defaultPath$1}const mnemonic=Mnemonic.fromEntropy(randomBytes(16),password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}}class HDNodeVoidWallet extends VoidSigner{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(guard,address,publicKey,parentFingerprint,chainCode,path,index,depth,provider){super(address,provider);logger.assertPrivate(guard,_guard,"HDNodeVoidWallet");defineProperties(this,{publicKey:publicKey});const fingerprint=dataSlice(ripemd160(sha256(publicKey)),0,4);defineProperties(this,{publicKey:publicKey,fingerprint:fingerprint,parentFingerprint:parentFingerprint,chainCode:chainCode,path:path,index:index,depth:depth})}connect(provider){return new HDNodeVoidWallet(_guard,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,provider)}get extendedKey(){if(this.depth>=256){throw new Error("Depth too large!")}return encodeBase58Check(concat(["0x0488B21E",zpad$1(this.depth,1),this.parentFingerprint,zpad$1(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return this.path!=null}deriveChild(_index){const index=logger.getNumber(_index,"index");if(index>4294967295){throw new Error("invalid index - "+String(index))}let path=this.path;if(path){path+="/"+(index&~HardenedBit);if(index&HardenedBit){path+="'"}}const{IR,IL}=ser_I(index,this.chainCode,this.publicKey,null);const Ki=SigningKey._addPoints(IL,this.publicKey,true);const address=computeAddress(Ki);return new HDNodeVoidWallet(_guard,address,Ki,this.fingerprint,hexlify(IR),path,index,this.depth+1,this.provider)}derivePath(path){return derivePath(this,path)}}class HDNodeWalletManager{#root;constructor(phrase,password="",path="m/44'/60'/0'/0",locale=langEn){this.#root=HDNodeWallet.fromPhrase(phrase,password,path,locale)}getSigner(index=0){return this.#root.deriveChild(index)}}function getAccountPath(_index){const index=logger.getNumber(_index,"index");if(index<0||index>=HardenedBit){logger.throwArgumentError("invalid account index","index",index)}return`m/44'/60'/${index}'/0/0`}var __classPrivateFieldSet$4=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet$4=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _AES_key,_AES_Kd,_AES_Ke;const numberOfRounds={16:10,24:12,32:14};const rcon=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145];const S=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22];const Si=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125];const T1=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986];const T2=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766];const T3=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126];const T4=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436];const T5=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890];const T6=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935];const T7=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600];const T8=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480];const U1=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795];const U2=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855];const U3=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150];const U4=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function convertToInt32(bytes){const result=[];for(let i=0;i>2;__classPrivateFieldGet$4(this,_AES_Ke,"f")[index][i%4]=tk[i];__classPrivateFieldGet$4(this,_AES_Kd,"f")[rounds-index][i%4]=tk[i]}let rconpointer=0;let t=KC,tt;while(t>16&255]<<24^S[tt>>8&255]<<16^S[tt&255]<<8^S[tt>>24&255]^rcon[rconpointer]<<24;rconpointer+=1;if(KC!=8){for(let i=1;i>8&255]<<8^S[tt>>16&255]<<16^S[tt>>24&255]<<24;for(let i=KC/2+1;i>2;c=t%4;__classPrivateFieldGet$4(this,_AES_Ke,"f")[r][c]=tk[i];__classPrivateFieldGet$4(this,_AES_Kd,"f")[rounds-r][c]=tk[i++];t++}}for(let r=1;r>24&255]^U2[tt>>16&255]^U3[tt>>8&255]^U4[tt&255]}}}get key(){return __classPrivateFieldGet$4(this,_AES_key,"f").slice()}encrypt(plaintext){if(plaintext.length!=16){throw new TypeError("invalid plaintext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$4(this,_AES_Ke,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(plaintext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$4(this,_AES_Ke,"f")[0][i]}for(let r=1;r>24&255]^T2[t[(i+1)%4]>>16&255]^T3[t[(i+2)%4]>>8&255]^T4[t[(i+3)%4]&255]^__classPrivateFieldGet$4(this,_AES_Ke,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$4(this,_AES_Ke,"f")[rounds][i];result[4*i]=(S[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(S[t[(i+1)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(S[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(S[t[(i+3)%4]&255]^tt)&255}return result}decrypt(ciphertext){if(ciphertext.length!=16){throw new TypeError("invalid ciphertext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$4(this,_AES_Kd,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(ciphertext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$4(this,_AES_Kd,"f")[0][i]}for(let r=1;r>24&255]^T6[t[(i+3)%4]>>16&255]^T7[t[(i+2)%4]>>8&255]^T8[t[(i+1)%4]&255]^__classPrivateFieldGet$4(this,_AES_Kd,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$4(this,_AES_Kd,"f")[rounds][i];result[4*i]=(Si[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(Si[t[(i+3)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(Si[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(Si[t[(i+1)%4]&255]^tt)&255}return result}}_AES_key=new WeakMap,_AES_Kd=new WeakMap,_AES_Ke=new WeakMap;class ModeOfOperation{constructor(name,key,cls){if(cls&&!(this instanceof cls)){throw new Error(`${name} must be instantiated with "new"`)}Object.defineProperties(this,{aes:{enumerable:true,value:new AES(key)},name:{enumerable:true,value:name}})}}var __classPrivateFieldSet$3=undefined&&undefined.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet$3=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _CBC_iv,_CBC_lastBlock;class CBC extends ModeOfOperation{constructor(key,iv){super("ECC",key,CBC);_CBC_iv.set(this,void 0);_CBC_lastBlock.set(this,void 0);if(iv){if(iv.length%16){throw new TypeError("invalid iv size (must be 16 bytes)")}__classPrivateFieldSet$3(this,_CBC_iv,new Uint8Array(iv),"f")}else{__classPrivateFieldSet$3(this,_CBC_iv,new Uint8Array(16),"f")}__classPrivateFieldSet$3(this,_CBC_lastBlock,this.iv,"f")}get iv(){return new Uint8Array(__classPrivateFieldGet$3(this,_CBC_iv,"f"))}encrypt(plaintext){if(plaintext.length%16){throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)")}const ciphertext=new Uint8Array(plaintext.length);for(let i=0;iNumber.MAX_SAFE_INTEGER){throw new TypeError("invalid counter initial integer value")}for(let index=15;index>=0;--index){__classPrivateFieldGet$1(this,_CTR_counter,"f")[index]=value%256;value=Math.floor(value/256)}}setCounterBytes(value){if(value.length!==16){throw new TypeError("invalid counter initial Uint8Array value length")}__classPrivateFieldGet$1(this,_CTR_counter,"f").set(value)}increment(){for(let i=15;i>=0;i--){if(__classPrivateFieldGet$1(this,_CTR_counter,"f")[i]===255){__classPrivateFieldGet$1(this,_CTR_counter,"f")[i]=0}else{__classPrivateFieldGet$1(this,_CTR_counter,"f")[i]++;break}}}encrypt(plaintext){var _a,_b;const crypttext=new Uint8Array(plaintext);for(let i=0;i16){throw new TypeError("PKCS#7 padding byte out of range")}const length=data.length-padder;for(let i=0;i{setTimeout(()=>{resolve()},duration)})}async function decryptKeystoreJson(json,_password,progress){const data=JSON.parse(json);const password=getPassword(_password);const params=getKdfParams(data);if(params.name==="pbkdf2"){if(progress){progress(0);await stall$1(0)}const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);if(progress){progress(1);await stall$1(0)}return getAccount(data,key)}else if(params.name==="scrypt"){const{salt,N,r,p,dkLen}=params;const key=await scrypt(password,salt,N,r,p,dkLen,progress);return getAccount(data,key)}throw new Error("unreachable")}async function encryptKeystoreJson(account,password,options,progressCallback){if(typeof options==="function"&&!progressCallback){progressCallback=options;options={}}if(!options){options={}}const privateKey=logger.getBytes(account.privateKey,"privateKey");const passwordBytes=getPassword(password);const salt=options.salt!=null?logger.getBytes(options.salt,"options.slat"):randomBytes(32);const iv=options.iv!=null?logger.getBytes(options.iv,"options.iv"):randomBytes(16);if(iv.length!==16){logger.throwArgumentError("invalid options.iv","options.iv",options.iv)}const uuidRandom=options.uuid!=null?logger.getBytes(options.uuid,"options.uuid"):randomBytes(16);if(uuidRandom.length!==16){logger.throwArgumentError("invalid options.uuid","options.uuid",options.iv)}if(uuidRandom.length!==16){throw new Error("invalid uuid")}let N=1<<17,r=8,p=1;if(options.scrypt){if(options.scrypt.N){N=options.scrypt.N}if(options.scrypt.r){r=options.scrypt.r}if(options.scrypt.p){p=options.scrypt.p}}const _key=await scrypt(passwordBytes,salt,N,r,p,64,progressCallback);const key=logger.getBytes(_key);const derivedKey=key.slice(0,16);const macPrefix=key.slice(16,32);const aesCtr=new CTR(derivedKey,iv);const ciphertext=logger.getBytes(aesCtr.encrypt(privateKey));const mac=keccak256(concat([macPrefix,ciphertext]));const data={address:account.address.substring(2).toLowerCase(),id:uuidV4(uuidRandom),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:hexlify(iv).substring(2)},ciphertext:hexlify(ciphertext).substring(2),kdf:"scrypt",kdfparams:{salt:hexlify(salt).substring(2),n:N,dklen:32,p:p,r:r},mac:mac.substring(2)}};if(account.mnemonic){const client=options.client!=null?options.client:`ethers/${version}`;const path=account.mnemonic.path||defaultPath;const locale=account.mnemonic.locale||"en";const mnemonicKey=key.slice(32,64);const entropy=logger.getBytes(account.mnemonic.entropy,"account.mnemonic.entropy");const mnemonicIv=randomBytes(16);const mnemonicAesCtr=new CTR(mnemonicKey,mnemonicIv);const mnemonicCiphertext=logger.getBytes(mnemonicAesCtr.encrypt(entropy));const now=new Date;const timestamp=now.getUTCFullYear()+"-"+zpad(now.getUTCMonth()+1,2)+"-"+zpad(now.getUTCDate(),2)+"T"+zpad(now.getUTCHours(),2)+"-"+zpad(now.getUTCMinutes(),2)+"-"+zpad(now.getUTCSeconds(),2)+".0Z";const gethFilename="UTC--"+timestamp+"--"+data.address;data["x-ethers"]={client:client,gethFilename:gethFilename,path:path,locale:locale,mnemonicCounter:hexlify(mnemonicIv).substring(2),mnemonicCiphertext:hexlify(mnemonicCiphertext).substring(2),version:"0.1"}}return JSON.stringify(data)}function tryWallet(value){try{if(!value||!value.signingKey){return null}const key=trySigningKey(value.signingKey);if(key==null||computeAddress(key.publicKey)!==value.address){return null}if(value.mnemonic){const wallet=HDNodeWallet.fromMnemonic(value.mnemonic);if(wallet.privateKey!==key.privateKey){return null}}return value}catch(e){console.log(e)}return null}function tryMnemonic(value){try{if(value==null||typeof value.phrase!=="string"||typeof value.password!=="string"||value.wordlist==null){return null}return HDNodeWallet.fromPhrase(value.phrase,value.password,null,value.wordlist)}catch(error){console.log(error)}return null}function trySigningKey(value){try{if(!value||!isHexString(value.privateKey,32)){return null}const key=value.privateKey;if(SigningKey.computePublicKey(key)!==value.publicKey){return null}return new SigningKey(key)}catch(e){console.log(e)}return null}function stall(duration){return new Promise(resolve=>{setTimeout(()=>{resolve()},duration)})}class Wallet extends BaseWallet{#mnemonic;constructor(key,provider){let signingKey=null;let mnemonic=null;if(typeof key==="string"){signingKey=new SigningKey(key)}if(signingKey==null){const wallet=tryWallet(key);if(wallet){signingKey=wallet.signingKey;mnemonic=wallet.mnemonic||null}}if(signingKey==null){const wallet=tryMnemonic(key);if(wallet){signingKey=wallet.signingKey;mnemonic=wallet.mnemonic||null}}if(signingKey==null){signingKey=trySigningKey(key)}if(signingKey==null){logger.throwArgumentError("invalid key","key","[ REDACTED ]")}super(signingKey,provider);this.#mnemonic=mnemonic}get mnemonic(){return this.#mnemonic}connect(provider){return new Wallet(this,provider)}async encrypt(password,options,progressCallback){throw new Error("TODO")}encryptSync(password,options){throw new Error("TODO")}static async fromEncryptedJson(json,password,progress){let account=null;if(isKeystoreJson(json)){account=await decryptKeystoreJson(json,password,progress)}else if(isCrowdsaleJson(json)){if(progress){progress(0);await stall(0)}account=decryptCrowdsaleJson(json,password);if(progress){progress(1);await stall(0)}}else{return logger.throwArgumentError("invalid JSON wallet","json","[ REDACTED ]")}const wallet=new Wallet(account.privateKey);if(wallet.address!==account.address){logger.throwArgumentError("address/privateKey mismatch","json","[ REDACTED ]")}return wallet}static fromEncryptedJsonSync(json,password){let account=null;if(isKeystoreJson(json)){account=decryptKeystoreJsonSync(json,password)}else if(isCrowdsaleJson(json)){account=decryptCrowdsaleJson(json,password)}else{return logger.throwArgumentError("invalid JSON wallet","json","[ REDACTED ]")}const wallet=new Wallet(account.privateKey);if(wallet.address!==account.address){logger.throwArgumentError("address/privateKey mismatch","json","[ REDACTED ]")}return wallet}static createRandom(provider,password,wordlist){return new Wallet(Mnemonic.fromEntropy(randomBytes(16),password,wordlist),provider)}static fromMnemonic(mnemonic,provider){return new Wallet(mnemonic,provider)}static fromPhrase(phrase,provider,password="",wordlist){return new Wallet(Mnemonic.fromPhrase(phrase,password,wordlist),provider)}}const wordlists=Object.freeze({en:langEn});const Base64=")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";function decodeBits(width,data){const maxValue=(1<=width){const value=accum>>bits-width;accum&=(1<{const match=accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);assertArgument(match!==null,"internal error parsing accents","accents",accents);let posOffset=0;const positions=decodeBits(parseInt(match[3]),match[4]);const charCode=parseInt(match[2]);const regex=new RegExp(`([${match[1]}])`,"g");words=words.replace(regex,(all,letter)=>{const rem=--positions[posOffset];if(rem===0){letter=String.fromCharCode(letter.charCodeAt(0),charCode);posOffset++}return letter})});return words.split(",")}class WordlistOwlA extends WordlistOwl{#accent;constructor(locale,data,accent,checksum){super(locale,data,checksum);this.#accent=accent}get _accent(){return this.#accent}_decodeWords(){return decodeOwlA(this._data,this._accent)}}var ethers=Object.freeze({__proto__:null,version:version,formatBytes32String:formatBytes32String,parseBytes32String:parseBytes32String,AbiCoder:AbiCoder,defaultAbiCoder:defaultAbiCoder,ConstructorFragment:ConstructorFragment,ErrorFragment:ErrorFragment,EventFragment:EventFragment,Fragment:Fragment,FunctionFragment:FunctionFragment,ParamType:ParamType,checkResultErrors:checkResultErrors,Indexed:Indexed,Interface:Interface,LogDescription:LogDescription,Result:Result,TransactionDescription:TransactionDescription,Typed:Typed,getAddress:getAddress,getIcapAddress:getIcapAddress,getCreateAddress:getCreateAddress,getCreate2Address:getCreate2Address,ZeroAddress:ZeroAddress,NegativeOne:NegativeOne,Zero:Zero,One:One,Two:Two,WeiPerEther:WeiPerEther,MaxUint256:MaxUint256,MinInt256:MinInt256,MaxInt256:MaxInt256,ZeroHash:ZeroHash,EtherSymbol:EtherSymbol,MessagePrefix:MessagePrefix,BaseContract:BaseContract,Contract:Contract,ContractFactory:ContractFactory,ContractEventPayload:ContractEventPayload,ContractTransactionReceipt:ContractTransactionReceipt,ContractTransactionResponse:ContractTransactionResponse,EventLog:EventLog,computeHmac:computeHmac,randomBytes:randomBytes,keccak256:keccak256,ripemd160:ripemd160,sha256:sha256,sha512:sha512,pbkdf2:pbkdf2,scrypt:scrypt,scryptSync:scryptSync,lock:lock,Signature:Signature,SigningKey:SigningKey,id:id,hashMessage:hashMessage,solidityPacked:solidityPacked,solidityPackedKeccak256:solidityPackedKeccak256,solidityPackedSha256:solidityPackedSha256,TypedDataEncoder:TypedDataEncoder,accessListify:accessListify,computeAddress:computeAddress,recoverAddress:recoverAddress,Transaction:Transaction,decodeBase58:decodeBase58,encodeBase58:encodeBase58,isCallException:isCallException,isError:isError,FetchRequest:FetchRequest,FetchResponse:FetchResponse,FixedFormat:FixedFormat,FixedNumber:FixedNumber,formatFixed:formatFixed,parseFixed:parseFixed,assertArgument:assertArgument,Logger:Logger,logger:logger,fromTwos:fromTwos,toTwos:toTwos,mask:mask,toArray:toArray,toBigInt:toBigInt,toHex:toHex,toNumber:toNumber,formatEther:formatEther,parseEther:parseEther,formatUnits:formatUnits,parseUnits:parseUnits,_toEscapedUtf8String:_toEscapedUtf8String,toUtf8Bytes:toUtf8Bytes,toUtf8CodePoints:toUtf8CodePoints,toUtf8String:toUtf8String,Utf8ErrorFuncs:Utf8ErrorFuncs,decodeRlp:decodeRlp,encodeRlp:encodeRlp,defaultPath:defaultPath$1,getAccountPath:getAccountPath,HDNodeWallet:HDNodeWallet,HDNodeVoidWallet:HDNodeVoidWallet,HDNodeWalletManager:HDNodeWalletManager,isCrowdsaleJson:isCrowdsaleJson,decryptCrowdsaleJson:decryptCrowdsaleJson,isKeystoreJson:isKeystoreJson,decryptKeystoreJsonSync:decryptKeystoreJsonSync,decryptKeystoreJson:decryptKeystoreJson,encryptKeystoreJson:encryptKeystoreJson,Mnemonic:Mnemonic,Wallet:Wallet,Wordlist:Wordlist,langEn:langEn,LangEn:LangEn,wordlists:wordlists,WordlistOwl:WordlistOwl,WordlistOwlA:WordlistOwlA,FallbackProvider:FallbackProvider,JsonRpcApiProvider:JsonRpcApiProvider,JsonRpcProvider:JsonRpcProvider,JsonRpcSigner:JsonRpcSigner,AlchemyProvider:AlchemyProvider,AnkrProvider:AnkrProvider,CloudflareProvider:CloudflareProvider,EtherscanProvider:EtherscanProvider,InfuraProvider:InfuraProvider,IpcSocketProvider:IpcSocketProvider,SocketProvider:SocketProvider,WebSocketProvider:WebSocketProvider,Network:Network});export{AbiCoder,AlchemyProvider,AnkrProvider,BaseContract,CloudflareProvider,ConstructorFragment,Contract,ContractEventPayload,ContractFactory,ContractTransactionReceipt,ContractTransactionResponse,ErrorFragment,EtherSymbol,EtherscanProvider,EventFragment,EventLog,FallbackProvider,FetchRequest,FetchResponse,FixedFormat,FixedNumber,Fragment,FunctionFragment,HDNodeVoidWallet,HDNodeWallet,HDNodeWalletManager,Indexed,InfuraProvider,Interface,IpcSocketProvider,JsonRpcApiProvider,JsonRpcProvider,JsonRpcSigner,LangEn,LogDescription,Logger,MaxInt256,MaxUint256,MessagePrefix,MinInt256,Mnemonic,NegativeOne,Network,One,ParamType,Result,Signature,SigningKey,SocketProvider,Transaction,TransactionDescription,Two,Typed,TypedDataEncoder,Utf8ErrorFuncs,Wallet,WebSocketProvider,WeiPerEther,Wordlist,WordlistOwl,WordlistOwlA,Zero,ZeroAddress,ZeroHash,_toEscapedUtf8String,accessListify,assertArgument,checkResultErrors,computeAddress,computeHmac,decodeBase58,decodeRlp,decryptCrowdsaleJson,decryptKeystoreJson,decryptKeystoreJsonSync,defaultAbiCoder,defaultPath$1 as defaultPath,encodeBase58,encodeRlp,encryptKeystoreJson,ethers,formatBytes32String,formatEther,formatFixed,formatUnits,fromTwos,getAccountPath,getAddress,getCreate2Address,getCreateAddress,getIcapAddress,hashMessage,id,isCallException,isCrowdsaleJson,isError,isKeystoreJson,keccak256,langEn,lock,logger,mask,parseBytes32String,parseEther,parseFixed,parseUnits,pbkdf2,randomBytes,recoverAddress,ripemd160,scrypt,scryptSync,sha256,sha512,solidityPacked,solidityPackedKeccak256,solidityPackedSha256,toArray,toBigInt,toHex,toNumber,toTwos,toUtf8Bytes,toUtf8CodePoints,toUtf8String,version,wordlists}; \ No newline at end of file diff --git a/dist/wordlists-extra.js b/dist/wordlists-extra.js new file mode 100644 index 000000000..ec73ed7d7 --- /dev/null +++ b/dist/wordlists-extra.js @@ -0,0 +1,1344 @@ +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== 'boolean') + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new TypeError('Expected Uint8Array'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') + throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +const assert = { + number, + bool, + bytes, + hash, + exists, + output, +}; + +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (h, l) => l; +const rotr32L = (h, l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +// There is almost no big endian hardware, but js typed arrays uses platform specific endianness. +// So, just to be sure not to corrupt anything. +if (!isLE) + throw new Error('Non little-endian hardware is not supported'); +Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); +function utf8ToBytes(str) { + if (typeof str !== 'string') { + throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); + } + return new TextEncoder().encode(str); +} +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + if (!(data instanceof Uint8Array)) + throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); + return data; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashConstructor) { + const hashC = (message) => hashConstructor().update(toBytes(message)).digest(); + const tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashConstructor(); + return hashC; +} +function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} + +// Various per round constants calculations +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(0x71); +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = u64.split(_SHA3_IOTA, true); +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => s > 32 ? u64.rotlBH(h, l, s) : u64.rotlSH(h, l, s); +const rotlL = (h, l, s) => s > 32 ? u64.rotlBL(h, l, s) : u64.rotlSL(h, l, s); +// Same as keccakf1600, but allows to skip some rounds +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) + B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + // Can be passed from user as dkLen + assert.number(outputLen); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error('Sha3 supports only keccak-f1600 function'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + assert.exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // Do the padding + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + assert.exists(this, false); + assert.bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + assert.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + assert.output(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); +gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ +gen(0x06, 136, 256 / 8); +gen(0x06, 104, 384 / 8); +gen(0x06, 72, 512 / 8); +gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ +const keccak_256 = gen(0x01, 136, 256 / 8); +gen(0x01, 104, 384 / 8); +gen(0x01, 72, 512 / 8); +const genShake = (suffix, blockLen, outputLen) => wrapConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)); +genShake(0x1f, 168, 128 / 8); +genShake(0x1f, 136, 256 / 8); + +const version = "6.0.0-beta-exports.0"; + +const LogLevels = ["debug", "info", "warning", "error", "off"]; +const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { + try { + // General test for normalize + /* c8 ignore start */ + if ("test".normalize(form) !== "test") { + throw new Error("bad"); + } + ; + /* c8 ignore stop */ + if (form === "NFD") { + const check = String.fromCharCode(0xe9).normalize("NFD"); + const expected = String.fromCharCode(0x65, 0x0301); + /* c8 ignore start */ + if (check !== expected) { + throw new Error("broken"); + } + /* c8 ignore stop */ + } + accum.push(form); + } + catch (error) { } + return accum; +}, []); +function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, writable: false, value, + }); +} +// IEEE 754 support 53-bits of mantissa +const maxValue = 0x1fffffffffffff; +// The type of error to use for various error codes +const ErrorConstructors = {}; +ErrorConstructors.INVALID_ARGUMENT = TypeError; +ErrorConstructors.NUMERIC_FAULT = RangeError; +ErrorConstructors.BUFFER_OVERRUN = RangeError; +class Logger { + version; + #logLevel; + constructor(version) { + defineReadOnly(this, "version", version || "_"); + this.#logLevel = 1; + } + get logLevel() { + return LogLevels[this.#logLevel]; + } + set logLevel(value) { + const logLevel = LogLevels.indexOf(value); + if (logLevel == null) { + this.throwArgumentError("invalid logLevel", "logLevel", value); + } + this.#logLevel = logLevel; + } + makeError(message, code, info) { + { + const details = []; + if (info) { + for (const key in info) { + const value = (info[key]); + try { + details.push(key + "=" + JSON.stringify(value)); + } + catch (error) { + details.push(key + "=[could not serialize object]"); + } + } + } + details.push(`code=${code}`); + details.push(`version=${this.version}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; + } + } + const create = ErrorConstructors[code] || Error; + const error = (new create(message)); + defineReadOnly(error, "code", code); + if (info) { + for (const key in info) { + defineReadOnly(error, key, (info[key])); + } + } + return error; + } + throwError(message, code, info) { + throw this.makeError(message, code, info); + } + throwArgumentError(message, name, value) { + return this.throwError(message, "INVALID_ARGUMENT", { + argument: name, + value: value + }); + } + assertNormalize(form) { + if (_normalizeForms.indexOf(form) === -1) { + this.throwError("platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", info: { form } + }); + } + } + assertPrivate(givenGuard, guard, className = "") { + if (givenGuard !== guard) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; + } + this.throwError(`private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation + }); + } + } + assertArgumentCount(count, expectedCount, message = "") { + if (message) { + message = ": " + message; + } + if (count < expectedCount) { + this.throwError("missing arguemnt" + message, "MISSING_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguemnts" + message, "UNEXPECTED_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + } + #getBytes(value, name, copy) { + if (value instanceof Uint8Array) { + if (copy) { + return new Uint8Array(value); + } + return value; + } + if (typeof (value) === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset = 2; + for (let i = 0; i < result.length; i++) { + result[i] = parseInt(value.substring(offset, offset + 2), 16); + offset += 2; + } + return result; + } + return this.throwArgumentError("invalid BytesLike value", name || "value", value); + } + getBytes(value, name) { + return this.#getBytes(value, name, false); + } + getBytesCopy(value, name) { + return this.#getBytes(value, name, true); + } + getNumber(value, name) { + switch (typeof (value)) { + case "bigint": + if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return Number(value); + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return value; + case "string": + try { + return this.getNumber(BigInt(value), name); + } + catch (e) { + this.throwArgumentError(`invalid numeric string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid numeric value", name || "value", value); + } + getBigInt(value, name) { + switch (typeof (value)) { + case "bigint": return value; + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return BigInt(value); + case "string": + try { + return BigInt(value); + } + catch (e) { + this.throwArgumentError(`invalid BigNumberish string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid BigNumberish value", name || "value", value); + } + #log(_logLevel, args) { + const logLevel = LogLevels.indexOf(_logLevel); + if (logLevel === -1) { + this.throwArgumentError("invalid log level name", "logLevel", _logLevel); + } + if (this.#logLevel > logLevel) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this.#log("debug", args); + } + info(...args) { + this.#log("info", args); + } + warn(...args) { + this.#log("warning", args); + } +} +const logger = new Logger(version); +function assertArgument(check, message, name, value) { + if (!check) { + logger.throwArgumentError(message, name, value); + } +} + +const HexCharacters = "0123456789abcdef"; +function hexlify(data) { + const bytes = logger.getBytes(data); + let result = "0x"; + for (let i = 0; i < bytes.length; i++) { + const v = bytes[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; +} + +/* +export interface CancellablePromise extends Promise { + cancel(): Promise; +} +export type IsCancelled = () => Promise; + +export function createPromise(resolve: (isCancelled: IsCancelled, (result: T) => void) => void, reject: (error: Error) => void, isCancelled: IsCancelled): CancellablePromise { + let cancelled = false; + + const promise = new Promise((resolve, reject) => { + + }); + + (>promise).cancel = function() { + cancelled = true; + }; + + return (>promise); +} +*/ +/* +export class A implements Freezable { + foo: number; + constructor(foo: number) { + this.foo = foo; + } + freeze(): Frozen { + Object.freeze(this); + return this; + } + clone(): A { + return new A(this.foo); + } +} + +export class B implements Freezable { + a: A; + constructor(a: A) { + this.a = a; + } + freeze(): Frozen { + this.a.freeze(); + Object.freeze(this); + return this; + } + clone(): B { + return new B(this.a); + } +} + +export function test() { + const a = new A(123); + const b = new B(a); + b.a = new A(234); + const b2 = b.freeze(); + b2.a.foo = 123; // = a; +} +*/ +function checkType(value, type) { + const types = type.split("|").map(t => t.trim()); + for (let i = 0; i < types.length; i++) { + switch (type) { + case "any": + return; + case "boolean": + case "number": + case "string": + if (typeof (value) === type) { + return; + } + } + } + throw new Error("invalid value for type"); +} +function defineProperties(target, values, types, defaults) { + for (let key in values) { + let value = values[key]; + const fallback = (defaults ? defaults[key] : undefined); + if (fallback !== undefined) { + value = fallback; + } + else { + const type = (types ? types[key] : null); + if (type) { + checkType(value, type); + } + } + Object.defineProperty(target, key, { enumerable: true, value, writable: false }); + } +} + +function errorFunc(reason, offset, bytes, output, badCodepoint) { + return logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === "OVERRUN") { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === "OVERLONG") { + output.push((badCodepoint != null) ? badCodepoint : -1); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes); +} +// Common error handing strategies +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + const bytes = logger.getBytes(_bytes, "bytes"); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result); + } + else { + i += onError("BAD_PREFIX", i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError("OVERRUN", i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError("MISSING_CONTINUE", i, bytes, result); + res = null; + break; + } + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +function toUtf8Bytes(str, form) { + if (form != null) { + logger.assertNormalize(form); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return new Uint8Array(result); +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} + +let locked = false; +const _keccak256 = function (data) { + return keccak_256(data); +}; +let __keccak256 = _keccak256; +function keccak256(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__keccak256(data)); +} +keccak256._ = _keccak256; +keccak256.lock = function () { locked = true; }; +keccak256.register = function (func) { + if (locked) { + throw new TypeError("keccak256 is locked"); + } + __keccak256 = func; +}; +Object.freeze(keccak256); + +function id(value) { + return keccak256(toUtf8Bytes(value)); +} + +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words, sep) { + let initial = 97; + return words.reduce((accum, word) => { + if (word === sep) { + initial++; + } + else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } + else { + initial = 97; + accum.push(word); + } + return accum; + }, []); +} +function decode(data, subs) { + // Replace all the substitutions with their expanded form + for (let i = subsChrs.length - 1; i >= 0; i--) { + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + } + // Get all tle clumps; each suffix, first-increment and second-increment + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { + if (semi) { + for (let i = parseInt(semi); i >= 0; i--) { + clumps.push(";"); + } + } + else { + clumps.push(item.toLowerCase()); + } + return ""; + }); + /* c8 ignore start */ + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); + } + /* c8 ignore stop */ + return unfold(unfold(clumps, ";"), ":"); +} +function decodeOwl(data) { + assertArgument(data[0] === "0", "unsupported auwl data", "data", data); + return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); +} + +class Wordlist { + locale; + constructor(locale) { + defineProperties(this, { locale }); + } + // Subclasses may override this + split(mnemonic) { + return mnemonic.toLowerCase().split(/ +/g); + } + // Subclasses may override this + join(words) { + return words.join(" "); + } +} + +// Use the encode-latin.js script to create the necessary +class WordlistOwl extends Wordlist { + #data; + #checksum; + constructor(locale, data, checksum) { + super(locale); + this.#data = data; + this.#checksum = checksum; + this.#words = null; + } + get _data() { return this.#data; } + _decodeWords() { + return decodeOwl(this.#data); + } + #words; + #loadWords() { + if (this.#words == null) { + const words = this._decodeWords(); + // Verify the computed list matches the official list + const checksum = id(words.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== this.#checksum) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); + } + /* c8 ignore stop */ + this.#words = words; + } + return this.#words; + } + getWord(index) { + const words = this.#loadWords(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return this.#loadWords().indexOf(word); + } +} + +const words$4 = "0itatkastcenaovo$taouleraeki&chor*teci%enbalodaeladet'!Chn=0Di#%E%^1Resa2Rese3CeT'#0EjKohol0Pu)%0A&sDul#Ekdo)Ke)Ti#Ul|3}aOgan%0FaltI$@tPi,%TmaTronom0LasL{i#Ol0Tobus4Yl:B#}R'?TaUb_U/!U^U+Ur!Xer2A^v#Ambo,An#AtrEp)Ike)KoLohOnzOskevUn{#Usin#Z^Zy2Bl.Bn|})D _D#D'aF{Jar(Kv?LdokLvaN^NkrRzaTikVolZola3D+tL.T'#0Ukot:PartRev&3DrDu+J/JnLaLerLkemLn?N.Nn(N'#NtrumNzZ(2O&2KolivUv!4It_N(0Dn(Ke)KrPot0Ak~AlIkRkot2Kli$a:L-oRe[T_Tum1E,1B!a}'#Cib_Fic Fla%KlKr{Mokr!PreseRbyS#T-tiv3Kob,zKt|O^P]mSkSp+jV`]Vo/2AhaOuhoUhopis1Es0BroByt-C@t}ut DnesH+dHo^H,JemJn?Kl`KolaKtAzeDolObn(OgerieOzdSn(T Z(2B@}'noD-HaH'#S SnoT(0Oj?Or>2Nam :9O]gOnomie0EktronIpsa0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eoh,D.D+LaN?S{Tal aZeZ #0Ezd0L`Us0Aj#AkAs>EvoHk(IvN'#Oup!1Uc|Uk0DaDiv(Doz&kD$voJ@skyJ&JskoLantL[L LnoSk'#Zid]Z'&0Ravo1Ab>A%tAhA)Ba}o+kH!StvaTu+0Ad T*p Tup0Ip4Bav Br!}|D!D,Fot H+d!H~Hod H,d Hub Jasn J{Jm=K]p Kon!L-!Maz!Mez Miz{Mys+tNe/!Nik!Nut P`!Pl! P,v Pu$ Raz R'n!Rv!Sl' SokoS)v Su~Syp!Tas Tes!Tr! Vi~Vol!Vrh_Zdob Zn!0AduBud }op DJ{Ji$ K+p!K*p Lep Mez Mot!Mys+tNe/!Nik!Pl! Poj Ps!Raz S)v Su~Taj Temn Tk~Ujm=Val Ve+tVin Vol!Vrt!Zvon 0Av RusuUd|Yt-1A+#ArmaAtn(IvoOb RojVihYm`]0L@.ManM.Pt!Z`uZdola2At Lt~Lubo#Ot' Ru[0MaMn?0Emn 0Lam!Oum!R!#Umav#0AtoEh#O[OmO$Ozvyk0Ap|ArAt-IjeIz{Ocn Odr!Rzl.Ut|0AkAl(Am@!Ovu0B,z Tav Ub-Ufa+0Lod Omal RavaR( Rud#Rvu1A^An C`]N (NoOv&Y/l Zav(1I/aR! 0B'.Br0Ed~EnkuEs_aOnR!Uk'odYk"; +const checksum$4 = "0x25f44555f4af25b51a711136e1c7d6e50ce9f8917d39d6b1f076b2bb4d2fac1a"; +class LangCz extends WordlistOwl { + constructor() { super("cz", words$4, checksum$4); } +} +const langCz = new LangCz(); + +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +function decodeBits(width, data) { + const maxValue = (1 << width) - 1; + const result = []; + let accum = 0, bits = 0, flood = 0; + for (let i = 0; i < data.length; i++) { + // Accumulate 6 bits of data + accum = ((accum << 6) | Base64.indexOf(data[i])); + bits += 6; + // While we have enough for a word... + while (bits >= width) { + // ...read the word + const value = (accum >> (bits - width)); + accum &= (1 << (bits - width)) - 1; + bits -= width; + // A value of 0 indicates we exceeded maxValue, it + // floods over into the next value + if (value === 0) { + flood += maxValue; + } + else { + result.push(value + flood); + flood = 0; + } + } + } + return result; +} + +function decodeOwlA(data, accents) { + let words = decodeOwl(data).join(","); + // Inject the accents + accents.split(/,/g).forEach((accent) => { + const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); + assertArgument(match !== null, "internal error parsing accents", "accents", accents); + let posOffset = 0; + const positions = decodeBits(parseInt(match[3]), match[4]); + const charCode = parseInt(match[2]); + const regex = new RegExp(`([${match[1]}])`, "g"); + words = words.replace(regex, (all, letter) => { + const rem = --positions[posOffset]; + if (rem === 0) { + letter = String.fromCharCode(letter.charCodeAt(0), charCode); + posOffset++; + } + return letter; + }); + }); + return words.split(","); +} + +class WordlistOwlA extends WordlistOwl { + #accent; + constructor(locale, data, accent, checksum) { + super(locale, data, checksum); + this.#accent = accent; + } + get _accent() { return this.#accent; } + _decodeWords() { + return decodeOwlA(this._data, this._accent); + } +} + +const words$3 = "0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?N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ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! b) { + return 1; + } + return 0; + } + // Load all the words + for (let length = 3; length <= 9; length++) { + const d = data$2[length - 3]; + for (let offset = 0; offset < d.length; offset += length) { + const word = []; + for (let i = 0; i < length; i++) { + const k = mapping.indexOf(d[offset + i]); + word.push(227); + word.push((k & 0x40) ? 130 : 129); + word.push((k & 0x3f) + 128); + } + wordlist.push(toString(word)); + } + } + wordlist.sort(sortJapanese); + // For some reason kyoku and kiyoku are flipped in node (!!). + // The order SHOULD be: + // - kyoku + // - kiyoku + // This should ignore "if", but that doesn't work here?? + /* c8 ignore start */ + if (hex(wordlist[442]) === KiYoKu && hex(wordlist[443]) === KyoKu) { + const tmp = wordlist[442]; + wordlist[442] = wordlist[443]; + wordlist[443] = tmp; + } + /* c8 ignore stop */ + // Verify the computed list matches the official list + /* istanbul ignore if */ + const checksum = id(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== "0xcb36b09e6baa935787fd762ce65e80b0c6a8dabdfbc3a7f86ac0e2c4fd111600") { + throw new Error("BIP39 Wordlist for ja (Japanese) FAILED"); + } + /* c8 ignore stop */ + _wordlist$2 = wordlist; + return wordlist; +} +class LangJa extends Wordlist { + constructor() { super("ja"); } + getWord(index) { + const words = loadWords$2(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords$2().indexOf(word); + } + split(mnemonic) { + //logger.assertNormalize(); + return mnemonic.split(/(?:\u3000| )+/g); + } + join(words) { + return words.join("\u3000"); + } +} +const langJa = new LangJa(); + +const data$1 = [ + "OYAa", + "ATAZoATBl3ATCT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OTrATMnGT8LhrAZ8GnvFnGnQXHToGgvAcrHTvAXvLl3HbrAZoMXoHgBlFXLg3HgMnFXrSnHgrSb8JUoHn6HT8LgvITvATrJUoJUoLZrRnvJU8HT8Jb8JXvFX8QT8JXvLToJTrJYrQnGnQXJgrJnoATrJnoJU8ScvJnvMnvMXoLTCTLgrJXLTJlRTvQlLbRnJlQYvLbrMb8LnvLbvFn3RnoLdCVSTGZrLeSTvGXCnLg3MnoLn3MToLlrETvMT8SToAl3MbrDU6GTvMb8LX4LhrPlrLXGXCnSToLf8Rg3STrDb8LTrSTvLTHXMnSb3RYLnMnSgOg6ATFg", + "HUDlGnrQXrJTrHgLnrAcJYMb8DULc8LTvFgGnCk3Mg8JbAnLX4QYvFYHnMXrRUoJnGnvFnRlvFTJlQnoSTrBXHXrLYSUJgLfoMT8Se8DTrHbDb", + "AbDl8SToJU8An3RbAb8ST8DUSTrGnrAgoLbFU6Db8LTrMg8AaHT8Jb8ObDl8SToJU8Pb3RlvFYoJl" +]; +const codes$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"; +function getHangul(code) { + if (code >= 40) { + code = code + 168 - 40; + } + else if (code >= 19) { + code = code + 97 - 19; + } + return toUtf8String(new Uint8Array([225, (code >> 6) + 132, (code & 0x3f) + 128])); +} +let _wordlist$1 = null; +function loadWords$1() { + if (_wordlist$1 != null) { + return _wordlist$1; + } + const wordlist = []; + data$1.forEach((data, length) => { + length += 4; + for (let i = 0; i < data.length; i += length) { + let word = ""; + for (let j = 0; j < length; j++) { + word += getHangul(codes$1.indexOf(data[i + j])); + } + wordlist.push(word); + } + }); + wordlist.sort(); + // Verify the computed list matches the official list + /* istanbul ignore if */ + const checksum = id(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== "0xf9eddeace9c5d3da9c93cf7d3cd38f6a13ed3affb933259ae865714e8a3ae71a") { + throw new Error("BIP39 Wordlist for ko (Korean) FAILED"); + } + /* c8 ignore stop */ + _wordlist$1 = wordlist; + return wordlist; +} +class LangKo extends Wordlist { + constructor() { + super("ko"); + } + getWord(index) { + const words = loadWords$1(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords$1().indexOf(word); + } +} +const langKo = new LangKo(); + +const words$1 = "0torea noica!iosorolotaleratelanena%oiadoencotivomai t ca%a0A]Bagl'Bin#E.Is(Oli!Rasi_Rog#0Cade!C[$Cus#E Roba+U 0Ag'Deb{DomeEgu#Eri!IpeOtt&Ul&1Fabi,Fe|Fis(F-n Oris`O(R~$0AveEn.E_,Ganc'I!It&OnismoR>*Rume Uzzo4AbardaA Bat)Ber#BoBumeCeCol>E|Ertu-OdePari!Pe^ Pogg'P)@Pun Ri,1Ab~AchideAgos+Ald~Anc'Atu-AzzoBit)Chiv'D{Eni,G[ GiSoTef%eZil*0Ciu|Col EpsiEtt>Fal I$O/Pir#P)Sagg'SeSolu Sur@TaT[u T%eT-|0Av>EismoOm>O$TesaTiv&Tor$Tr{Tua,0Sil'Str?Tis+To$moTun$0Anz#E!V[i!Vi(Volge!3IoS(Tos+Ttu U,VaVosa3C]FfaLg'LvaNdaNe_,Nig$Nzi=ReRli=Ta3Bi+CiDoR@S]Tan>T^$Zzo*2Acc'AdipoA`An}Avu-E.l/Eve|EzzaIgl?Il/n.Ind&Oc]*O@Onzi=Ul*U$2BboT+di$UffoVet+Vi,2Ass>In~O)2C]Dar@D%eE!n.G$meLl&Lm#Lo!Lpo(L^v#LzaMaMe+M`n@Mo@Mpu.rMuS+n.Ttu-V#2A.!Avat+E#Ede!Emo(Esci+E+Ice I=,IsiIt>OceO=}Os++Uc?,Us}2Ci!Cu*Gi$Ll#Po/R#!R(!R_Sci$S de:DoI$L`+Meri$Nie/N$(Nz&T#Van^Vve)3Bu|C[n'Ci(Cli$Col*C! D%#Fin{FormeG$Leg&Lfi$Lir'L+M[zaNot#Nt)Pos{R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#0Elli!Erv#O@0BbalzoBr'C]r(C?,Da,Ffi|G$Ld#L[M`NdaNe|Nnife)Pi!Ppe(P-Rge!Rpas(Rri(R(R.gg'R_l#Spi)S+T^,0AdaAl/Arge!A /Av[ Azzo/EcieEdi!EgRappoReg#Ridu*Rozz&Ru|Ucc&UfoUp[@0B[t)C](Do!Gger{GoL+$On&PerboPpor Rgel#R)g#Ssur)Tu-0Ag&EdeseEgl'El&Enu Ez?IluppoIs+Izze-Ol+Uot&:Bac]Bul#Cci&Citur$LeLis`$MpoVer=Vo/+Zza3CaCn>Lefo$Me-r'MpoMu N@Pog-foRagg'RoTan'To*Tuban.Z'Zzo<5Cc&L,r&L Mbo/MoNfoNsil/Paz'Po*g?PpaRbaRn&R)L,t+Lo)(Lut&L_/Mpa+Ng&N{(NoN+gg'Nve-Po!Ra$Rc#R?n.S}3Det+DovaDu Ge+,I]*Lc)Li=Llu LoceN#Ndemm?N RaceRba,Rgog=Rif~RoRru}Rt~,Sc~Ssil*S+,Te-$Tri=Tus 3Andan.B-n.C[daChingoCi=nzaDim&Gil?G< Go!LeL/$MiniNc{!O/Pe-Rgo/Ro*goRu,n S](S'5Cche)Fo*LuPpa"; +const checksum$1 = "0x5c1362d88fd4cf614a96f3234941d29f7d37c08c5292fde03bf62c2db6ff7620"; +class LangIt extends WordlistOwl { + constructor() { super("it", words$1, checksum$1); } +} +const langIt = new LangIt(); + +const words = "0arad!ototealirertainrasoent hoandoaR#riareha!aroele'oronul0Aca%AixoAl A%rDuz'El]Er$IsmoO$ Rum S-&T(i&TigoVo[=0F&.Il#P' S?S* So&/Sun$Tr&0Ac#Adu+Al/A[f E End(Er_EuIng'Ir?IvoOl{oRac Revi=RizU&Um0Di$rM-.R>o+TismoT|@Tu 0Ali An%Ar@Ent&Es,I?Is Ul,1Ila1Ar E=Ei%Ulejo:B BosaC&]uCh `C@GagemI+c>~/Se#S)n%Ta)Te=rTidaTomTuc Unil]3B(IjoIr^IsebolLd!eLezaLgaLisc Ndi$Ng&aNz(RimbauRl*d>_Sou_XigaZ(_3CoCu=En&Foc&Furc G|naLhe%Mest[Mo$rOlog@OmboOsf(aPol Rr-$Scoi$Sne$SpoSsex$TolaZ _2Ind#OcoOque 2A$BagemC#CejoChec]Ico.L^LetimL]LoMb{oNdeNecoNi)Rb~h>d>e&R+c]V*oXe?2AncoAsaAvezaEuIgaIl/Inc OaOchu+Onze O$Uxo2C]DismoF LeRacoScaS$Z*a:Bimb Rn{oRpe%R['>)zRv&/SacoScaSeb[S%loS~oT a)Tiv UleUs?U%l V&oV(na3BolaDil]G}]Lebr L~ Nou+N,N%ioRc Rr#R%'oRvejaTimV^2Aco)Al{aAm#Ap^ArmeAticeAveEfeEg^E'oEqueIco%If[In`oOc&/Ov(UmboU.Uva0CatrizCl}eD!eD['aEn%Gcui$Rurg@T 2A[zaE_Ic OneUbe2A=Ag'Ba@B($rBr C^El/Ent_E,Gum`oIb'IfaIo%L L{aLh(Lid'Lme@L}oLunaM<=Mb* M-.MitivaMov(MplexoMumNc]N=rNec.Nfu,Ng` Nhec(Njug Nsum'Nt+$Nvi%Op( P{oPi?PoQue%lRagemRdi&Rne)R}h>p|&R[ioR%joRuj>voSs-oS%laT}e%U_UveVilZ*]2A%+AvoEcheE=rEmeErEspoI^Im*&Io~oIseItic Os)UaUz{o2B+m SafioSbo.Sc<,S-/Sfi#Sgas%Sigu&SlizeSmam SovaSpesaS)queSvi T&h T-$rT} Tri$UsaV(Vi=Vot#Z-a3Ag+maAle$Da)Fu,Gi.Lat#Lu-%M*u'Nast@Nh{oOceseRe$Sc[)Sf ceSp oSque%Ssip S)n%T?UrnoV(,Vi,rV~g Z(5Br?L|i=M?M*#NativoNz`>m-%Rs&SagemUr#U$r2EnagemIbleOg @2El EndeE$PloQues><%Vi=,:1Lod'O Olog@0Ific It&Uc#1Ei$Etiv 3E.1Ab| Eg(Ei$rEncoEv?Im* Ogi 0B goBol#Br~/Buti=EndaErg'Is,rPat@P-/P*#Polg P[goPurr Ul?0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S,u+Z Zio3A=D Ge.Ic~ L{oLhiceLu=Nce=rNdav&N( Nt[Rb&Rd!eRe?Rg}h>m`/RnizRs R%n%SpaSti=T|i&3Adu$AgemAj Atu+Br?D{aDr @ElaGaG-%Gi G| L ejoNcoNhe)NilOle)R!>tudeSi.S$Tr&V{oZ*/5A=rArG&L<%LeibolL)gemLumo,Nt!e5L$Vuz`a::D[zRope3QueRe.Rife3Ng ::Ng#Rp 3BuL?9Mb Olog@5Mbi="; +const checksum = "0x2219000926df7b50d8aa0a3d495826b988287df4657fbd100e6fe596c8f737ac"; +class LangPt extends WordlistOwl { + constructor() { super("pt", words, checksum); } +} +const langPt = new LangPt(); + +const data = "}aE#4A=Yv&co#4N#6G=cJ&SM#66|/Z#4t&kn~46#4K~4q%b9=IR#7l,mB#7W_X2*dl}Uo~7s}Uf&Iw#9c&cw~6O&H6&wx&IG%v5=IQ~8a&Pv#47$PR&50%Ko&QM&3l#5f,D9#4L|/H&tQ;v0~6n]nN> 2), + 128 + codes.indexOf(data[i * 3 + 1]), + 128 + codes.indexOf(data[i * 3 + 2]), + ]; + if (locale === "zh_tw") { + const common = s % 4; + for (let i = common; i < 3; i++) { + bytes[i] = codes.indexOf(deltaData[deltaOffset++]) + ((i == 0) ? 228 : 128); + } + } + wordlist.push(toUtf8String(new Uint8Array(bytes))); + } + // Verify the computed list matches the official list + const checksum = id(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== Checks[locale]) { + throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`); + } + /* c8 ignore stop */ + _wordlist[locale] = wordlist; + return wordlist; +} +class LangZh extends Wordlist { + constructor(country) { super("zh_" + country); } + getWord(index) { + const words = loadWords(this.locale); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords(this.locale).indexOf(word); + } + split(mnemonic) { + mnemonic = mnemonic.replace(/(?:\u3000| )+/g, ""); + return mnemonic.split(""); + } +} +const langZhCn = new LangZh("cn"); +const langZhTw = new LangZh("tw"); + +const wordlists = Object.freeze({ + cz: langCz, es: langEs, fr: langFr, ja: langJa, ko: langKo, it: langIt, pt: langPt, zh_cn: langZhCn, zh_tw: langZhTw +}); + +export { wordlists }; +//# sourceMappingURL=wordlists-extra.js.map diff --git a/dist/wordlists-extra.min.js b/dist/wordlists-extra.min.js new file mode 100644 index 000000000..54b352efe --- /dev/null +++ b/dist/wordlists-extra.min.js @@ -0,0 +1 @@ +function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bool(b){if(typeof b!=="boolean")throw new Error(`Expected boolean, not ${b}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function hash(hash){if(typeof hash!=="function"||typeof hash.create!=="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(hash.outputLen);number(hash.blockLen)}function exists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function output(out,instance){bytes(out);const min=instance.outputLen;if(out.length>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;iBigInt(h>>>0)<<_32n|BigInt(l>>>0);const shrSH=(h,l,s)=>h>>>s;const shrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;const rotr32H=(h,l)=>l;const rotr32L=(h,l)=>h;const rotlSH=(h,l,s)=>h<>>32-s;const rotlSL=(h,l,s)=>l<>>32-s;const rotlBH=(h,l,s)=>l<>>64-s;const rotlBL=(h,l,s)=>h<>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;const u64={fromBig:fromBig,split:split,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH,rotlSL:rotlSL,rotlBH:rotlBH,rotlBL:rotlBL,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L};const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(v,i)=>i.toString(16).padStart(2,"0"));function utf8ToBytes(str){if(typeof str!=="string"){throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`)}return(new TextEncoder).encode(str)}function toBytes(data){if(typeof data==="string")data=utf8ToBytes(data);if(!(data instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);return data}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(hashConstructor){const hashC=message=>hashConstructor().update(toBytes(message)).digest();const tmp=hashConstructor();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashConstructor();return hashC}function wrapConstructorWithOpts(hashCons){const hashC=(msg,opts)=>hashCons(opts).update(toBytes(msg)).digest();const tmp=hashCons({});hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=opts=>hashCons(opts);return hashC}const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];const _0n=BigInt(0);const _1n=BigInt(1);const _2n=BigInt(2);const _7n=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n;for(let j=0;j<7;j++){R=(R<<_1n^(R>>_7n)*_0x71n)%_256n;if(R&_2n)t^=_1n<<(_1n<s>32?u64.rotlBH(h,l,s):u64.rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?u64.rotlBL(h,l,s):u64.rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;assert.number(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds);this.posOut=0;this.pos=0}update(data){assert.exists(this);const{blockLen,state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){assert.number(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){assert.output(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor(()=>new Keccak(blockLen,suffix,outputLen));gen(6,144,224/8);gen(6,136,256/8);gen(6,104,384/8);gen(6,72,512/8);gen(1,144,224/8);const keccak_256=gen(1,136,256/8);gen(1,104,384/8);gen(1,72,512/8);const genShake=(suffix,blockLen,outputLen)=>wrapConstructorWithOpts((opts={})=>new Keccak(blockLen,suffix,opts.dkLen===undefined?outputLen:opts.dkLen,true));genShake(31,168,128/8);genShake(31,136,256/8);const version="6.0.0-beta-exports.0";const LogLevels=["debug","info","warning","error","off"];const _normalizeForms=["NFD","NFC","NFKD","NFKC"].reduce((accum,form)=>{try{if("test".normalize(form)!=="test"){throw new Error("bad")}if(form==="NFD"){const check=String.fromCharCode(233).normalize("NFD");const expected=String.fromCharCode(101,769);if(check!==expected){throw new Error("broken")}}accum.push(form)}catch(error){}return accum},[]);function defineReadOnly(object,name,value){Object.defineProperty(object,name,{enumerable:true,writable:false,value:value})}const maxValue=9007199254740991;const ErrorConstructors={};ErrorConstructors.INVALID_ARGUMENT=TypeError;ErrorConstructors.NUMERIC_FAULT=RangeError;ErrorConstructors.BUFFER_OVERRUN=RangeError;class Logger{version;#logLevel;constructor(version){defineReadOnly(this,"version",version||"_");this.#logLevel=1}get logLevel(){return LogLevels[this.#logLevel]}set logLevel(value){const logLevel=LogLevels.indexOf(value);if(logLevel==null){this.throwArgumentError("invalid logLevel","logLevel",value)}this.#logLevel=logLevel}makeError(message,code,info){{const details=[];if(info){for(const key in info){const value=info[key];try{details.push(key+"="+JSON.stringify(value))}catch(error){details.push(key+"=[could not serialize object]")}}}details.push(`code=${code}`);details.push(`version=${this.version}`);if(details.length){message+=" ("+details.join(", ")+")"}}const create=ErrorConstructors[code]||Error;const error=new create(message);defineReadOnly(error,"code",code);if(info){for(const key in info){defineReadOnly(error,key,info[key])}}return error}throwError(message,code,info){throw this.makeError(message,code,info)}throwArgumentError(message,name,value){return this.throwError(message,"INVALID_ARGUMENT",{argument:name,value:value})}assertNormalize(form){if(_normalizeForms.indexOf(form)===-1){this.throwError("platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:form}})}}assertPrivate(givenGuard,guard,className=""){if(givenGuard!==guard){let method=className,operation="new";if(className){method+=".";operation+=" "+className}this.throwError(`private constructor; use ${method}from* methods`,"UNSUPPORTED_OPERATION",{operation:operation})}}assertArgumentCount(count,expectedCount,message=""){if(message){message=": "+message}if(countexpectedCount){this.throwError("too many arguemnts"+message,"UNEXPECTED_ARGUMENT",{count:count,expectedCount:expectedCount})}}#getBytes(value,name,copy){if(value instanceof Uint8Array){if(copy){return new Uint8Array(value)}return value}if(typeof value==="string"&&value.match(/^0x([0-9a-f][0-9a-f])*$/i)){const result=new Uint8Array((value.length-2)/2);let offset=2;for(let i=0;imaxValue){this.throwArgumentError("overflow",name||"value",value)}return Number(value);case"number":if(!Number.isInteger(value)){this.throwArgumentError("underflow",name||"value",value)}else if(value<-maxValue||value>maxValue){this.throwArgumentError("overflow",name||"value",value)}return value;case"string":try{return this.getNumber(BigInt(value),name)}catch(e){this.throwArgumentError(`invalid numeric string: ${e.message}`,name||"value",value)}}return this.throwArgumentError("invalid numeric value",name||"value",value)}getBigInt(value,name){switch(typeof value){case"bigint":return value;case"number":if(!Number.isInteger(value)){this.throwArgumentError("underflow",name||"value",value)}else if(value<-maxValue||value>maxValue){this.throwArgumentError("overflow",name||"value",value)}return BigInt(value);case"string":try{return BigInt(value)}catch(e){this.throwArgumentError(`invalid BigNumberish string: ${e.message}`,name||"value",value)}}return this.throwArgumentError("invalid BigNumberish value",name||"value",value)}#log(_logLevel,args){const logLevel=LogLevels.indexOf(_logLevel);if(logLevel===-1){this.throwArgumentError("invalid log level name","logLevel",_logLevel)}if(this.#logLevel>logLevel){return}console.log.apply(console,args)}debug(...args){this.#log("debug",args)}info(...args){this.#log("info",args)}warn(...args){this.#log("warning",args)}}const logger=new Logger(version);function assertArgument(check,message,name,value){if(!check){logger.throwArgumentError(message,name,value)}}const HexCharacters="0123456789abcdef";function hexlify(data){const bytes=logger.getBytes(data);let result="0x";for(let i=0;i>4]+HexCharacters[v&15]}return result}function checkType(value,type){const types=type.split("|").map(t=>t.trim());for(let i=0;i>6!==2){break}i++}return i}if(reason==="OVERRUN"){return bytes.length-offset-1}return 0}function replaceFunc(reason,offset,bytes,output,badCodepoint){if(reason==="OVERLONG"){output.push(badCodepoint!=null?badCodepoint:-1);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes)}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(_bytes,onError){if(onError==null){onError=Utf8ErrorFuncs.error}const bytes=logger.getBytes(_bytes,"bytes");const result=[];let i=0;while(i>7===0){result.push(c);continue}let extraLength=null;let overlongMask=null;if((c&224)===192){extraLength=1;overlongMask=127}else if((c&240)===224){extraLength=2;overlongMask=2047}else if((c&248)===240){extraLength=3;overlongMask=65535}else{if((c&192)===128){i+=onError("UNEXPECTED_CONTINUE",i-1,bytes,result)}else{i+=onError("BAD_PREFIX",i-1,bytes,result)}continue}if(i-1+extraLength>=bytes.length){i+=onError("OVERRUN",i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j1114111){i+=onError("OUT_OF_RANGE",i-1-extraLength,bytes,result,res);continue}if(res>=55296&&res<=57343){i+=onError("UTF16_SURROGATE",i-1-extraLength,bytes,result,res);continue}if(res<=overlongMask){i+=onError("OVERLONG",i-1-extraLength,bytes,result,res);continue}result.push(res)}return result}function toUtf8Bytes(str,form){if(form!=null){logger.assertNormalize(form);str=str.normalize(form)}let result=[];for(let i=0;i>6|192);result.push(c&63|128)}else if((c&64512)==55296){i++;const c2=str.charCodeAt(i);if(i>=str.length||(c2&64512)!==56320){throw new Error("invalid utf-8 string")}const pair=65536+((c&1023)<<10)+(c2&1023);result.push(pair>>18|240);result.push(pair>>12&63|128);result.push(pair>>6&63|128);result.push(pair&63|128)}else{result.push(c>>12|224);result.push(c>>6&63|128);result.push(c&63|128)}}return new Uint8Array(result)}function _toUtf8String(codePoints){return codePoints.map(codePoint=>{if(codePoint<=65535){return String.fromCharCode(codePoint)}codePoint-=65536;return String.fromCharCode((codePoint>>10&1023)+55296,(codePoint&1023)+56320)}).join("")}function toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}let locked=false;const _keccak256=function(data){return keccak_256(data)};let __keccak256=_keccak256;function keccak256(_data){const data=logger.getBytes(_data,"data");return hexlify(__keccak256(data))}keccak256._=_keccak256;keccak256.lock=function(){locked=true};keccak256.register=function(func){if(locked){throw new TypeError("keccak256 is locked")}__keccak256=func};Object.freeze(keccak256);function id(value){return keccak256(toUtf8Bytes(value))}const subsChrs=" !#$%&'()*+,-./<=>?@[]^_`{|}~";const Word=/^[a-z]*$/i;function unfold(words,sep){let initial=97;return words.reduce((accum,word)=>{if(word===sep){initial++}else if(word.match(Word)){accum.push(String.fromCharCode(initial)+word)}else{initial=97;accum.push(word)}return accum},[])}function decode(data,subs){for(let i=subsChrs.length-1;i>=0;i--){data=data.split(subsChrs[i]).join(subs.substring(2*i,2*i+2))}const clumps=[];const leftover=data.replace(/(:|([0-9])|([A-Z][a-z]*))/g,(all,item,semi,word)=>{if(semi){for(let i=parseInt(semi);i>=0;i--){clumps.push(";")}}else{clumps.push(item.toLowerCase())}return""});if(leftover){throw new Error(`leftovers: ${JSON.stringify(leftover)}`)}return unfold(unfold(clumps,";"),":")}function decodeOwl(data){assertArgument(data[0]==="0","unsupported auwl data","data",data);return decode(data.substring(1+2*subsChrs.length),data.substring(1,1+2*subsChrs.length))}class Wordlist{locale;constructor(locale){defineProperties(this,{locale:locale})}split(mnemonic){return mnemonic.toLowerCase().split(/ +/g)}join(words){return words.join(" ")}}class WordlistOwl extends Wordlist{#data;#checksum;constructor(locale,data,checksum){super(locale);this.#data=data;this.#checksum=checksum;this.#words=null}get _data(){return this.#data}_decodeWords(){return decodeOwl(this.#data)}#words;#loadWords(){if(this.#words==null){const words=this._decodeWords();const checksum=id(words.join("\n")+"\n");if(checksum!==this.#checksum){throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`)}this.#words=words}return this.#words}getWord(index){const words=this.#loadWords();if(index<0||index>=words.length){logger.throwArgumentError(`invalid word index: ${index}`,"index",index)}return words[index]}getWordIndex(word){return this.#loadWords().indexOf(word)}}const words$4="0itatkastcenaovo$taouleraeki&chor*teci%enbalodaeladet'!Chn=0Di#%E%^1Resa2Rese3CeT'#0EjKohol0Pu)%0A&sDul#Ekdo)Ke)Ti#Ul|3}aOgan%0FaltI$@tPi,%TmaTronom0LasL{i#Ol0Tobus4Yl:B#}R'?TaUb_U/!U^U+Ur!Xer2A^v#Ambo,An#AtrEp)Ike)KoLohOnzOskevUn{#Usin#Z^Zy2Bl.Bn|})D _D#D'aF{Jar(Kv?LdokLvaN^NkrRzaTikVolZola3D+tL.T'#0Ukot:PartRev&3DrDu+J/JnLaLerLkemLn?N.Nn(N'#NtrumNzZ(2O&2KolivUv!4It_N(0Dn(Ke)KrPot0Ak~AlIkRkot2Kli$a:L-oRe[T_Tum1E,1B!a}'#Cib_Fic Fla%KlKr{Mokr!PreseRbyS#T-tiv3Kob,zKt|O^P]mSkSp+jV`]Vo/2AhaOuhoUhopis1Es0BroByt-C@t}ut DnesH+dHo^H,JemJn?Kl`KolaKtAzeDolObn(OgerieOzdSn(T Z(2B@}'noD-HaH'#S SnoT(0Oj?Or>2Nam :9O]gOnomie0EktronIpsa0AilIseO%P!ie2Izo^O/aOpejOs2EjEn%K<)Kymo0Ike)0FR&S]Zky3StOhOup(T!Ub.U/o)0AtO)Yz0IsOjivoOut0Bl.Boj}DinyDl!Dno)D|Jn(KejLin#L#LubMo+N [No,%RalR^RizontRkoRliv>RmonRn.RoskopR$voSpo^St.T'(U[UfUp!Us#V<2Ad[An?Av(Az^Bo+kD.D]D(N-Ob#Oma^OtOu^Oz@St#Ub(Yz!2B@(B~D[KotMrS aSto)0Ozd2Bn(D,ntGie&M&Sterik:2Yl#3Ned2O&0Uze0Un a0F-%Fla%KasoOva%Sp-%Tern{Vali^Ve$N)rRmarkRoSanSnoT#VD+Dn!_HlanKotL@L oMn(NomP?S{erV Zd>Zero3NakNdyNo/Sk,Sto)Trn?Zva3En|1Gurt5R):Bar{B_Bin{}&D{Did]HanJakJu)KaoKtusLam a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n(IvoOb RojVihYm`]0L@.ManM.Pt!Z`uZdola2At Lt~Lubo#Ot' Ru[0MaMn?0Emn 0Lam!Oum!R!#Umav#0AtoEh#O[OmO$Ozvyk0Ap|ArAt-IjeIz{Ocn Odr!Rzl.Ut|0AkAl(Am@!Ovu0B,z Tav Ub-Ufa+0Lod Omal RavaR( Rud#Rvu1A^An C`]N (NoOv&Y/l Zav(1I/aR! 0B'.Br0Ed~EnkuEs_aOnR!Uk'odYk";const checksum$4="0x25f44555f4af25b51a711136e1c7d6e50ce9f8917d39d6b1f076b2bb4d2fac1a";class LangCz extends WordlistOwl{constructor(){super("cz",words$4,checksum$4)}}const langCz=new LangCz;const Base64=")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";function decodeBits(width,data){const maxValue=(1<=width){const value=accum>>bits-width;accum&=(1<{const match=accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);assertArgument(match!==null,"internal error parsing accents","accents",accents);let posOffset=0;const positions=decodeBits(parseInt(match[3]),match[4]);const charCode=parseInt(match[2]);const regex=new RegExp(`([${match[1]}])`,"g");words=words.replace(regex,(all,letter)=>{const rem=--positions[posOffset];if(rem===0){letter=String.fromCharCode(letter.charCodeAt(0),charCode);posOffset++}return letter})});return words.split(",")}class WordlistOwlA extends WordlistOwl{#accent;constructor(locale,data,accent,checksum){super(locale,data,checksum);this.#accent=accent}get _accent(){return this.#accent}_decodeWords(){return decodeOwlA(this._data,this._accent)}}const words$3="0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|o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#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv!b){return 1}return 0}for(let length=3;length<=9;length++){const d=data$2[length-3];for(let offset=0;offset=words.length){logger.throwArgumentError(`invalid word index: ${index}`,"index",index)}return words[index]}getWordIndex(word){return loadWords$2().indexOf(word)}split(mnemonic){return mnemonic.split(/(?:\u3000| )+/g)}join(words){return words.join(" ")}}const langJa=new LangJa;const data$1=["OYAa","ATAZoATBl3ATCTrATCl8ATDloATGg3ATHT8ATJT8ATJl3ATLlvATLn4ATMT8ATMX8ATMboATMgoAToLbAToMTATrHgATvHnAT3AnAT3JbAT3MTAT8DbAT8JTAT8LmAT8MYAT8MbAT#LnAUHT8AUHZvAUJXrAUJX8AULnrAXJnvAXLUoAXLgvAXMn6AXRg3AXrMbAX3JTAX3QbAYLn3AZLgvAZrSUAZvAcAZ8AaAZ8AbAZ8AnAZ8HnAZ8LgAZ8MYAZ8MgAZ8OnAaAboAaDTrAaFTrAaJTrAaJboAaLVoAaMXvAaOl8AaSeoAbAUoAbAg8AbAl4AbGnrAbMT8AbMXrAbMn4AbQb8AbSV8AbvRlAb8AUAb8AnAb8HgAb8JTAb8NTAb8RbAcGboAcLnvAcMT8AcMX8AcSToAcrAaAcrFnAc8AbA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LfoMT8Se8DTrHbDb","AbDl8SToJU8An3RbAb8ST8DUSTrGnrAgoLbFU6Db8LTrMg8AaHT8Jb8ObDl8SToJU8Pb3RlvFYoJl"];const codes$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function getHangul(code){if(code>=40){code=code+168-40}else if(code>=19){code=code+97-19}return toUtf8String(new Uint8Array([225,(code>>6)+132,(code&63)+128]))}let _wordlist$1=null;function loadWords$1(){if(_wordlist$1!=null){return _wordlist$1}const wordlist=[];data$1.forEach((data,length)=>{length+=4;for(let i=0;i=words.length){logger.throwArgumentError(`invalid word index: ${index}`,"index",index)}return words[index]}getWordIndex(word){return loadWords$1().indexOf(word)}}const langKo=new LangKo;const words$1="0torea noica!iosorolotaleratelanena%oiadoencotivomai t ca%a0A]Bagl'Bin#E.Is(Oli!Rasi_Rog#0Cade!C[$Cus#E Roba+U 0Ag'Deb{DomeEgu#Eri!IpeOtt&Ul&1Fabi,Fe|Fis(F-n Oris`O(R~$0AveEn.E_,Ganc'I!It&OnismoR>*Rume Uzzo4AbardaA Bat)Ber#BoBumeCeCol>E|Ertu-OdePari!Pe^ Pogg'P)@Pun Ri,1Ab~AchideAgos+Ald~Anc'Atu-AzzoBit)Chiv'D{Eni,G[ GiSoTef%eZil*0Ciu|Col EpsiEtt>Fal I$O/Pir#P)Sagg'SeSolu Sur@TaT[u T%eT-|0Av>EismoOm>O$TesaTiv&Tor$Tr{Tua,0Sil'Str?Tis+To$moTun$0Anz#E!V[i!Vi(Volge!3IoS(Tos+Ttu U,VaVosa3C]FfaLg'LvaNdaNe_,Nig$Nzi=ReRli=Ta3Bi+CiDoR@S]Tan>T^$Zzo*2Acc'AdipoA`An}Avu-E.l/Eve|EzzaIgl?Il/n.Ind&Oc]*O@Onzi=Ul*U$2BboT+di$UffoVet+Vi,2Ass>In~O)2C]Dar@D%eE!n.G$meLl&Lm#Lo!Lpo(L^v#LzaMaMe+M`n@Mo@Mp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esc'5BizzoBr~GaLli$Mi:B#Bbi&Bot#Go`Las(Ldatu-Lgem`Liv&LmoEtt)HedaHie=IarpaI[zaInde!IppoI)ppoI_*Ler&Odel/Olp{Ompar Onfor Opri!Or+Os(Mul#Nfon?Ngo*Nist)NoN.siNu(idePar'S`S ,Tu#2It+Ogatu-Ove$0Arr{Emor#En^ E-l@IlzoOnt&Ott#Uss#0Elli!Erv#O@0BbalzoBr'C]r(C?,Da,Ffi|G$Ld#L[M`NdaNe|Nnife)Pi!Ppe(P-Rge!Rpas(Rri(R(R.gg'R_l#Spi)S+T^,0AdaAl/Arge!A /Av[ Azzo/EcieEdi!EgRappoReg#Ridu*Rozz&Ru|Ucc&UfoUp[@0B[t)C](Do!Gger{GoL+$On&PerboPpor Rgel#R)g#Ssur)Tu-0Ag&EdeseEgl'El&Enu Ez?IluppoIs+Izze-Ol+Uot&:Bac]Bul#Cci&Citur$LeLis`$MpoVer=Vo/+Zza3CaCn>Lefo$Me-r'MpoMu N@Pog-foRagg'RoTan'To*Tuban.Z'Zzo<5Cc&L,r&L Mbo/MoNfoNsil/Paz'Po*g?PpaRbaRn&R)L,t+Lo)(Lut&L_/Mpa+Ng&N{(NoN+gg'Nve-Po!Ra$Rc#R?n.S}3Det+DovaDu Ge+,I]*Lc)Li=Llu LoceN#Ndemm?N RaceRba,Rgog=Rif~RoRru}Rt~,Sc~Ssil*S+,Te-$Tri=Tus 3Andan.B-n.C[daChingoCi=nzaDim&Gil?G< Go!LeL/$MiniNc{!O/Pe-Rgo/Ro*goRu,n S](S'5Cche)Fo*LuPpa";const checksum$1="0x5c1362d88fd4cf614a96f3234941d29f7d37c08c5292fde03bf62c2db6ff7620";class LangIt extends WordlistOwl{constructor(){super("it",words$1,checksum$1)}}const langIt=new LangIt;const words="0arad!ototealirertainrasoent hoandoaR#riareha!aroele'oronul0Aca%AixoAl A%rDuz'El]Er$IsmoO$ Rum S-&T(i&TigoVo[=0F&.Il#P' S?S* So&/Sun$Tr&0Ac#Adu+Al/A[f E End(Er_EuIng'Ir?IvoOl{oRac Revi=RizU&Um0Di$rM-.R>o+TismoT|@Tu 0Ali An%Ar@Ent&Es,I?Is Ul,1Ila1Ar E=Ei%Ulejo:B BosaC&]uCh `C@GagemI+c>~/Se#S)n%Ta)Te=rTidaTomTuc Unil]3B(IjoIr^IsebolLd!eLezaLgaLisc Ndi$Ng&aNz(RimbauRl*d>_Sou_XigaZ(_3CoCu=En&Foc&Furc G|naLhe%Mest[Mo$rOlog@OmboOsf(aPol Rr-$Scoi$Sne$SpoSsex$TolaZ _2Ind#OcoOque 2A$BagemC#CejoChec]Ico.L^LetimL]LoMb{oNdeNecoNi)Rb~h>d>e&R+c]V*oXe?2AncoAsaAvezaEuIgaIl/Inc OaOchu+Onze O$Uxo2C]DismoF LeRacoScaS$Z*a:Bimb Rn{oRpe%R['>)zRv&/SacoScaSeb[S%loS~oT a)Tiv UleUs?U%l V&oV(na3BolaDil]G}]Lebr L~ Nou+N,N%ioRc Rr#R%'oRvejaTimV^2Aco)Al{aAm#Ap^ArmeAticeAveEfeEg^E'oEqueIco%If[In`oOc&/Ov(UmboU.Uva0CatrizCl}eD!eD['aEn%Gcui$Rurg@T 2A[zaE_Ic OneUbe2A=Ag'Ba@B($rBr C^El/Ent_E,Gum`oIb'IfaIo%L L{aLh(Lid'Lme@L}oLunaM<=Mb* M-.MitivaMov(MplexoMumNc]N=rNec.Nfu,Ng` Nhec(Njug Nsum'Nt+$Nvi%Op( P{oPi?PoQue%lRagemRdi&Rne)R}h>p|&R[ioR%joRuj>voSs-oS%laT}e%U_UveVilZ*]2A%+AvoEcheE=rEmeErEspoI^Im*&Io~oIseItic Os)UaUz{o2B+m SafioSbo.Sc<,S-/Sfi#Sgas%Sigu&SlizeSmam SovaSpesaS)queSvi T&h T-$rT} Tri$UsaV(Vi=Vot#Z-a3Ag+maAle$Da)Fu,Gi.Lat#Lu-%M*u'Nast@Nh{oOceseRe$Sc[)Sf ceSp oSque%Ssip S)n%T?UrnoV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g Aje$AmaAnc ApoAs{oAt?Av E*oEm(Epid EvoIagemIboIcicloId-%Ilog@Ind!eIploItur Iunf&Oc Ombe)OvaUnfoUque2B~ CquesaT` T|i&:7V 3Bigo0HaId!eIf|me3Olog@SoTigaUbu0A=InaUfru':C*aDi G o,I=,LaL-%Lid!eLo[sN)gemQu{oRe)Rr(Sc~ Sil]S,u+Z Zio3A=D Ge.Ic~ L{oLhiceLu=Nce=rNdav&N( Nt[Rb&Rd!eRe?Rg}h>m`/RnizRs R%n%SpaSti=T|i&3Adu$AgemAj Atu+Br?D{aDr @ElaGaG-%Gi G| L ejoNcoNhe)NilOle)R!>tudeSi.S$Tr&V{oZ*/5A=rArG&L<%LeibolL)gemLumo,Nt!e5L$Vuz`a::D[zRope3QueRe.Rife3Ng ::Ng#Rp 3BuL?9Mb Olog@5Mbi=";const checksum="0x2219000926df7b50d8aa0a3d495826b988287df4657fbd100e6fe596c8f737ac";class LangPt extends WordlistOwl{constructor(){super("pt",words,checksum)}}const langPt=new LangPt;const data="}aE#4A=Yv&co#4N#6G=cJ&SM#66|/Z#4t&kn~46#4K~4q%b9=IR#7l,mB#7W_X2*dl}Uo~7s}Uf&Iw#9c&cw~6O&H6&wx&IG%v5=IQ~8a&Pv#47$PR&50%Ko&QM&3l#5f,D9#4L|/H&tQ;v0~6n]nN>2),128+codes.indexOf(data[i*3+1]),128+codes.indexOf(data[i*3+2])];if(locale==="zh_tw"){const common=s%4;for(let i=common;i<3;i++){bytes[i]=codes.indexOf(deltaData[deltaOffset++])+(i==0?228:128)}}wordlist.push(toUtf8String(new Uint8Array(bytes)))}const checksum=id(wordlist.join("\n")+"\n");if(checksum!==Checks[locale]){throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`)}_wordlist[locale]=wordlist;return wordlist}class LangZh extends Wordlist{constructor(country){super("zh_"+country)}getWord(index){const words=loadWords(this.locale);if(index<0||index>=words.length){logger.throwArgumentError(`invalid word index: ${index}`,"index",index)}return words[index]}getWordIndex(word){return loadWords(this.locale).indexOf(word)}split(mnemonic){mnemonic=mnemonic.replace(/(?:\u3000| )+/g,"");return mnemonic.split("")}}const langZhCn=new LangZh("cn");const langZhTw=new LangZh("tw");const wordlists=Object.freeze({cz:langCz,es:langEs,fr:langFr,ja:langJa,ko:langKo,it:langIt,pt:langPt,zh_cn:langZhCn,zh_tw:langZhTw});export{wordlists}; \ No newline at end of file diff --git a/lib.commonjs/_tests/test-abi.js b/lib.commonjs/_tests/test-abi.js new file mode 100644 index 000000000..b0750b057 --- /dev/null +++ b/lib.commonjs/_tests/test-abi.js @@ -0,0 +1,46 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +function equal(actual, expected) { + switch (expected.type) { + case "address": + case "boolean": + case "hexstring": + case "string": + assert_1.default.equal(actual, expected.value); + return; + case "number": + assert_1.default.equal(actual, BigInt(expected.value)); + return; + case "array": + case "object": + assert_1.default.ok(Array.isArray(actual), "!array"); + assert_1.default.equal(actual.length, expected.value.length, ".length mismatch"); + for (let i = 0; i < actual.length; i++) { + equal(actual[i], expected.value[i]); + } + return; + } + throw new Error(`unsupported: ${expected}`); +} +describe("Tests ABI Coder", function () { + const tests = (0, utils_js_1.loadTests)("abi"); + for (const test of tests) { + it(`tests ABI encoding: (${test.name})`, function () { + const encoded = index_js_1.defaultAbiCoder.encode([test.type], [test.value]); + assert_1.default.equal(encoded, test.encoded, "encoded"); + }); + } + for (const test of tests) { + it(`tests ABI decoding: (${test.name})`, function () { + const decoded = index_js_1.defaultAbiCoder.decode([test.type], test.encoded)[0]; + equal(decoded, test.verbose); + }); + } +}); +//# sourceMappingURL=test-abi.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-abi.js.map b/lib.commonjs/_tests/test-abi.js.map new file mode 100644 index 000000000..1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I,IAAI,KAAK,EAAE;QACtB,EAAE,CAAC,wBAAyB,IAAI,CAAC,IAAK,GAAG,EAAE;YACvC,MAAM,OAAO,GAAG,0BAAe,CAAC,MAAM,CAAC,CAAE,IAAI,CAAC,IAAI,CAAE,EAAE,CAAE,IAAI,CAAC,KAAK,CAAE,CAAC,CAAC;YACtE,gBAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QACnD,CAAC,CAAC,CAAC;KACN;IAED,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,EAAE,CAAC,wBAAyB,IAAI,CAAC,IAAK,GAAG,EAAE;YACvC,MAAM,OAAO,GAAG,0BAAe,CAAC,MAAM,CAAC,CAAE,IAAI,CAAC,IAAI,CAAE,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YACvE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-address.js b/lib.commonjs/_tests/test-address.js new file mode 100644 index 000000000..7e2fe46b6 --- /dev/null +++ b/lib.commonjs/_tests/test-address.js @@ -0,0 +1,115 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +describe("computes checksum address", function () { + const tests = (0, utils_js_1.loadTests)("accounts"); + for (const test of tests) { + it(`computes the checksum address: ${test.name}`, function () { + assert_1.default.equal((0, index_js_1.getAddress)(test.address), test.address); + assert_1.default.equal((0, index_js_1.getAddress)(test.icap), test.address); + assert_1.default.equal((0, index_js_1.getAddress)(test.address.substring(2)), test.address); + assert_1.default.equal((0, index_js_1.getAddress)(test.address.toLowerCase()), test.address); + assert_1.default.equal((0, index_js_1.getAddress)("0x" + test.address.substring(2).toUpperCase()), test.address); + }); + } + const invalidAddresses = [ + { name: "null", value: null }, + { name: "number", value: 1234 }, + { name: "emtpy bytes", value: "0x" }, + { name: "too short", value: "0x8ba1f109551bd432803012645ac136ddd64dba" }, + { name: "too long", value: "0x8ba1f109551bd432803012645ac136ddd64dba7200" }, + ]; + invalidAddresses.forEach(({ name, value }) => { + it(`fails on invalid address: ${name}`, function () { + assert_1.default.throws(function () { + (0, index_js_1.getAddress)(value); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid address/) && + error.argument === "address" && + error.value === value); + }); + }); + }); + it("fails on invalid checksum", function () { + const value = "0x8ba1f109551bD432803012645Ac136ddd64DBa72"; + assert_1.default.throws(function () { + (0, index_js_1.getAddress)(value); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^bad address checksum/) && + error.argument === "address" && + error.value === value); + }); + }); + it("fails on invalid IBAN checksum", function () { + const value = "XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37"; + assert_1.default.throws(function () { + (0, index_js_1.getAddress)(value); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^bad icap checksum/) && + error.argument === "address" && + error.value === value); + }); + }); +}); +describe("computes ICAP address", function () { + const tests = (0, utils_js_1.loadTests)("accounts"); + for (const test of tests) { + it(`computes the ICAP address: ${test.name}`, function () { + assert_1.default.equal((0, index_js_1.getIcapAddress)(test.address), test.icap); + assert_1.default.equal((0, index_js_1.getAddress)(test.address.toLowerCase()), test.address); + assert_1.default.equal((0, index_js_1.getAddress)("0x" + test.address.substring(2).toUpperCase()), test.address); + }); + } +}); +describe("computes create address", function () { + const tests = (0, utils_js_1.loadTests)("create"); + for (const { sender, creates } of tests) { + for (const { name, nonce, address } of creates) { + it(`computes the create address: ${name}`, function () { + assert_1.default.equal((0, index_js_1.getCreateAddress)({ from: sender, nonce }), address); + }); + } + } +}); +describe("computes create2 address", function () { + const tests = (0, utils_js_1.loadTests)("create2"); + for (const { sender, creates } of tests) { + for (const { name, salt, initCodeHash, address } of creates) { + it(`computes the create2 address: ${name}`, function () { + assert_1.default.equal((0, index_js_1.getCreate2Address)(sender, salt, initCodeHash), address); + }); + } + } + const sender = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; + const salt = "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"; + const initCodeHash = "0x8452c9b9140222b08593a26daa782707297be9f7b3e8281d7b4974769f19afd0"; + it("fails on invalid salt", function () { + const badSalt = "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36dea"; + assert_1.default.throws(function () { + (0, index_js_1.getCreate2Address)(sender, badSalt, initCodeHash); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "salt" && + error.value === badSalt); + }); + }); + it("fails on invalid initCodeHash", function () { + const badInitCodeHash = "0x8452c9b9140222b08593a26daa782707297be9f7b3e8281d7b4974769f19af"; + assert_1.default.throws(function () { + (0, index_js_1.getCreate2Address)(sender, salt, badInitCodeHash); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "initCodeHash" && + error.value === badInitCodeHash); + }); + }); +}); +//# sourceMappingURL=test-address.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-address.js.map b/lib.commonjs/_tests/test-address.js.map new file mode 100644 index 000000000..047ba006c --- /dev/null +++ b/lib.commonjs/_tests/test-address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-address.js","sourceRoot":"","sources":["../../src.ts/_tests/test-address.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,yCAAuC;AAQvC,0CAGqB;AAGrB,QAAQ,CAAC,2BAA2B,EAAE;IAClC,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAkB,UAAU,CAAC,CAAC;IACrD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,EAAE,CAAC,kCAAmC,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 No newline at end of file diff --git a/lib.commonjs/_tests/test-contract.js b/lib.commonjs/_tests/test-contract.js new file mode 100644 index 000000000..86aed7e10 --- /dev/null +++ b/lib.commonjs/_tests/test-contract.js @@ -0,0 +1,99 @@ +"use strict"; +/* +import { Typed } from "../abi/index.js"; +import * as providers from "../providers/index.js"; + +import { Contract } from "../index.js"; + +import { log } from "./utils.js"; +*/ +//import type { Addressable } from "@ethersproject/address"; +//import type { BigNumberish } from "@ethersproject/logger"; +/* +import type { + ConstantContractMethod, ContractMethod, ContractEvent +} from "../index.js"; +*/ +// @TODO +/* +describe("Test Contract Calls", function() { + it("finds typed methods", async function() { + const contract = new Contract("0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72", [ + "function foo(string s) view returns (uint)", + "function foo(uint8) view returns (uint)", + "function foo(uint u, bool b) view returns (uint)", + ]); + const value = Typed.string("42"); + await contract.foo.populateTransaction(value, Typed.overrides({ value: 100 })) + contract["foo(string)"].fragment + }); +}); +*/ +/* +describe("Test Contract Interface", function() { + it("builds contract interfaces", async function() { + this.timeout(60000); + + interface Erc20Interface { + // Constant Methods + balanceOf: ConstantContractMethod<[ address: string | Addressable ], bigint>; + decimals: ConstantContractMethod<[ ], bigint>; + + name: ConstantContractMethod<[ ], string>; + symbol: ConstantContractMethod<[ ], string>; + + // Mutation Methods + transferFrom: ContractMethod<[ address: string | Addressable, + address: string | Addressable, amount: BigNumberish ], boolean>; + + // Events + filters: { + Transfer: ContractEvent<[ from: Addressable | string, to: BigNumberish ]>; + } + } + + const erc20Abi = [ + "function balanceOf(address owner) view returns (uint)", + "function decimals() view returns (uint)", + "function name() view returns (string)", + "function symbol() view returns (string)", + + "function transferFrom(address from, address to, uint amount) returns (boolean)", + + "event Transfer(address indexed from, address indexed to, uint amount)" + ]; + + class Erc20Contract extends BaseContract.buildClass(erc20Abi) { }; + + const provider = new providers.InfuraProvider(); + // ENS + //const addr = "0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72"; + // DAI + const addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; + const contract = new Erc20Contract(addr, provider); + console.log("SYMBOL", await contract.symbol()); + console.log("DECIMALS", await contract.decimals()); + console.log(await contract.balanceOf("0x5555763613a12D8F3e73be831DFf8598089d3dCa")); + console.log(await contract.balanceOf("ricmoo.eth")); + + await contract.on(contract.filters.Transfer, (from, to, value, event) => { + console.log("HELLO!", { from, to, value, event }); + event.removeListener(); + }); + const logs = await contract.queryFilter("Transfer", -10); + console.log(logs, logs[0], logs[0].args.from); + }); +}); +*/ +/* +describe("Test Contract Calls", function() { + it("calls ERC-20 methods", async function() { + const provider = new providers.AnkrProvider(); + const contract = new Contract("0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72", [ + "function balanceOf(address owner) view returns (uint)", + ], provider); + log(this, `balance: ${ await contract.balanceOf("0x5555763613a12D8F3e73be831DFf8598089d3dCa") }`); + }); +}); +*/ +//# sourceMappingURL=test-contract.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-contract.js.map b/lib.commonjs/_tests/test-contract.js.map new file mode 100644 index 000000000..736766abd --- /dev/null +++ b/lib.commonjs/_tests/test-contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-contract.js","sourceRoot":"","sources":["../../src.ts/_tests/test-contract.ts"],"names":[],"mappings":";AAAA;;;;;;;EAOE;AACF,4DAA4D;AAC5D,4DAA4D;AAE5D;;;;EAIE;AAEF,QAAQ;AACR;;;;;;;;;;;;;EAaE;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuDE;AACF;;;;;;;;;;EAUE"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-crypto-algoswap.js b/lib.commonjs/_tests/test-crypto-algoswap.js new file mode 100644 index 000000000..21ac7d123 --- /dev/null +++ b/lib.commonjs/_tests/test-crypto-algoswap.js @@ -0,0 +1,87 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const index_js_1 = require("../index.js"); +describe("test registration", function () { + let hijack = ""; + function getHijack(algo) { + return function (...args) { + hijack = `hijacked ${algo}: ${JSON.stringify(args)}`; + return "0x42"; + }; + } + const tests = [ + { + name: "keccak256", + params: ["0x"], + hijackTag: 'hijacked keccak256: [{}]', + algorithm: index_js_1.keccak256 + }, + { + name: "sha256", + params: ["0x"], + hijackTag: 'hijacked sha256: [{}]', + algorithm: index_js_1.sha256 + }, + { + name: "sha512", + params: ["0x"], + hijackTag: 'hijacked sha512: [{}]', + algorithm: index_js_1.sha512 + }, + { + name: "ripemd160", + params: ["0x"], + hijackTag: 'hijacked ripemd160: [{}]', + algorithm: index_js_1.ripemd160 + }, + { + name: "pbkdf2", + params: ["0x", "0x", 1024, 32, "sha256"], + hijackTag: 'hijacked pbkdf2: [{},{},1024,32,"sha256"]', + algorithm: index_js_1.pbkdf2 + }, + { + name: "scryptSync", + params: ["0x", "0x", 1024, 8, 1, 32], + hijackTag: 'hijacked scryptSync: [{},{},1024,8,1,32]', + algorithm: index_js_1.scryptSync + }, + { + name: "scrypt", + params: ["0x", "0x", 1024, 8, 1, 32], + hijackTag: 'hijacked scrypt: [{},{},1024,8,1,32,null]', + algorithm: index_js_1.scrypt + }, + { + name: "computeHmac", + params: ["sha256", "0x", "0x"], + hijackTag: 'hijacked computeHmac: ["sha256",{},{}]', + algorithm: index_js_1.computeHmac + }, + ]; + tests.forEach(({ name, params, hijackTag, algorithm }) => { + it(`swaps in hijacked callback: ${name}`, async function () { + const initial = await algorithm(...params); + algorithm.register(getHijack(name)); + assert_1.default.equal(await algorithm(...params), "0x42"); + assert_1.default.equal(hijack, hijackTag); + algorithm.register(algorithm._); + assert_1.default.equal(await algorithm(...params), initial); + }); + }); + it("prevents swapping after locked", function () { + (0, index_js_1.lock)(); + tests.forEach(({ name, params, hijackTag, algorithm }) => { + assert_1.default.throws(function () { + algorithm.register(getHijack("test")); + }, function (error) { + return (error.message === `${name} is locked`); + }); + }); + }); +}); +//# sourceMappingURL=test-crypto-algoswap.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-crypto-algoswap.js.map b/lib.commonjs/_tests/test-crypto-algoswap.js.map new file mode 100644 index 000000000..f0615c011 --- /dev/null +++ b/lib.commonjs/_tests/test-crypto-algoswap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-crypto-algoswap.js","sourceRoot":"","sources":["../../src.ts/_tests/test-crypto-algoswap.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,0CAQqB;AAkBrB,QAAQ,CAAC,mBAAmB,EAAE;IAE1B,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,SAAS,SAAS,CAAC,IAAY;QAC3B,OAAO,UAAS,GAAG,IAAgB;YAC/B,MAAM,GAAG,YAAa,IAAK,KAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAE,EAAE,CAAC;YACzD,OAAO,MAAM,CAAC;QAClB,CAAC,CAAA;IACL,CAAC;IAED,MAAM,KAAK,GAAoB;QAC3B;YACI,IAAI,EAAE,WAAW;YACjB,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,0BAA0B;YACrC,SAAS,EAAE,oBAAS;SACvB;QACD;YACI,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,uBAAuB;YAClC,SAAS,EAAE,iBAAM;SACpB;QACD;YACI,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,uBAAuB;YAClC,SAAS,EAAE,iBAAM;SACpB;QACD;YACI,IAAI,EAAE,WAAW;YACjB,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,0BAA0B;YACrC,SAAS,EAAE,oBAAS;SACvB;QACD;YACI,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,CAAE,I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CAAC;QACtD,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,gCAAgC,EAAE;QACjC,IAAA,eAAI,GAAE,CAAC;QAEP,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE;YACrD,gBAAM,CAAC,MAAM,CAAC;gBACV,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;YAC1C,CAAC,EAAE,UAAS,KAAU;gBAClB,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,GAAI,IAAK,YAAY,CAAC,CAAC;YACrD,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AAEP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-crypto.js b/lib.commonjs/_tests/test-crypto.js new file mode 100644 index 000000000..36d6b6683 --- /dev/null +++ b/lib.commonjs/_tests/test-crypto.js @@ -0,0 +1,219 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +describe("test hashing", function () { + const tests = (0, utils_js_1.loadTests)("hashes"); + tests.forEach((test) => { + it(`computes sha2-256: ${test.name}`, function () { + assert_1.default.equal((0, index_js_1.sha256)(test.data), test.sha256); + }); + }); + tests.forEach((test) => { + it(`computes sha2-512: ${test.name}`, function () { + assert_1.default.equal((0, index_js_1.sha512)(test.data), test.sha512); + }); + }); + tests.forEach((test) => { + it(`computes ripemd160: ${test.name}`, function () { + assert_1.default.equal((0, index_js_1.ripemd160)(test.data), test.ripemd160); + }); + }); + tests.forEach((test) => { + it(`computes keccak256: ${test.name}`, function () { + assert_1.default.equal((0, index_js_1.keccak256)(test.data), test.keccak256); + }); + }); +}); +describe("test password-based key derivation", function () { + const tests = (0, utils_js_1.loadTests)("pbkdf"); + tests.forEach((test) => { + it(`computes pbkdf2: ${test.name}`, function () { + const password = Buffer.from(test.password.substring(2), "hex"); + const salt = Buffer.from(test.salt.substring(2), "hex"); + const { iterations, algorithm, key } = test.pbkdf2; + const result = (0, index_js_1.pbkdf2)(password, salt, iterations, test.dkLen, algorithm); + assert_1.default.equal(result, key); + }); + }); + tests.forEach((test) => { + it(`computes scrypt (sync): ${test.name}`, function () { + this.timeout(1000); + const password = Buffer.from(test.password.substring(2), "hex"); + const salt = Buffer.from(test.salt.substring(2), "hex"); + const { N, r, p, key } = test.scrypt; + const result = (0, index_js_1.scryptSync)(password, salt, N, r, p, test.dkLen); + assert_1.default.equal(result, key); + }); + }); + tests.forEach((test) => { + it(`computes scrypt (async): ${test.name}`, async function () { + this.timeout(1000); + const password = Buffer.from(test.password.substring(2), "hex"); + const salt = Buffer.from(test.salt.substring(2), "hex"); + const { N, r, p, key } = test.scrypt; + let progressCount = 0, progressOk = true, lastProgress = -1; + const result = await (0, index_js_1.scrypt)(password, salt, N, r, p, test.dkLen, (progress) => { + if (progress < lastProgress) { + progressOk = false; + } + lastProgress = progress; + progressCount++; + }); + assert_1.default.ok(progressOk, "progress was not monotonically increasing"); + assert_1.default.ok(progressCount > 100, "progress callback was called at leat 100 times"); + assert_1.default.equal(result, key); + }); + }); +}); +describe("test hmac", function () { + const tests = (0, utils_js_1.loadTests)("hmac"); + tests.forEach((test) => { + it(`computes hmac: ${test.name}`, async function () { + const { algorithm, key, data } = test; + assert_1.default.equal((0, index_js_1.computeHmac)(algorithm, key, data), test.hmac); + }); + }); +}); +/* +describe("test registration", function() { + let hijack = ""; + function getHijack(algo: string) { + return function(...args: Array) { + hijack = `hijacked ${ algo }: ${ JSON.stringify(args) }`; + return "0x42"; + } + } + + it("hijacks keccak256", function() { + const initial = keccak256("0x"); + + keccak256.register(getHijack("kecak256")); + assert.equal(keccak256("0x"), "0x42"); + assert.equal(hijack, 'hijacked kecak256: [{}]'); + + keccak256.register(keccak256._); + assert.equal(keccak256("0x"), initial); + + keccak256.lock(); + + assert.throws(function() { + keccak256.register(getHijack("test")); + }, function(error) { + return (error.message === "keccak256 is locked"); + }); + }); + + it("hijacks sha256", function() { + const initial = sha256("0x"); + + sha256.register(getHijack("sha256")); + assert.equal(sha256("0x"), "0x42"); + assert.equal(hijack, 'hijacked sha256: [{}]'); + + sha256.register(sha256._); + assert.equal(sha256("0x"), initial); + + sha256.lock(); + + assert.throws(function() { + sha256.register(getHijack("test")); + }, function(error) { + return (error.message === "sha256 is locked"); + }); + }); + + it("hijacks sha512", function() { + const initial = sha512("0x"); + + sha512.register(getHijack("sha512")); + assert.equal(sha512("0x"), "0x42"); + assert.equal(hijack, 'hijacked sha512: [{}]'); + + sha512.register(sha512._); + assert.equal(sha512("0x"), initial); + + sha512.lock(); + + assert.throws(function() { + sha512.register(getHijack("test")); + }, function(error) { + return (error.message === "sha512 is locked"); + }); + }); + + it("hijacks pbkdf2", function() { + const initial = pbkdf2("0x", "0x", 1024, 32, "sha256"); + + pbkdf2.register(getHijack("pbkdf2")); + assert.equal(pbkdf2("0x", "0x", 1024, 32, "sha256"), "0x42"); + assert.equal(hijack, 'hijacked pbkdf2: [{},{},1024,32,"sha256"]'); + + pbkdf2.register(pbkdf2._); + assert.equal(pbkdf2("0x", "0x", 1024, 32, "sha256"), initial); + + pbkdf2.lock(); + + assert.throws(function() { + pbkdf2.register(getHijack("test")); + }, function(error) { + return (error.message === "pbkdf2 is locked"); + }); + }); + + it("hijacks scryptSync", function() { + + function getHijack(...args: Array) { + hijack = `hijacked scryptSync: ${ JSON.stringify(args) }`; + return new Uint8Array([ 0x42 ]); + } + + const initial = scryptSync("0x", "0x", 1024, 8, 1, 32); + + scryptSync.register(getHijack); + assert.equal(scryptSync("0x", "0x", 1024, 8, 1, 32), "0x42"); + assert.equal(hijack, 'hijacked scryptSync: [{},{},1024,8,1,32]'); + + scryptSync.register(scryptSync._); + assert.equal(scryptSync("0x", "0x", 1024, 8, 1, 32), initial); + + scryptSync.lock(); + + assert.throws(function() { + scryptSync.register(getHijack); + }, function(error) { + return (error.message === "scryptSync is locked"); + }); + }); + + it("hijacks scrypt", async function() { + function getHijack(...args: Array) { + hijack = `hijacked scrypt: ${ JSON.stringify(args) }`; + return Promise.resolve(new Uint8Array([ 0x42 ])); + } + + const initial = await scrypt("0x", "0x", 1024, 8, 1, 32); + + scrypt.register(getHijack); + assert.equal(await scrypt("0x", "0x", 1024, 8, 1, 32), "0x42"); + assert.equal(hijack, 'hijacked scrypt: [{},{},1024,8,1,32,null]'); + + scrypt.register(scrypt._); + assert.equal(await scrypt("0x", "0x", 1024, 8, 1, 32), initial); + + scrypt.lock(); + + assert.throws(function() { + scrypt.register(getHijack); + }, function(error) { + return (error.message === "scrypt is locked"); + }); + }); + +}); +*/ +//# sourceMappingURL=test-crypto.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-crypto.js.map b/lib.commonjs/_tests/test-crypto.js.map new file mode 100644 index 000000000..90c068f6a --- /dev/null +++ b/lib.commonjs/_tests/test-crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-crypto.js","sourceRoot":"","sources":["../../src.ts/_tests/test-crypto.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,yCAAuC;AAIvC,0CAIqB;AAGrB,QAAQ,CAAC,cAAc,EAAE;IACrB,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAe,QAAQ,CAAC,CAAC;IAEhD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,EAAE,CAAC,sBAAuB,IAAI,CAAC,IAAK,EAAE,EAAE;YACpC,gBAAM,CAAC,KAAK,CAAC,IAAA,iBAAM,EAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACjD,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH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AAmB,IAAI,CAAC,IAAI,EAAE,EAAE,KAAK;YACpC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;YACtC,gBAAM,CAAC,KAAK,CAAC,IAAA,sBAAW,EAAC,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwIE"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-hash-typeddata.js b/lib.commonjs/_tests/test-hash-typeddata.js new file mode 100644 index 000000000..575d578f0 --- /dev/null +++ b/lib.commonjs/_tests/test-hash-typeddata.js @@ -0,0 +1,21 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +describe("Tests Typed Data (EIP-712)", function () { + const tests = (0, utils_js_1.loadTests)("typed-data"); + for (const test of tests) { + it(`tests encoding typed-data: ${test.name}`, function () { + const encoder = index_js_1.TypedDataEncoder.from(test.types); + assert_1.default.equal(encoder.primaryType, test.primaryType, "primaryType"); + assert_1.default.equal(encoder.encode(test.data), test.encoded, "encoded"); + assert_1.default.equal(index_js_1.TypedDataEncoder.getPrimaryType(test.types), test.primaryType, "primaryType"); + assert_1.default.equal(index_js_1.TypedDataEncoder.hash(test.domain, test.types, test.data), test.digest, "digest"); + }); + } +}); +//# sourceMappingURL=test-hash-typeddata.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-hash-typeddata.js.map b/lib.commonjs/_tests/test-hash-typeddata.js.map new file mode 100644 index 000000000..c8dc25ff6 --- /dev/null +++ b/lib.commonjs/_tests/test-hash-typeddata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-hash-typeddata.js","sourceRoot":"","sources":["../../src.ts/_tests/test-hash-typeddata.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAC5B,yCAAuC;AAGvC,0CAA+C;AAG/C,QAAQ,CAAC,4BAA4B,EAAE;IACnC,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAoB,YAAY,CAAC,CAAC;IACzD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,EAAE,CAAC,8BAA+B,IAAI,CAAC,IAAK,EAAE,EAAE;YAC5C,MAAM,OAAO,GAAG,2BAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAClD,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;YACnE,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;YAEjE,gBAAM,CAAC,KAAK,CAAC,2BAAgB,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;YAC3F,gBAAM,CAAC,KAAK,CAAC,2BAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACnG,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-hash.js b/lib.commonjs/_tests/test-hash.js new file mode 100644 index 000000000..fb88da02e --- /dev/null +++ b/lib.commonjs/_tests/test-hash.js @@ -0,0 +1,112 @@ +"use strict"; +/* +import assert from "assert"; +import { loadTests } from "./utils.js" +import type { TestCaseNamehash } from "./types.js"; + +import { dnsEncode, isValidName, namehash } from "../index.js"; + +describe("Tests Namehash", function() { + const tests = loadTests("namehash"); + for (const test of tests) { + it(`hashes ENS names: ${ JSON.stringify(test.ensName) }`, function() { + const actual = namehash(test.ensName); + + assert.equal(actual, test.namehash, "namehash"); + + // The empty string is not a valid ENS name + if (test.ensName) { + assert.ok(isValidName(test.ensName), "isValidName"); + } + }); + } +}); + +describe("Tests Bad ENS Names", function() { + const badTests: Array<{ ensName: any, prefix: string }> = [ + { ensName: ".", prefix: "missing component" }, + { ensName:"..", prefix: "missing component" }, + { ensName:"ricmoo..eth", prefix: "missing component" }, + { ensName:"ricmoo...eth", prefix: "missing component" }, + { ensName:".foo", prefix: "missing component" }, + { ensName:"foo.", prefix: "missing component" }, + { ensName: 1234, prefix: "not a string" }, + { ensName: true, prefix: "not a string" }, + ]; + + // The empty string is not a valid name, but has a valid namehash + // (the zero hash) as it is the base case for recursion + it("empty ENS name", function() { + assert.ok(!isValidName(""), "!isValidName"); + }); + + for (const { ensName, prefix } of badTests) { + it(`fails on bad ENS name: ${ JSON.stringify(ensName) }`, function() { + assert.ok(!isValidName(ensName), "!isValidName"); + assert.throws(() => { + const result = namehash(ensName); + console.log(result); + }, (error) => { + const errorPrefix = `invalid ENS name; ${ prefix }`; + return (error.code === "INVALID_ARGUMENT" && + error.argument === "name" && error.value === ensName && + error.message.substring(0, errorPrefix.length) === errorPrefix); + }); + }); + } +}); + +describe("Tests DNS Encoding", function() { + const tests: Array<{ ensName: string, dnsEncoded: string}> = [ + { ensName: "", dnsEncoded: "0x00" }, + { ensName: "ricmoo.eth", dnsEncoded: "0x067269636d6f6f0365746800" }, + ]; + + for (const { ensName, dnsEncoded } of tests) { + it(`computes the DNS Encoding: ${ JSON.stringify(ensName) }`, function() { + assert.equal(dnsEncode(ensName), dnsEncoded, "dnsEncoded"); + }); + } +}); + +describe("Tests DNS Names", function() { + const badTests: Array<{ ensName: any, prefix: string}> = [ + { ensName: ".", prefix: "invalid DNS name; missing component" }, + { ensName: "foo..bar", prefix: "invalid DNS name; missing component" }, + { ensName: ".foo", prefix: "invalid DNS name; missing component" }, + { ensName: "foo.", prefix: "invalid DNS name; missing component" }, + { ensName: 1234, prefix: "invalid DNS name; not a string" }, + { ensName: true, prefix: "invalid DNS name; not a string" }, + ]; + + for (const { ensName, prefix } of badTests) { + it(`fails on bad DNS name: ${ JSON.stringify(ensName) }`, function() { + assert.throws(() => { + const result = dnsEncode(ensName); + console.log(result); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "name" && error.value === ensName && + error.message.substring(0, prefix.length) === prefix); + }); + }); + } + + { + const ensName = "foobar012345678901234567890123456789012345678901234567890123456789"; + const prefix = "too long"; + it(`fails on bad DNS name: ${ JSON.stringify(ensName) }`, function() { + assert.throws(() => { + const result = dnsEncode(ensName); + console.log(result); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "value" && error.value === ensName && + error.message.substring(0, prefix.length) === prefix); + }); + }); + } + +}); +*/ +//# sourceMappingURL=test-hash.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-hash.js.map b/lib.commonjs/_tests/test-hash.js.map new file mode 100644 index 000000000..54c88f89b --- /dev/null +++ b/lib.commonjs/_tests/test-hash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-hash.js","sourceRoot":"","sources":["../../src.ts/_tests/test-hash.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6GE"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-rlp.js b/lib.commonjs/_tests/test-rlp.js new file mode 100644 index 000000000..8df7a29a3 --- /dev/null +++ b/lib.commonjs/_tests/test-rlp.js @@ -0,0 +1,93 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +describe("Test RLP Coder", function () { + const tests = (0, utils_js_1.loadTests)("rlp"); + tests.forEach(({ name, encoded, decoded }) => { + it(`encodes RLP: ${name}`, function () { + assert_1.default.equal((0, index_js_1.encodeRlp)(decoded), encoded); + }); + }); + tests.forEach(({ name, encoded, decoded }) => { + it(`decodes RLP: ${name}`, function () { + assert_1.default.deepStrictEqual((0, index_js_1.decodeRlp)(encoded), decoded); + }); + }); +}); +describe("Test bad RLP Data", function () { + it("fails encoding data with invalid values", function () { + assert_1.default.throws(() => { + (0, index_js_1.encodeRlp)(["0x1234", 1234]); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "object" && + error.value === 1234); + }); + }); + it("fails decoding data with trailing junk", function () { + assert_1.default.throws(() => { + // Zeros_1 + (0, index_js_1.decodeRlp)("0x0042"); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^unexpected junk after rlp payload/) && + error.argument === "data" && + error.value === "0x0042"); + }); + }); + it("fails decoding short data", function () { + assert_1.default.throws(() => { + (0, index_js_1.decodeRlp)("0x"); + }, (error) => { + return (error.code === "BUFFER_OVERRUN" && + error.message.match(/^data too short/) && + Buffer.from(error.buffer).toString("hex") === "" && + error.offset === 1 && + error.length === 0); + }); + }); + it("fails decoding short data in child", function () { + assert_1.default.throws(() => { + (0, index_js_1.decodeRlp)("0xc8880102030405060708"); + }, (error) => { + return (error.code === "BUFFER_OVERRUN" && + error.message.match(/^child data too short/) && + Buffer.from(error.buffer).toString("hex") === "c8880102030405060708" && + error.offset === 0 && + error.length === 8); + }); + }); + it("fails decoding short segment data", function () { + assert_1.default.throws(() => { + // [["0x4243"], ["0x3145"]] = 0xc8 c3 82 4243 c3 82 3145 + // XXXX + (0, index_js_1.decodeRlp)("0xc8c382c3823145"); + }, (error) => { + return (error.code === "BUFFER_OVERRUN" && + error.message.match(/^data short segment too short/) && + Buffer.from(error.buffer).toString("hex") === "c8c382c3823145" && + error.offset === 9 && + error.length === 7); + }); + }); +}); +/* + utils.RLP.encode([["0x4243"], ["0x3145"]]) + + 0xc8 c3 82 4243 c3 82 3145 + + { + "name": "arrayShort2", + "decoded": [ + "0x48656c6c6f20576f726c64", + "0x48656c6c6f20576f726c64" + ], + "encoded": "0xd8 8b 48656c6c6f20576f726c64 8b 48656c6c6f20576f726c64" + }, +*/ +//# sourceMappingURL=test-rlp.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-rlp.js.map b/lib.commonjs/_tests/test-rlp.js.map new file mode 100644 index 000000000..b4f2bf31c --- /dev/null +++ b/lib.commonjs/_tests/test-rlp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-rlp.js","sourceRoot":"","sources":["../../src.ts/_tests/test-rlp.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,yCAAuC;AAEvC,0CAAmD;AAInD,QAAQ,CAAC,gBAAgB,EAAE;IAEvB,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAc,KAAK,CAAC,CAAC;IAE5C,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE;QACzC,EAAE,CAAC,gBAAiB,IAAK,EAAE,EAAE;YACzB,gBAAM,CAAC,KAAK,CAAC,IAAA,oBAAS,EAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE;QACzC,EAAE,CAAC,gBAAiB,IAAK,EAAE,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K,CAAC,CAAC,CAAA;QAC3B,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC;AAEH;;;;;;;;;;;;;EAaE"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-transaction.js b/lib.commonjs/_tests/test-transaction.js new file mode 100644 index 000000000..4b7bdad24 --- /dev/null +++ b/lib.commonjs/_tests/test-transaction.js @@ -0,0 +1,263 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +const BN_0 = BigInt(0); +describe("Tests Unsigned Transaction Serializing", function () { + const tests = (0, utils_js_1.loadTests)("transactions"); + for (const test of tests) { + it(`serialized unsigned legacy transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }); + // Use the testcase sans the chainId for a legacy test + if (txData.chainId != null && parseInt(txData.chainId) != 0) { + txData.chainId = "0x00"; + } + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.unsignedSerialized, test.unsignedLegacy, "unsignedLegacy"); + }); + } + for (const test of tests) { + // Unsupported parameters for EIP-155; i.e. unspecified chain ID + if (!test.unsignedEip155) { + continue; + } + it(`serialized unsigned EIP-155 transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }); + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.unsignedSerialized, test.unsignedEip155, "unsignedEip155"); + }); + } + for (const test of tests) { + it(`serialized unsigned Berlin transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 1, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }); + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.unsignedSerialized, test.unsignedBerlin, "unsignedBerlin"); + }); + } + for (const test of tests) { + it(`serialized unsigned London transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { type: 2 }); + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.unsignedSerialized, test.unsignedLondon, "unsignedLondon"); + }); + } +}); +describe("Tests Signed Transaction Serializing", function () { + const tests = (0, utils_js_1.loadTests)("transactions"); + for (const test of tests) { + it(`serialized signed legacy transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined, + signature: test.signatureLegacy + }); + // Use the testcase sans the chainId for a legacy test + if (txData.chainId != null && parseInt(txData.chainId) != 0) { + txData.chainId = "0x00"; + } + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.serialized, test.signedLegacy, "signedLegacy"); + }); + } + for (const test of tests) { + if (!test.unsignedEip155) { + continue; + } + it(`serialized signed EIP-155 transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined, + signature: test.signatureEip155 + }); + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.serialized, test.signedEip155, "signedEip155"); + }); + } + for (const test of tests) { + it(`serialized signed Berlin transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 1, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }, { signature: test.signatureBerlin }); + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.serialized, test.signedBerlin, "signedBerlin"); + }); + } + for (const test of tests) { + it(`serialized signed London transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 2, + signature: test.signatureLondon + }); + const tx = index_js_1.Transaction.from(txData); + assert_1.default.equal(tx.serialized, test.signedLondon, "signedLondon"); + }); + } +}); +function assertTxUint(actual, _expected, name) { + const expected = (_expected != null ? BigInt(_expected) : null); + assert_1.default.equal(actual, expected, name); +} +function assertTxEqual(actual, expected) { + assert_1.default.equal(actual.to, expected.to, "to"); + assert_1.default.equal(actual.nonce, expected.nonce, "nonce"); + assertTxUint(actual.gasLimit, expected.gasLimit, "gasLimit"); + assertTxUint(actual.gasPrice, expected.gasPrice, "gasPrice"); + assertTxUint(actual.maxFeePerGas, expected.maxFeePerGas, "maxFeePerGas"); + assertTxUint(actual.maxPriorityFeePerGas, expected.maxPriorityFeePerGas, "maxPriorityFeePerGas"); + assert_1.default.equal(actual.data, expected.data, "data"); + assertTxUint(actual.value, expected.value, "value"); + if (expected.accessList) { + assert_1.default.equal(JSON.stringify(actual.accessList), JSON.stringify(expected.accessList), "accessList"); + } + else { + assert_1.default.equal(actual.accessList, null, "accessList:!null"); + } + assertTxUint(actual.chainId, expected.chainId, "chainId"); +} +function addDefault(tx, key, defaultValue) { + if (tx[key] == null) { + tx[key] = defaultValue; + } +} +function addDefaults(tx) { + tx = Object.assign({}, tx); + addDefault(tx, "nonce", 0); + addDefault(tx, "gasLimit", BN_0); + addDefault(tx, "gasPrice", BN_0); + addDefault(tx, "maxFeePerGas", BN_0); + addDefault(tx, "maxPriorityFeePerGas", BN_0); + addDefault(tx, "value", BN_0); + addDefault(tx, "data", "0x"); + addDefault(tx, "accessList", []); + addDefault(tx, "chainId", BN_0); + return tx; +} +describe("Tests Unsigned Transaction Parsing", function () { + const tests = (0, utils_js_1.loadTests)("transactions"); + for (const test of tests) { + it(`parses unsigned legacy transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.unsignedLegacy); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + expected.chainId = BN_0; + assertTxEqual(tx, expected); + }); + } + for (const test of tests) { + if (!test.unsignedEip155) { + continue; + } + it(`parses unsigned EIP-155 transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.unsignedEip155); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + assertTxEqual(tx, expected); + }); + } + for (const test of tests) { + it(`parses unsigned Berlin transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.unsignedBerlin); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + assertTxEqual(tx, expected); + }); + } + for (const test of tests) { + it(`parses unsigned London transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.unsignedLondon); + const expected = addDefaults(test.transaction); + expected.gasPrice = null; + assertTxEqual(tx, expected); + }); + } +}); +describe("Tests Signed Transaction Parsing", function () { + const tests = (0, utils_js_1.loadTests)("transactions"); + for (const test of tests) { + it(`parses signed legacy transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.signedLegacy); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + expected.chainId = BN_0; + assertTxEqual(tx, expected); + assert_1.default.ok(!!tx.signature, "signature:!null"); + assert_1.default.equal(tx.signature.r, test.signatureLegacy.r, "signature.r"); + assert_1.default.equal(tx.signature.s, test.signatureLegacy.s, "signature.s"); + assert_1.default.equal(BigInt(tx.signature.v), BigInt(test.signatureLegacy.v), "signature.v"); + }); + } + for (const test of tests) { + if (!test.unsignedEip155) { + continue; + } + it(`parses signed EIP-155 transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.signedEip155); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + assertTxEqual(tx, expected); + assert_1.default.ok(!!tx.signature, "signature:!null"); + assert_1.default.equal(tx.signature.r, test.signatureEip155.r, "signature.r"); + assert_1.default.equal(tx.signature.s, test.signatureEip155.s, "signature.s"); + assert_1.default.equal(tx.signature.networkV, BigInt(test.signatureEip155.v), "signature.v"); + }); + } + for (const test of tests) { + it(`parses signed Berlin transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.signedBerlin); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + assertTxEqual(tx, expected); + assert_1.default.ok(!!tx.signature, "signature:!null"); + assert_1.default.equal(tx.signature.r, test.signatureBerlin.r, "signature.r"); + assert_1.default.equal(tx.signature.s, test.signatureBerlin.s, "signature.s"); + assert_1.default.equal(tx.signature.yParity, parseInt(test.signatureBerlin.v), "signature.v"); + }); + } + for (const test of tests) { + it(`parses signed London transaction: ${test.name}`, function () { + const tx = index_js_1.Transaction.from(test.signedLondon); + const expected = addDefaults(test.transaction); + expected.gasPrice = null; + assertTxEqual(tx, expected); + assert_1.default.ok(!!tx.signature, "signature:!null"); + assert_1.default.equal(tx.signature.r, test.signatureLondon.r, "signature.r"); + assert_1.default.equal(tx.signature.s, test.signatureLondon.s, "signature.s"); + assert_1.default.equal(tx.signature.yParity, parseInt(test.signatureLondon.v), "signature.v"); + }); + } +}); +//# sourceMappingURL=test-transaction.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-transaction.js.map b/lib.commonjs/_tests/test-transaction.js.map new file mode 100644 index 000000000..a8ddb1b67 --- /dev/null +++ b/lib.commonjs/_tests/test-transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-transaction.js","sourceRoot":"","sources":["../../src.ts/_tests/test-transaction.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAC5B,yCAAuC;AAIvC,0CAA0C;AAG1C,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvB,QAAQ,CAAC,wCAAwC,EAAE;IAC/C,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAsB,cAAc,CAAC,CAAC;IAE7D,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,EAAE,CAAC,2CAA4C,IAAI,CAAC,IAAK,EAAE,EAAE;YACzD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAG,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AM,CAAC,KAAK,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;QACxF,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet-hd.js b/lib.commonjs/_tests/test-wallet-hd.js new file mode 100644 index 000000000..50028e3e7 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet-hd.js @@ -0,0 +1,125 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const wordlists_js_1 = require("../wordlists/wordlists.js"); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +const decoder = new TextDecoder(); +function fromHex(hex) { + const data = Buffer.from(hex.substring(2), "hex"); + return decoder.decode(data); +} +describe("Test HDWallets", function () { + function checkWallet(wallet, test) { + assert_1.default.equal(wallet.chainCode, test.chainCode, "chainCode"); + assert_1.default.equal(wallet.depth, test.depth, "depth"); + assert_1.default.equal(wallet.index, test.index, "index"); + assert_1.default.equal(wallet.fingerprint, test.fingerprint, "fingerprint"); + assert_1.default.equal(wallet.parentFingerprint, test.parentFingerprint, "parentFingerprint"); + assert_1.default.equal(wallet.publicKey, test.publicKey, "publicKey"); + if (wallet instanceof index_js_1.HDNodeWallet) { + assert_1.default.equal(wallet.extendedKey, test.xpriv, "xpriv"); + assert_1.default.equal(wallet.privateKey, test.privateKey, "privateKey"); + assert_1.default.equal(wallet.neuter().extendedKey, test.xpub, "xpub"); + } + else if (wallet instanceof index_js_1.HDNodeVoidWallet) { + assert_1.default.equal(wallet.extendedKey, test.xpub, "xpub"); + } + } + const tests = (0, utils_js_1.loadTests)("mnemonics"); + const checks = []; + tests.forEach((test) => { + // The phrase and password are stored in the test as hex so they + // are safe as ascii7 values for viewing, printing, etc. + const phrase = fromHex(test.phrase); + const password = fromHex(test.password); + const wordlist = wordlists_js_1.wordlists[test.locale]; + if (wordlist == null) { + it(`tests ${test.name}`, function () { + this.skip(); + }); + return; + } + const mnemonic = index_js_1.Mnemonic.fromPhrase(phrase, password, wordlist); + function checkMnemonic(actual) { + assert_1.default.equal(actual.phrase, phrase, "phrase"); + assert_1.default.equal(actual.password, password, "password"); + assert_1.default.equal(actual.wordlist.locale, test.locale, "locale"); + assert_1.default.equal(actual.entropy, mnemonic.entropy, "entropy"); + assert_1.default.equal(actual.computeSeed(), mnemonic.computeSeed(), "seed"); + } + checks.push({ + phrase, password, wordlist, mnemonic, checkMnemonic, test + }); + }); + for (const { test, checkMnemonic, phrase, password, wordlist } of checks) { + it(`computes the HD keys by mnemonic: ${test.name}`, function () { + for (const subtest of test.nodes) { + const w = index_js_1.HDNodeWallet.fromPhrase(phrase, password, subtest.path, wordlist); + assert_1.default.ok(w instanceof index_js_1.HDNodeWallet, "instanceof HDNodeWallet"); + assert_1.default.equal(w.path, subtest.path, "path"); + checkWallet(w, subtest); + assert_1.default.ok(!!w.mnemonic, "has mnemonic"); + checkMnemonic(w.mnemonic); + } + }); + } + for (const { test } of checks) { + it(`computes the HD keys by entropy: ${test.name}`, function () { + const seedRoot = index_js_1.HDNodeWallet.fromSeed(test.seed); + for (const subtest of test.nodes) { + const w = seedRoot.derivePath(subtest.path); + assert_1.default.ok(w instanceof index_js_1.HDNodeWallet, "instanceof HDNodeWallet"); + assert_1.default.equal(w.path, subtest.path, "path"); + checkWallet(w, subtest); + assert_1.default.equal(w.mnemonic, null); + } + }); + } + for (const { test } of checks) { + it(`computes the HD keys by enxtended private key: ${test.name}`, function () { + for (const subtest of test.nodes) { + const w = index_js_1.HDNodeWallet.fromExtendedKey(subtest.xpriv); + assert_1.default.ok(w instanceof index_js_1.HDNodeWallet, "instanceof HDNodeWallet"); + checkWallet(w, subtest); + assert_1.default.equal(w.mnemonic, null); + } + }); + } + for (const { test, phrase, password, wordlist } of checks) { + it(`computes the neutered HD keys by paths: ${test.name}`, function () { + const root = index_js_1.HDNodeWallet.fromPhrase(phrase, password, "m", wordlist).neuter(); + for (const subtest of test.nodes) { + if (subtest.path.indexOf("'") >= 0) { + assert_1.default.throws(() => { + const w = root.derivePath(subtest.path); + console.log(w); + }, (error) => { + return (error.code === "UNSUPPORTED_OPERATION" && + error.message.match(/^cannot derive child of neutered node/) && + error.operation === "deriveChild"); + }); + } + else { + const w = root.derivePath(subtest.path); + assert_1.default.ok(w instanceof index_js_1.HDNodeVoidWallet, "instanceof HDNodeVoidWallet"); + assert_1.default.equal(w.path, subtest.path, "path"); + checkWallet(w, subtest); + } + } + }); + } + for (const { test } of checks) { + it(`computes the neutered HD keys by enxtended public key: ${test.name}`, function () { + for (const subtest of test.nodes) { + const w = index_js_1.HDNodeWallet.fromExtendedKey(subtest.xpub); + assert_1.default.ok(w instanceof index_js_1.HDNodeVoidWallet, "instanceof HDNodeVoidWallet"); + checkWallet(w, subtest); + } + }); + } +}); +//# sourceMappingURL=test-wallet-hd.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet-hd.js.map b/lib.commonjs/_tests/test-wallet-hd.js.map new file mode 100644 index 000000000..9b9dc147d --- /dev/null +++ b/lib.commonjs/_tests/test-wallet-hd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet-hd.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet-hd.ts"],"names":[],"mappings":";;;;;AACA,oDAA4B;AAE5B,4DAAsD;AAEtD,yCAAuC;AAEvC,0CAAuE;AAcvE,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,SAAS,OAAO,CAAC,GAAW;IACxB,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;A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C,IAAI,CAAC,CAAC;wBACxC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;oBACnB,CAAC,EAAE,CAAC,KAAU,EAAE,EAAE;wBACd,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,uBAAuB;4BAC1C,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC;4BAC5D,KAAK,CAAC,SAAS,KAAK,aAAa,CAAC,CAAC;oBAC3C,CAAC,CAAC,CAAC;iBACN;qBAAM;oBACH,MAAM,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;oBACxC,gBAAM,CAAC,EAAE,CAAC,CAAC,YAAY,2BAAgB,EAAE,6BAA6B,CAAC,CAAC;oBACxE,gBAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;oBAC1C,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;iBAC3B;aACJ;QACL,CAAC,CAAC,CAAC;KACN;IAED,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,MAAM,EAAE;QAC3B,EAAE,CAAC,0DAA2D,IAAI,CAAC,IAAK,EAAE,EAAE;YACxE,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE;gBAC9B,MAAM,CAAC,GAAG,uBAAY,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;gBACrD,gBAAM,CAAC,EAAE,CAAC,CAAC,YAAY,2BAAgB,EAAE,6BAA6B,CAAC,CAAC;gBACxE,WAAW,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;aAC3B;QACL,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet-json.js b/lib.commonjs/_tests/test-wallet-json.js new file mode 100644 index 000000000..23808b587 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet-json.js @@ -0,0 +1,64 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +describe("Tests JSON Wallet Formats", function () { + const tests = (0, utils_js_1.loadTests)("wallets"); + tests.forEach((test) => { + if (test.type !== "crowdsale") { + return; + } + it(`tests decrypting Crowdsale JSON: ${test.name}`, async function () { + const password = Buffer.from(test.password.substring(2), "hex"); + const account = (0, index_js_1.decryptCrowdsaleJson)(test.content, password); + assert_1.default.equal(account.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + if (test.type !== "keystore") { + return; + } + it(`tests decrypting Keystore JSON (sync): ${test.name}`, function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const account = (0, index_js_1.decryptKeystoreJsonSync)(test.content, password); + //console.log(account); + assert_1.default.equal(account.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + if (test.type !== "keystore") { + return; + } + it(`tests decrypting Keystore JSON (async): ${test.name}`, async function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const account = await (0, index_js_1.decryptKeystoreJson)(test.content, password); + //console.log(account); + assert_1.default.equal(account.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + it(`tests decrypting JSON (sync): ${test.name}`, function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const wallet = index_js_1.Wallet.fromEncryptedJsonSync(test.content, password); + //console.log(wallet); + assert_1.default.equal(wallet.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + it(`tests decrypting JSON (async): ${test.name}`, async function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const wallet = await index_js_1.Wallet.fromEncryptedJson(test.content, password); + //console.log(wallet); + assert_1.default.equal(wallet.address, test.address, "address"); + }); + }); +}); +//# sourceMappingURL=test-wallet-json.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet-json.js.map b/lib.commonjs/_tests/test-wallet-json.js.map new file mode 100644 index 000000000..8e1635949 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet-json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet-json.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet-json.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,yCAAuC;AAIvC,0CAIqB;AAErB,QAAQ,CAAC,2BAA2B,EAAE;IACjC,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAiB,SAAS,CAAC,CAAC;IACnD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,EAAE;YAAE,OAAO;SAAE;QAC1C,EAAE,CAAC,oCAAqC,IAAI,CAAC,IAAK,EAAE,EAAE,KAAK;YACvD,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAChE,MAAM,OAAO,GAAG,IAAA,+BAAoB,EAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC7D,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,IAAI,IAAI,CAAC,IAAI,KAAK,UAAU,EAAE;YAAE,OAAO;SAAE;QACzC,EAAE,CAAC,0CAA2C,IAAI,CAAC,IAAK,EAAE,EAAE;YACxD,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,C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IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACpE,sBAAsB;YACtB,gBAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC1D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,EAAE,CAAC,kCAAmC,IAAI,CAAC,IAAK,EAAE,EAAE,KAAK;YACrD,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAChE,MAAM,MAAM,GAAG,MAAM,iBAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACtE,sBAAsB;YACtB,gBAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC1D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACR,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet-mnemonic.js b/lib.commonjs/_tests/test-wallet-mnemonic.js new file mode 100644 index 000000000..706e10bd9 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet-mnemonic.js @@ -0,0 +1,126 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const index_js_1 = require("../crypto/index.js"); +const utf8_js_1 = require("../utils/utf8.js"); +const wordlists_js_1 = require("../wordlists/wordlists.js"); +const index_js_2 = require("../index.js"); +const utils_js_1 = require("./utils.js"); +const decoder = new TextDecoder(); +function fromHex(hex) { + const data = Buffer.from(hex.substring(2), "hex"); + return decoder.decode(data); +} +function repeat(text, length) { + const result = []; + while (result.length < length) { + result.push(text); + } + return result; +} +describe("Tests Mnemonics", function () { + const tests = (0, utils_js_1.loadTests)("mnemonics"); + function runTest(phrase, mnemonic, test) { + assert_1.default.ok(index_js_2.Mnemonic.isValidMnemonic(phrase, mnemonic.wordlist), "isValidMnemonic"); + if (test.locale === "en") { + assert_1.default.ok(index_js_2.Mnemonic.isValidMnemonic(phrase), "isValidMnemonic (default)"); + } + assert_1.default.equal(mnemonic.wordlist.locale, test.locale, "locale"); + assert_1.default.equal(mnemonic.entropy, test.entropy, "entropy"); + assert_1.default.equal(mnemonic.computeSeed(), test.seed, "seed"); + assert_1.default.equal((0, index_js_1.sha256)((0, utf8_js_1.toUtf8Bytes)(phrase)), test.phraseHash, "phraseHash"); + } + for (const test of tests) { + const wordlist = wordlists_js_1.wordlists[test.locale]; + it(`computes mnemonic from phrase: ${test.name}`, function () { + if (wordlist == null) { + this.skip(); + return; + } + const phrase = fromHex(test.phrase); + const password = fromHex(test.password); + const mnemonic = index_js_2.Mnemonic.fromPhrase(phrase, password, wordlist); + runTest(phrase, mnemonic, test); + }); + } + for (const test of tests) { + const wordlist = wordlists_js_1.wordlists[test.locale]; + it(`computes mnemonic from entropy: ${test.name}`, function () { + if (wordlist == null) { + this.skip(); + return; + } + const phrase = fromHex(test.phrase); + const password = fromHex(test.password); + const mnemonic = index_js_2.Mnemonic.fromEntropy(test.entropy, password, wordlist); + runTest(phrase, mnemonic, test); + }); + } +}); +describe("Tests Bad Mnemonics Fail", function () { + const badLengths = [ + repeat("abandon", 9), + repeat("abandon", 16), + repeat("abandon", 27), // 27 words; too long + ]; + for (const _phrase of badLengths) { + const phrase = _phrase.join(" "); + it(`fails on invalid mnemonic length: ${_phrase.length}`, function () { + assert_1.default.ok(!index_js_2.Mnemonic.isValidMnemonic(phrase)); + assert_1.default.throws(function () { + index_js_2.Mnemonic.fromPhrase(phrase); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid mnemonic length/) && + error.argument === "mnemonic" && + error.value === "[ REDACTED ]"); + }); + }); + } + it("fails on invalid mnemonic word", function () { + const phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon wagmi"; + assert_1.default.ok(!index_js_2.Mnemonic.isValidMnemonic(phrase)); + assert_1.default.throws(function () { + index_js_2.Mnemonic.fromPhrase(phrase); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid mnemonic word at index 11/) && + error.argument === "mnemonic" && + error.value === "[ REDACTED ]"); + }); + }); + it("fails on invalid mnemonic checksum", function () { + const phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"; + assert_1.default.ok(!index_js_2.Mnemonic.isValidMnemonic(phrase)); + assert_1.default.throws(function () { + index_js_2.Mnemonic.fromPhrase(phrase); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid mnemonic checksum/) && + error.argument === "mnemonic" && + error.value === "[ REDACTED ]"); + }); + }); + const badEntropyLengths = [ + repeat("42", 12), + repeat("42", 15), + repeat("42", 36), // 36 bytes; too long + ]; + for (const _entropy of badEntropyLengths) { + const entropy = "0x" + _entropy.join(""); + it(`fails on invalid entropy length: ${_entropy.length}`, function () { + assert_1.default.throws(function () { + index_js_2.Mnemonic.fromEntropy(entropy); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid entropy size/) && + error.argument === "entropy" && + error.value === "[ REDACTED ]"); + }); + }); + } +}); +//# sourceMappingURL=test-wallet-mnemonic.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet-mnemonic.js.map b/lib.commonjs/_tests/test-wallet-mnemonic.js.map new file mode 100644 index 000000000..a46cb1f84 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet-mnemonic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet-mnemonic.js","sourceRoot":"","sources":["../../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,CAAC,MAAM,CAAC;gBACV,mBAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YAClC,CAAC,EAAE,UAAS,KAAU;gBAClB,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,kBAAkB;oBACrC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC;oBAC5C,KAAK,CAAC,QAAQ,KAAK,SAAS;oBAC5B,KAAK,CAAC,KAAK,KAAK,cAAc,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet.js b/lib.commonjs/_tests/test-wallet.js new file mode 100644 index 000000000..ce8eb4944 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet.js @@ -0,0 +1,77 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const utils_js_1 = require("./utils.js"); +const index_js_1 = require("../index.js"); +describe("Test Private Key Wallet", function () { + const tests = (0, utils_js_1.loadTests)("accounts"); + tests.forEach(({ name, privateKey, address }) => { + it(`creates wallet: ${name}`, function () { + const wallet = new index_js_1.Wallet(privateKey); + assert_1.default.equal(wallet.privateKey, privateKey); + assert_1.default.equal(wallet.address, address); + }); + }); +}); +describe("Test Transaction Signing", function () { + const tests = (0, utils_js_1.loadTests)("transactions"); + for (const test of tests) { + it(`tests signing a legacy transaction: ${test.name}`, async function () { + const wallet = new index_js_1.Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 0, accessList: undefined, maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }); + // Use the testcase sans the chainId for a legacy test + if (txData.chainId != null && parseInt(txData.chainId) != 0) { + txData.chainId = "0x00"; + } + const signed = await wallet.signTransaction(txData); + assert_1.default.equal(signed, test.signedLegacy, "signedLegacy"); + }); + } + for (const test of tests) { + if (!test.signedEip155) { + continue; + } + it(`tests signing an EIP-155 transaction: ${test.name}`, async function () { + const wallet = new index_js_1.Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 0, accessList: undefined, maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }); + const signed = await wallet.signTransaction(txData); + assert_1.default.equal(signed, test.signedEip155, "signedEip155"); + }); + } + for (const test of tests) { + it(`tests signing a Berlin transaction: ${test.name}`, async function () { + const wallet = new index_js_1.Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 1, maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }); + const signed = await wallet.signTransaction(txData); + assert_1.default.equal(signed, test.signedBerlin, "signedBerlin"); + }); + } + for (const test of tests) { + it(`tests signing a London transaction: ${test.name}`, async function () { + const wallet = new index_js_1.Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 2 }); + const signed = await wallet.signTransaction(txData); + assert_1.default.equal(signed, test.signedLondon, "signedLondon"); + }); + } +}); +describe("Test Message Signing (EIP-191)", function () { +}); +describe("Test Typed-Data Signing (EIP-712)", function () { + const tests = (0, utils_js_1.loadTests)("typed-data"); + for (const test of tests) { + const { privateKey, signature } = test; + if (privateKey == null || signature == null) { + continue; + } + it(`tests signing typed-data: ${test.name}`, async function () { + const wallet = new index_js_1.Wallet(privateKey); + const sig = await wallet.signTypedData(test.domain, test.types, test.data); + assert_1.default.equal(sig, signature, "signature"); + }); + } +}); +//# sourceMappingURL=test-wallet.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wallet.js.map b/lib.commonjs/_tests/test-wallet.js.map new file mode 100644 index 000000000..9e0e9c546 --- /dev/null +++ b/lib.commonjs/_tests/test-wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,yCAAuC;AAOvC,0CAAqC;AAGrC,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,CAAC;QAC9C,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wordlists.js b/lib.commonjs/_tests/test-wordlists.js new file mode 100644 index 000000000..1dab0bdb7 --- /dev/null +++ b/lib.commonjs/_tests/test-wordlists.js @@ -0,0 +1,71 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const index_js_1 = require("../index.js"); +const utils_js_1 = require("./utils.js"); +describe('Check Wordlists', function () { + const tests = (0, utils_js_1.loadTests)("wordlists"); + tests.forEach((test) => { + let wordlist = index_js_1.wordlists[test.locale]; + if (wordlist == null) { + return; + } + it(`matches wordlists: ${test.locale}`, function () { + const words = test.content.split('\n'); + let check = ""; + for (let i = 0; i < 2048; i++) { + let word = wordlist.getWord(i); + check += (word + "\n"); + assert_1.default.equal(word, words[i]); + assert_1.default.equal(wordlist.getWordIndex(word), i); + } + assert_1.default.equal(check, test.content); + }); + }); + tests.forEach((test) => { + let wordlist = index_js_1.wordlists[test.locale]; + if (wordlist == null) { + return; + } + it(`splitting and joining are equivalent: ${test.locale}`, function () { + const words = []; + for (let i = 0; i < 12; i++) { + words.push(wordlist.getWord(i)); + } + const phrase = wordlist.join(words); + const words2 = wordlist.split(phrase); + const phrase2 = wordlist.join(words2); + assert_1.default.deepStrictEqual(words2, words, "split words"); + assert_1.default.deepStrictEqual(phrase2, phrase, "re-joined words"); + }); + }); + tests.forEach((test) => { + let wordlist = index_js_1.wordlists[test.locale]; + if (wordlist == null) { + return; + } + it(`handles out-of-range values: ${test.locale}`, function () { + assert_1.default.equal(wordlist.getWordIndex("foobar"), -1); + assert_1.default.throws(() => { + wordlist.getWord(-1); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid word index/) && + error.argument === "index" && + error.value === -1); + }); + assert_1.default.throws(() => { + wordlist.getWord(2048); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid word index/) && + error.argument === "index" && + error.value === 2048); + }); + }); + }); +}); +//# sourceMappingURL=test-wordlists.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-wordlists.js.map b/lib.commonjs/_tests/test-wordlists.js.map new file mode 100644 index 000000000..64cf4f9dc --- /dev/null +++ b/lib.commonjs/_tests/test-wordlists.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wordlists.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wordlists.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,0CAAwC;AAExC,yCAAuC;AAKvC,QAAQ,CAAC,iBAAiB,EAAE;IACxB,MAAM,KAAK,GAAG,IAAA,oBAAS,EAAmB,WAAW,CAAC,CAAC;IAEvD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,IAAI,QAAQ,GAAG,oBAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACtC,IAAI,QAAQ,IAAI,IAAI,EAAE;YAAE,OAAO;SAAE;QAEjC,EAAE,CAAC,sBAAuB,IAAI,CAAC,MAAO,EAAE,EAAE;YACtC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAEvC,IAAI,KAAK,GAAG,EAAE,CAAC;YACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;gBAC3B,IAAI,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC/B,KAAK,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;gBACvB,gBAAM,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC7B,gBAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,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AAE,EAAE;YAChD,gBAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAElD,gBAAM,CAAC,MAAM,CAAC,GAAG,EAAE;gBACf,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YACzB,CAAC,EAAE,CAAC,KAAU,EAAE,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,kBAAkB;oBACrC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC;oBAC1C,KAAK,CAAC,QAAQ,KAAK,OAAO;oBAC1B,KAAK,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;YAEH,gBAAM,CAAC,MAAM,CAAC,GAAG,EAAE;gBACf,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YAC3B,CAAC,EAAE,CAAC,KAAU,EAAE,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,kBAAkB;oBACrC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC;oBAC1C,KAAK,CAAC,QAAQ,KAAK,OAAO;oBAC1B,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC;YAC9B,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IAEP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/types.js b/lib.commonjs/_tests/types.js new file mode 100644 index 000000000..2004e03da --- /dev/null +++ b/lib.commonjs/_tests/types.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +; +//# sourceMappingURL=types.js.map \ 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 000000000..934c85582 --- /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":";;AAiOC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/utils.js b/lib.commonjs/_tests/utils.js new file mode 100644 index 000000000..226593ef6 --- /dev/null +++ b/lib.commonjs/_tests/utils.js @@ -0,0 +1,40 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.log = exports.loadTests = void 0; +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const zlib_1 = __importDefault(require("zlib")); +// Find the package root (based on the nyc output/ folder) +const root = (function () { + let root = process.cwd(); + while (true) { + if (fs_1.default.existsSync(path_1.default.join(root, "output"))) { + return root; + } + const parent = path_1.default.join(root, ".."); + if (parent === root) { + break; + } + root = parent; + } + throw new Error("could not find root"); +})(); +// Load the tests +function loadTests(tag) { + const filename = path_1.default.resolve(root, "testcases", tag + ".json.gz"); + return JSON.parse(zlib_1.default.gunzipSync(fs_1.default.readFileSync(filename)).toString()); +} +exports.loadTests = loadTests; +function log(context, text) { + if (context && context.test && typeof (context.test._ethersLog) === "function") { + context.test._ethersLog(text); + } + else { + console.log(text); + } +} +exports.log = log; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/utils.js.map b/lib.commonjs/_tests/utils.js.map new file mode 100644 index 000000000..1af2edf52 --- /dev/null +++ b/lib.commonjs/_tests/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src.ts/_tests/utils.ts"],"names":[],"mappings":";;;;;;AACA,4CAAmB;AACnB,gDAAwB;AACxB,gDAAwB;AAExB,0DAA0D;AAC1D,MAAM,IAAI,GAAG,CAAC;IACV,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAEzB,OAAO,IAAI,EAAE;QACT,IAAI,YAAE,CAAC,UAAU,CAAC,cAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QAC9D,MAAM,MAAM,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACrC,IAAI,MAAM,KAAK,IAAI,EAAE;YAAE,MAAM;SAAE;QAC/B,IAAI,GAAG,MAAM,CAAC;KACjB;IAED,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC3C,CAAC,CAAC,EAAE,CAAC;AAEL,iBAAiB;AACjB,SAAgB,SAAS,CAAI,GAAW;IACrC,MAAM,QAAQ,GAAG,cAAI,CAAC,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,GAAG,UAAU,CAAC,CAAC;IACnE,OAAO,IAAI,CAAC,KAAK,CAAC,cAAI,CAAC,UAAU,CAAC,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC;AAHD,8BAGC;AAED,SAAgB,GAAG,CAAC,OAAY,EAAE,IAAY;IAC1C,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,IAAI,OAAM,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,UAAU,EAAE;QAC3E,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;KACjC;SAAM;QACH,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;KACrB;AACL,CAAC;AAND,kBAMC"} \ No newline at end of file diff --git a/lib.commonjs/_version.js b/lib.commonjs/_version.js new file mode 100644 index 000000000..10e974e5a --- /dev/null +++ b/lib.commonjs/_version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +exports.version = "6.0.0-beta-exports.0"; +//# sourceMappingURL=_version.js.map \ No newline at end of file diff --git a/lib.commonjs/_version.js.map b/lib.commonjs/_version.js.map new file mode 100644 index 000000000..248af7713 --- /dev/null +++ b/lib.commonjs/_version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_version.js","sourceRoot":"","sources":["../src.ts/_version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,sBAAsB,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/abi/abi-coder.js b/lib.commonjs/abi/abi-coder.js new file mode 100644 index 000000000..fc9c23d05 --- /dev/null +++ b/lib.commonjs/abi/abi-coder.js @@ -0,0 +1,80 @@ +"use strict"; +// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultAbiCoder = exports.AbiCoder = void 0; +const logger_js_1 = require("../utils/logger.js"); +const abstract_coder_js_1 = require("./coders/abstract-coder.js"); +const address_js_1 = require("./coders/address.js"); +const array_js_1 = require("./coders/array.js"); +const boolean_js_1 = require("./coders/boolean.js"); +const bytes_js_1 = require("./coders/bytes.js"); +const fixed_bytes_js_1 = require("./coders/fixed-bytes.js"); +const null_js_1 = require("./coders/null.js"); +const number_js_1 = require("./coders/number.js"); +const string_js_1 = require("./coders/string.js"); +const tuple_js_1 = require("./coders/tuple.js"); +const fragments_js_1 = require("./fragments.js"); +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +class AbiCoder { + #getCoder(param) { + if (param.isArray()) { + return new array_js_1.ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); + } + if (param.isTuple()) { + return new tuple_js_1.TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name); + } + switch (param.baseType) { + case "address": + return new address_js_1.AddressCoder(param.name); + case "bool": + return new boolean_js_1.BooleanCoder(param.name); + case "string": + return new string_js_1.StringCoder(param.name); + case "bytes": + return new bytes_js_1.BytesCoder(param.name); + case "": + return new null_js_1.NullCoder(param.name); + } + // u?int[0-9]* + let match = param.type.match(paramTypeNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if (size === 0 || size > 256 || (size % 8) !== 0) { + logger_js_1.logger.throwArgumentError("invalid " + match[1] + " bit length", "param", param); + } + return new number_js_1.NumberCoder(size / 8, (match[1] === "int"), param.name); + } + // bytes[0-9]+ + match = param.type.match(paramTypeBytes); + if (match) { + let size = parseInt(match[1]); + if (size === 0 || size > 32) { + logger_js_1.logger.throwArgumentError("invalid bytes length", "param", param); + } + return new fixed_bytes_js_1.FixedBytesCoder(size, param.name); + } + return logger_js_1.logger.throwArgumentError("invalid type", "type", param.type); + } + getDefaultValue(types) { + const coders = types.map((type) => this.#getCoder(fragments_js_1.ParamType.from(type))); + const coder = new tuple_js_1.TupleCoder(coders, "_"); + return coder.defaultValue(); + } + encode(types, values) { + logger_js_1.logger.assertArgumentCount(values.length, types.length, "types/values length mismatch"); + const coders = types.map((type) => this.#getCoder(fragments_js_1.ParamType.from(type))); + const coder = (new tuple_js_1.TupleCoder(coders, "_")); + const writer = new abstract_coder_js_1.Writer(); + coder.encode(writer, values); + return writer.data; + } + decode(types, data, loose) { + const coders = types.map((type) => this.#getCoder(fragments_js_1.ParamType.from(type))); + const coder = new tuple_js_1.TupleCoder(coders, "_"); + return coder.decode(new abstract_coder_js_1.Reader(data, loose)); + } +} +exports.AbiCoder = AbiCoder; +exports.defaultAbiCoder = new AbiCoder(); +//# sourceMappingURL=abi-coder.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/abi-coder.js.map b/lib.commonjs/abi/abi-coder.js.map new file mode 100644 index 000000000..dde322112 --- /dev/null +++ b/lib.commonjs/abi/abi-coder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abi-coder.js","sourceRoot":"","sources":["../../src.ts/abi/abi-coder.ts"],"names":[],"mappings":";AAAA,mEAAmE;;;AAEnE,kDAA4C;AAE5C,kEAA2E;AAC3E,oDAAmD;AACnD,gDAA+C;AAC/C,oDAAmD;AACnD,gDAA+C;AAC/C,4DAA0D;A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,YAAY,EAAE,CAAC;IAChC,CAAC;IAED,MAAM,CAAC,KAAwC,EAAE,MAA0B;QACvE,kBAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,8BAA8B,CAAC,CAAC;QAExF,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,wBAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACzE,MAAM,KAAK,GAAG,CAAC,IAAI,qBAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;QAE5C,MAAM,MAAM,GAAG,IAAI,0BAAM,EAAE,CAAC;QAC5B,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC7B,OAAO,MAAM,CAAC,IAAI,CAAC;IACvB,CAAC;IAED,MAAM,CAAC,KAAwC,EAAE,IAAe,EAAE,KAAe;QAC7E,MAAM,MAAM,GAAiB,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,wBAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvF,MAAM,KAAK,GAAG,IAAI,qBAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC1C,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,0BAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;IACjD,CAAC;CACJ;AArED,4BAqEC;AAGY,QAAA,eAAe,GAAa,IAAI,QAAQ,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/abi/bytes32.js b/lib.commonjs/abi/bytes32.js new file mode 100644 index 000000000..af8117c95 --- /dev/null +++ b/lib.commonjs/abi/bytes32.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBytes32String = exports.formatBytes32String = void 0; +const data_js_1 = require("../utils/data.js"); +const logger_js_1 = require("../utils/logger.js"); +const utf8_js_1 = require("../utils/utf8.js"); +function formatBytes32String(text) { + // Get the bytes + const bytes = (0, utf8_js_1.toUtf8Bytes)(text); + // Check we have room for null-termination + if (bytes.length > 31) { + throw new Error("bytes32 string must be less than 32 bytes"); + } + // Zero-pad (implicitly null-terminates) + return (0, data_js_1.zeroPadBytes)(bytes, 32); +} +exports.formatBytes32String = formatBytes32String; +function parseBytes32String(_bytes) { + const data = logger_js_1.logger.getBytes(_bytes, "bytes"); + // Must be 32 bytes with a null-termination + if (data.length !== 32) { + throw new Error("invalid bytes32 - not 32 bytes long"); + } + if (data[31] !== 0) { + throw new Error("invalid bytes32 string - no null terminator"); + } + // Find the null termination + let length = 31; + while (data[length - 1] === 0) { + length--; + } + // Determine the string value + return (0, utf8_js_1.toUtf8String)(data.slice(0, length)); +} +exports.parseBytes32String = parseBytes32String; +//# sourceMappingURL=bytes32.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/bytes32.js.map b/lib.commonjs/abi/bytes32.js.map new file mode 100644 index 000000000..fae2c3263 --- /dev/null +++ b/lib.commonjs/abi/bytes32.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes32.js","sourceRoot":"","sources":["../../src.ts/abi/bytes32.ts"],"names":[],"mappings":";;;AACA,8CAAgD;AAEhD,kDAA4C;AAE5C,8CAA6D;AAK7D,SAAgB,mBAAmB,CAAC,IAAY;IAE5C,gBAAgB;IAChB,MAAM,KAAK,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,CAAC;IAEhC,0CAA0C;IAC1C,IAAI,KAAK,CAAC,MAAM,GAAG,EAAE,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAAE;IAExF,wCAAwC;IACxC,OAAO,IAAA,sBAAY,EAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAVD,kDAUC;AAED,SAAgB,kBAAkB,CAAC,MAAiB;IAChD,MAAM,IAAI,GAAG,kBAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE9C,2CAA2C;IAC3C,IAAI,IAAI,CAAC,MAAM,KAAK,EAAE,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;KAAE;IACnF,IAAI,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAAE;IAEvF,4BAA4B;IAC5B,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE;QAAE,MAAM,EAAE,CAAC;KAAE;IAE5C,6BAA6B;IAC7B,OAAO,IAAA,sBAAY,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AAC/C,CAAC;AAbD,gDAaC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/abstract-coder.js b/lib.commonjs/abi/coders/abstract-coder.js new file mode 100644 index 000000000..170f11d3e --- /dev/null +++ b/lib.commonjs/abi/coders/abstract-coder.js @@ -0,0 +1,273 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Reader = exports.Writer = exports.Coder = exports.checkResultErrors = exports.Result = exports.WordSize = void 0; +const maths_js_1 = require("../../utils/maths.js"); +const data_js_1 = require("../../utils/data.js"); +const properties_js_1 = require("../../utils/properties.js"); +const logger_js_1 = require("../../utils/logger.js"); +exports.WordSize = 32; +const Padding = new Uint8Array(exports.WordSize); +// Properties used to immediate pass through to the underlying object +// - `then` is used to detect if an object is a Promise for await +const passProperties = ["then"]; +const _guard = {}; +class Result extends Array { + #indices; + constructor(guard, items, keys) { + logger_js_1.logger.assertPrivate(guard, _guard, "Result"); + super(...items); + // Name lookup table + this.#indices = new Map(); + if (keys) { + keys.forEach((key, index) => { + if (key == null) { + return; + } + if (this.#indices.has(key)) { + (this.#indices.get(key)).push(index); + } + else { + this.#indices.set(key, [index]); + } + }); + } + Object.freeze(this); + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "string") { + if (prop.match(/^[0-9]+$/)) { + const index = logger_js_1.logger.getNumber(prop, "%index"); + if (index < 0 || index >= this.length) { + throw new RangeError("out of result range"); + } + const item = target[index]; + if (item instanceof Error) { + this.#throwError(`index ${index}`, item); + } + return item; + } + // Pass important checks (like `then` for Promise) through + if (prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + // Something that could be a result keyword value + if (!(prop in target)) { + return target.getValue(prop); + } + } + return Reflect.get(target, prop, receiver); + } + }); + } + /* + toJSON(): any { + if (this.#indices.length === this.length) { + const result: Record = { }; + for (const key of this.#indices.keys()) { + result[key] = ths.getValue(key); + } + return result; + } + return this; + } + */ + slice(start, end) { + if (start == null) { + start = 0; + } + if (end == null) { + end = this.length; + } + const result = []; + for (let i = start; i < end; i++) { + let value; + try { + value = this[i]; + } + catch (error) { + value = error.error; + } + result.push(value); + } + return result; + } + #throwError(name, error) { + const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); + wrapped.error = error; + throw wrapped; + } + getValue(name) { + const index = this.#indices.get(name); + if (index != null && index.length === 1) { + const item = this[index[0]]; + if (item instanceof Error) { + this.#throwError(`property ${JSON.stringify(name)}`, item); + } + return item; + } + throw new Error(`no named parameter: ${JSON.stringify(name)}`); + } + static fromItems(items, keys) { + return new Result(_guard, items, keys); + } +} +exports.Result = Result; +function checkResultErrors(result) { + // Find the first error (if any) + const errors = []; + const checkErrors = function (path, object) { + if (!Array.isArray(object)) { + return; + } + for (let key in object) { + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object[key]); + } + catch (error) { + errors.push({ path: childPath, error: error }); + } + } + }; + checkErrors([], result); + return errors; +} +exports.checkResultErrors = checkResultErrors; +function getValue(value) { + let bytes = (0, maths_js_1.toArray)(value); + if (bytes.length > exports.WordSize) { + logger_js_1.logger.throwError("value out-of-bounds", "BUFFER_OVERRUN", { + buffer: bytes, + length: exports.WordSize, + offset: bytes.length + }); + } + if (bytes.length !== exports.WordSize) { + bytes = logger_js_1.logger.getBytesCopy((0, data_js_1.concat)([Padding.slice(bytes.length % exports.WordSize), bytes])); + } + return bytes; +} +class Coder { + // The coder name: + // - address, uint256, tuple, array, etc. + name; + // The fully expanded type, including composite types: + // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. + type; + // The localName bound in the signature, in this example it is "baz": + // - tuple(address foo, uint bar) baz + localName; + // Whether this type is dynamic: + // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. + // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) + dynamic; + constructor(name, type, localName, dynamic) { + (0, properties_js_1.defineProperties)(this, { name, type, localName, dynamic }, { + name: "string", type: "string", localName: "string", dynamic: "boolean" + }); + } + _throwError(message, value) { + return logger_js_1.logger.throwArgumentError(message, this.localName, value); + } +} +exports.Coder = Coder; +class Writer { + // An array of WordSize lengthed objects to concatenation + #data; + #dataLength; + constructor() { + this.#data = []; + this.#dataLength = 0; + } + get data() { + return (0, data_js_1.concat)(this.#data); + } + get length() { return this.#dataLength; } + #writeData(data) { + this.#data.push(data); + this.#dataLength += data.length; + return data.length; + } + appendWriter(writer) { + return this.#writeData(logger_js_1.logger.getBytesCopy(writer.data)); + } + // Arrayish item; pad on the right to *nearest* WordSize + writeBytes(value) { + let bytes = logger_js_1.logger.getBytesCopy(value); + const paddingOffset = bytes.length % exports.WordSize; + if (paddingOffset) { + bytes = logger_js_1.logger.getBytesCopy((0, data_js_1.concat)([bytes, Padding.slice(paddingOffset)])); + } + return this.#writeData(bytes); + } + // Numeric item; pad on the left *to* WordSize + writeValue(value) { + return this.#writeData(getValue(value)); + } + // Inserts a numeric place-holder, returning a callback that can + // be used to asjust the value later + writeUpdatableValue() { + const offset = this.#data.length; + this.#data.push(Padding); + this.#dataLength += exports.WordSize; + return (value) => { + this.#data[offset] = getValue(value); + }; + } +} +exports.Writer = Writer; +class Reader { + // Allows incomplete unpadded data to be read; otherwise an error + // is raised if attempting to overrun the buffer. This is required + // to deal with an old Solidity bug, in which event data for + // external (not public thoguh) was tightly packed. + allowLoose; + #data; + #offset; + constructor(data, allowLoose) { + (0, properties_js_1.defineProperties)(this, { allowLoose: !!allowLoose }); + this.#data = logger_js_1.logger.getBytesCopy(data); + this.#offset = 0; + } + get data() { return (0, data_js_1.hexlify)(this.#data); } + get dataLength() { return this.#data.length; } + get consumed() { return this.#offset; } + get bytes() { return new Uint8Array(this.#data); } + #peekBytes(offset, length, loose) { + let alignedLength = Math.ceil(length / exports.WordSize) * exports.WordSize; + if (this.#offset + alignedLength > this.#data.length) { + if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { + alignedLength = length; + } + else { + logger_js_1.logger.throwError("data out-of-bounds", "BUFFER_OVERRUN", { + buffer: logger_js_1.logger.getBytesCopy(this.#data), + length: this.#data.length, + offset: this.#offset + alignedLength + }); + } + } + return this.#data.slice(this.#offset, this.#offset + alignedLength); + } + // Create a sub-reader with the same underlying data, but offset + subReader(offset) { + return new Reader(this.#data.slice(this.#offset + offset), this.allowLoose); + } + // Read bytes + readBytes(length, loose) { + let bytes = this.#peekBytes(0, length, !!loose); + this.#offset += bytes.length; + // @TODO: Make sure the length..end bytes are all 0? + return bytes.slice(0, length); + } + // Read a numeric values + readValue() { + return (0, maths_js_1.toBigInt)(this.readBytes(exports.WordSize)); + } + readIndex() { + return (0, maths_js_1.toNumber)(this.readBytes(exports.WordSize)); + } +} +exports.Reader = Reader; +//# sourceMappingURL=abstract-coder.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/abstract-coder.js.map b/lib.commonjs/abi/coders/abstract-coder.js.map new file mode 100644 index 000000000..fd8e9735c --- /dev/null +++ b/lib.commonjs/abi/coders/abstract-coder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-coder.js","sourceRoot":"","sources":["../../../src.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,CAAC,OAAO,GAAG,aAAa,CAAC,CAAA;IACvE,CAAC;IAED,gEAAgE;IAChE,SAAS,CAAC,MAAc;QACpB,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAChF,CAAC;IAED,aAAa;IACb,SAAS,CAAC,MAAc,EAAE,KAAe;QACrC,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC;QAChD,IAAI,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC;QAC7B,oDAAoD;QACpD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IAClC,CAAC;IAED,wBAAwB;IACxB,SAAS;QACL,OAAO,IAAA,mBAAQ,EAAC,IAAI,CAAC,SAAS,CAAC,gBAAQ,CAAC,CAAC,CAAC;IAC9C,CAAC;IAED,SAAS;QACL,OAAO,IAAA,mBAAQ,EAAC,IAAI,CAAC,SAAS,CAAC,gBAAQ,CAAC,CAAC,CAAC;IAC9C,CAAC;CACJ;AA5DD,wBA4DC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/address.js b/lib.commonjs/abi/coders/address.js new file mode 100644 index 000000000..2449f0589 --- /dev/null +++ b/lib.commonjs/abi/coders/address.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AddressCoder = void 0; +const index_js_1 = require("../../address/index.js"); +const maths_js_1 = require("../../utils/maths.js"); +const typed_js_1 = require("../typed.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +class AddressCoder extends abstract_coder_js_1.Coder { + constructor(localName) { + super("address", "address", localName, false); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, _value) { + let value = typed_js_1.Typed.dereference(_value, "string"); + try { + value = (0, index_js_1.getAddress)(value); + } + catch (error) { + return this._throwError(error.message, _value); + } + return writer.writeValue(value); + } + decode(reader) { + return (0, index_js_1.getAddress)((0, maths_js_1.toHex)(reader.readValue(), 20)); + } +} +exports.AddressCoder = AddressCoder; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/address.js.map b/lib.commonjs/abi/coders/address.js.map new file mode 100644 index 000000000..bb5abd2dd --- /dev/null +++ b/lib.commonjs/abi/coders/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/address.ts"],"names":[],"mappings":";;;AAAA,qDAAoD;AACpD,mDAA6C;AAE7C,0CAAoC;AACpC,2DAA4C;AAK5C,MAAa,YAAa,SAAQ,yBAAK;IAEnC,YAAY,SAAiB;QACzB,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAClD,CAAC;IAED,YAAY;QACR,OAAO,4CAA4C,CAAC;IACxD,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAsB;QACzC,IAAI,KAAK,GAAG,gBAAK,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChD,IAAI;YACA,KAAK,GAAG,IAAA,qBAAU,EAAC,KAAK,CAAC,CAAC;SAC7B;QAAC,OAAO,KAAU,EAAE;YACjB,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;SAClD;QACD,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,IAAA,qBAAU,EAAC,IAAA,gBAAK,EAAC,MAAM,CAAC,SAAS,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;IACrD,CAAC;CACJ;AAvBD,oCAuBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/anonymous.js b/lib.commonjs/abi/coders/anonymous.js new file mode 100644 index 000000000..a2990311c --- /dev/null +++ b/lib.commonjs/abi/coders/anonymous.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AnonymousCoder = void 0; +const abstract_coder_js_1 = require("./abstract-coder.js"); +// Clones the functionality of an existing Coder, but without a localName +class AnonymousCoder extends abstract_coder_js_1.Coder { + coder; + constructor(coder) { + super(coder.name, coder.type, "_", coder.dynamic); + this.coder = coder; + } + defaultValue() { + return this.coder.defaultValue(); + } + encode(writer, value) { + return this.coder.encode(writer, value); + } + decode(reader) { + return this.coder.decode(reader); + } +} +exports.AnonymousCoder = AnonymousCoder; +//# sourceMappingURL=anonymous.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/anonymous.js.map b/lib.commonjs/abi/coders/anonymous.js.map new file mode 100644 index 000000000..e939ff9d0 --- /dev/null +++ b/lib.commonjs/abi/coders/anonymous.js.map @@ -0,0 +1 @@ +{"version":3,"file":"anonymous.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/anonymous.ts"],"names":[],"mappings":";;;AAAA,2DAA4C;AAI5C,yEAAyE;AACzE,MAAa,cAAe,SAAQ,yBAAK;IAC7B,KAAK,CAAQ;IAErB,YAAY,KAAY;QACpB,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,YAAY;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;IACrC,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,KAAU;QAC7B,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACJ;AAnBD,wCAmBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/array.js b/lib.commonjs/abi/coders/array.js new file mode 100644 index 000000000..c7ae58a10 --- /dev/null +++ b/lib.commonjs/abi/coders/array.js @@ -0,0 +1,178 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArrayCoder = exports.unpack = exports.pack = void 0; +const properties_js_1 = require("../../utils/properties.js"); +const errors_js_1 = require("../../utils/errors.js"); +const logger_js_1 = require("../../utils/logger.js"); +const typed_js_1 = require("../typed.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +const anonymous_js_1 = require("./anonymous.js"); +function pack(writer, coders, values) { + let arrayValues = []; + if (Array.isArray(values)) { + arrayValues = values; + } + else if (values && typeof (values) === "object") { + let unique = {}; + arrayValues = coders.map((coder) => { + const name = coder.localName; + if (!name) { + logger_js_1.logger.throwError("cannot encode object for signature with missing names", "INVALID_ARGUMENT", { + argument: "values", + info: { coder }, + value: values + }); + } + if (unique[name]) { + logger_js_1.logger.throwError("cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { + argument: "values", + info: { coder }, + value: values + }); + } + unique[name] = true; + return values[name]; + }); + } + else { + logger_js_1.logger.throwArgumentError("invalid tuple value", "tuple", values); + } + if (coders.length !== arrayValues.length) { + logger_js_1.logger.throwArgumentError("types/value length mismatch", "tuple", values); + } + let staticWriter = new abstract_coder_js_1.Writer(); + let dynamicWriter = new abstract_coder_js_1.Writer(); + let updateFuncs = []; + coders.forEach((coder, index) => { + let value = arrayValues[index]; + if (coder.dynamic) { + // Get current dynamic offset (for the future pointer) + let dynamicOffset = dynamicWriter.length; + // Encode the dynamic value into the dynamicWriter + coder.encode(dynamicWriter, value); + // Prepare to populate the correct offset once we are done + let updateFunc = staticWriter.writeUpdatableValue(); + updateFuncs.push((baseOffset) => { + updateFunc(baseOffset + dynamicOffset); + }); + } + else { + coder.encode(staticWriter, value); + } + }); + // Backfill all the dynamic offsets, now that we know the static length + updateFuncs.forEach((func) => { func(staticWriter.length); }); + let length = writer.appendWriter(staticWriter); + length += writer.appendWriter(dynamicWriter); + return length; +} +exports.pack = pack; +function unpack(reader, coders) { + let values = []; + let keys = []; + // A reader anchored to this base + let baseReader = reader.subReader(0); + coders.forEach((coder) => { + let value = null; + if (coder.dynamic) { + let offset = reader.readIndex(); + let offsetReader = baseReader.subReader(offset); + try { + value = coder.decode(offsetReader); + } + catch (error) { + // Cannot recover from this + if ((0, errors_js_1.isError)(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + else { + try { + value = coder.decode(reader); + } + catch (error) { + // Cannot recover from this + if ((0, errors_js_1.isError)(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + if (value == undefined) { + throw new Error("investigate"); + } + values.push(value); + keys.push(coder.localName || null); + }); + return abstract_coder_js_1.Result.fromItems(values, keys); +} +exports.unpack = unpack; +class ArrayCoder extends abstract_coder_js_1.Coder { + coder; + length; + constructor(coder, length, localName) { + const type = (coder.type + "[" + (length >= 0 ? length : "") + "]"); + const dynamic = (length === -1 || coder.dynamic); + super("array", type, localName, dynamic); + (0, properties_js_1.defineProperties)(this, { coder, length }); + } + defaultValue() { + // Verifies the child coder is valid (even if the array is dynamic or 0-length) + const defaultChild = this.coder.defaultValue(); + const result = []; + for (let i = 0; i < this.length; i++) { + result.push(defaultChild); + } + return result; + } + encode(writer, _value) { + const value = typed_js_1.Typed.dereference(_value, "array"); + if (!Array.isArray(value)) { + this._throwError("expected array value", value); + } + let count = this.length; + if (count === -1) { + count = value.length; + writer.writeValue(value.length); + } + logger_js_1.logger.assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : "")); + let coders = []; + for (let i = 0; i < value.length; i++) { + coders.push(this.coder); + } + return pack(writer, coders, value); + } + decode(reader) { + let count = this.length; + if (count === -1) { + count = reader.readIndex(); + // Check that there is *roughly* enough data to ensure + // stray random data is not being read as a length. Each + // slot requires at least 32 bytes for their value (or 32 + // bytes as a link to the data). This could use a much + // tighter bound, but we are erroring on the side of safety. + if (count * abstract_coder_js_1.WordSize > reader.dataLength) { + logger_js_1.logger.throwError("insufficient data length", "BUFFER_OVERRUN", { + buffer: reader.bytes, + offset: count * abstract_coder_js_1.WordSize, + length: reader.dataLength + }); + } + } + let coders = []; + for (let i = 0; i < count; i++) { + coders.push(new anonymous_js_1.AnonymousCoder(this.coder)); + } + return unpack(reader, coders); + } +} +exports.ArrayCoder = ArrayCoder; +//# sourceMappingURL=array.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/array.js.map b/lib.commonjs/abi/coders/array.js.map new file mode 100644 index 000000000..e3ef9c1b1 --- /dev/null +++ b/lib.commonjs/abi/coders/array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"array.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/array.ts"],"names":[],"mappings":";;;AAAA,6DAA6D;AAC7D,qDAAgD;AAChD,qDAA+C;AAE/C,0CAAoC;AACpC,2DAAsE;AACtE,iDAAgD;AAKhD,SAAgB,IAAI,CAAC,MAAc,EAAE,MAA4B,EAAE,MAA8C;IAC7G,IAAI,WAAW,GAAe,EAAG,CAAC;IAElC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACxB,WAAW,GAAG,MAAM,CAAC;KAEvB;SAAM,IAAI,MAAM,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,EAAE;QAC9C,IAAI,MAAM,GAAkC,EAAG,CAAC;QAEhD,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;YAC/B,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC;YAC7B,IAAI,CAAC,IAAI,EAAE;gBACP,kBAAM,CAAC,UAAU,CAAC,uDAAuD,EAAE,kBAAkB,EAAE;oBAC3F,QAAQ,EAAE,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C,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;SAAE;QAEnE,OAAO,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC;QACxB,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;YACd,KAAK,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;YAE3B,sDAAsD;YACtD,wDAAwD;YACxD,yDAAyD;YACzD,sDAAsD;YACtD,4DAA4D;YAC5D,IAAI,KAAK,GAAG,4BAAQ,GAAG,MAAM,CAAC,UAAU,EAAE;gBACtC,kBAAM,CAAC,UAAU,CAAC,0BAA0B,EAAE,gBAAgB,EAAE;oBAC5D,MAAM,EAAE,MAAM,CAAC,KAAK;oBACpB,MAAM,EAAE,KAAK,GAAG,4BAAQ;oBACxB,MAAM,EAAE,MAAM,CAAC,UAAU;iBAC5B,CAAC,CAAC;aACN;SACJ;QACD,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YAAE,MAAM,CAAC,IAAI,CAAC,IAAI,6BAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;SAAE;QAEhF,OAAO,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,CAAC;CACJ;AAnED,gCAmEC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/boolean.js b/lib.commonjs/abi/coders/boolean.js new file mode 100644 index 000000000..c7df434c3 --- /dev/null +++ b/lib.commonjs/abi/coders/boolean.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BooleanCoder = void 0; +const typed_js_1 = require("../typed.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +class BooleanCoder extends abstract_coder_js_1.Coder { + constructor(localName) { + super("bool", "bool", localName, false); + } + defaultValue() { + return false; + } + encode(writer, _value) { + const value = typed_js_1.Typed.dereference(_value, "bool"); + return writer.writeValue(value ? 1 : 0); + } + decode(reader) { + return !!reader.readValue(); + } +} +exports.BooleanCoder = BooleanCoder; +//# sourceMappingURL=boolean.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/boolean.js.map b/lib.commonjs/abi/coders/boolean.js.map new file mode 100644 index 000000000..24b68db3b --- /dev/null +++ b/lib.commonjs/abi/coders/boolean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/boolean.ts"],"names":[],"mappings":";;;AAAA,0CAAoC;AACpC,2DAA4C;AAK5C,MAAa,YAAa,SAAQ,yBAAK;IAEnC,YAAY,SAAiB;QACzB,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED,YAAY;QACR,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAuB;QAC1C,MAAM,KAAK,GAAG,gBAAK,CAAC,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAChC,CAAC;CACJ;AAlBD,oCAkBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/bytes.js b/lib.commonjs/abi/coders/bytes.js new file mode 100644 index 000000000..5eea9b348 --- /dev/null +++ b/lib.commonjs/abi/coders/bytes.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BytesCoder = exports.DynamicBytesCoder = void 0; +const logger_js_1 = require("../../utils/logger.js"); +const data_js_1 = require("../../utils/data.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +class DynamicBytesCoder extends abstract_coder_js_1.Coder { + constructor(type, localName) { + super(type, type, localName, true); + } + defaultValue() { + return "0x"; + } + encode(writer, value) { + value = logger_js_1.logger.getBytesCopy(value); + let length = writer.writeValue(value.length); + length += writer.writeBytes(value); + return length; + } + decode(reader) { + return reader.readBytes(reader.readIndex(), true); + } +} +exports.DynamicBytesCoder = DynamicBytesCoder; +class BytesCoder extends DynamicBytesCoder { + constructor(localName) { + super("bytes", localName); + } + decode(reader) { + return (0, data_js_1.hexlify)(super.decode(reader)); + } +} +exports.BytesCoder = BytesCoder; +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/bytes.js.map b/lib.commonjs/abi/coders/bytes.js.map new file mode 100644 index 000000000..ac704849b --- /dev/null +++ b/lib.commonjs/abi/coders/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/bytes.ts"],"names":[],"mappings":";;;AAAA,qDAA+C;AAC/C,iDAA8C;AAE9C,2DAA4C;AAK5C,MAAa,iBAAkB,SAAQ,yBAAK;IACxC,YAAY,IAAY,EAAE,SAAiB;QACxC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;IAED,YAAY;QACR,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,KAAU;QAC7B,KAAK,GAAG,kBAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,MAAM,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,EAAE,EAAE,IAAI,CAAC,CAAC;IACtD,CAAC;CACJ;AAnBD,8CAmBC;AAED,MAAa,UAAW,SAAQ,iBAAiB;IAC7C,YAAY,SAAiB;QACzB,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,IAAA,iBAAO,EAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IACzC,CAAC;CACJ;AARD,gCAQC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/fixed-bytes.js b/lib.commonjs/abi/coders/fixed-bytes.js new file mode 100644 index 000000000..7fb2e9227 --- /dev/null +++ b/lib.commonjs/abi/coders/fixed-bytes.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FixedBytesCoder = void 0; +const logger_js_1 = require("../../utils/logger.js"); +const data_js_1 = require("../../utils/data.js"); +const properties_js_1 = require("../../utils/properties.js"); +const typed_js_1 = require("../typed.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +class FixedBytesCoder extends abstract_coder_js_1.Coder { + size; + constructor(size, localName) { + let name = "bytes" + String(size); + super(name, name, localName, false); + (0, properties_js_1.defineProperties)(this, { size }, { size: "number" }); + } + defaultValue() { + return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2); + } + encode(writer, _value) { + let data = logger_js_1.logger.getBytesCopy(typed_js_1.Typed.dereference(_value, this.type)); + if (data.length !== this.size) { + this._throwError("incorrect data length", _value); + } + return writer.writeBytes(data); + } + decode(reader) { + return (0, data_js_1.hexlify)(reader.readBytes(this.size)); + } +} +exports.FixedBytesCoder = FixedBytesCoder; +//# sourceMappingURL=fixed-bytes.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/fixed-bytes.js.map b/lib.commonjs/abi/coders/fixed-bytes.js.map new file mode 100644 index 000000000..b700da6d7 --- /dev/null +++ b/lib.commonjs/abi/coders/fixed-bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fixed-bytes.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/fixed-bytes.ts"],"names":[],"mappings":";;;AACA,qDAA+C;AAC/C,iDAA8C;AAC9C,6DAA6D;AAE7D,0CAAoC;AACpC,2DAA4C;AAO5C,MAAa,eAAgB,SAAQ,yBAAK;IAC7B,IAAI,CAAU;IAEvB,YAAY,IAAY,EAAE,SAAiB;QACvC,IAAI,IAAI,GAAG,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAClC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QACpC,IAAA,gCAAgB,EAAkB,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC1E,CAAC;IAED,YAAY;QACR,OAAO,CAAC,oEAAoE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;IAClH,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAyB;QAC5C,IAAI,IAAI,GAAG,kBAAM,CAAC,YAAY,CAAC,gBAAK,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACrE,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE;YAAE,IAAI,CAAC,WAAW,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;SAAE;QACrF,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,IAAA,iBAAO,EAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,CAAC;CACJ;AAtBD,0CAsBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/null.js b/lib.commonjs/abi/coders/null.js new file mode 100644 index 000000000..71a188a86 --- /dev/null +++ b/lib.commonjs/abi/coders/null.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NullCoder = void 0; +const abstract_coder_js_1 = require("./abstract-coder.js"); +const Empty = new Uint8Array([]); +class NullCoder extends abstract_coder_js_1.Coder { + constructor(localName) { + super("null", "", localName, false); + } + defaultValue() { + return null; + } + encode(writer, value) { + if (value != null) { + this._throwError("not null", value); + } + return writer.writeBytes(Empty); + } + decode(reader) { + reader.readBytes(0); + return null; + } +} +exports.NullCoder = NullCoder; +//# sourceMappingURL=null.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/null.js.map b/lib.commonjs/abi/coders/null.js.map new file mode 100644 index 000000000..4da7cc80a --- /dev/null +++ b/lib.commonjs/abi/coders/null.js.map @@ -0,0 +1 @@ +{"version":3,"file":"null.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/null.ts"],"names":[],"mappings":";;;AAAA,2DAA4C;AAG5C,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,EAAG,CAAC,CAAC;AAElC,MAAa,SAAU,SAAQ,yBAAK;IAEhC,YAAY,SAAiB;QACzB,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IACxC,CAAC;IAED,YAAY;QACR,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,KAAU;QAC7B,IAAI,KAAK,IAAI,IAAI,EAAE;YAAE,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;SAAE;QAC3D,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AAnBD,8BAmBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/number.js b/lib.commonjs/abi/coders/number.js new file mode 100644 index 000000000..6dfbf1ac9 --- /dev/null +++ b/lib.commonjs/abi/coders/number.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NumberCoder = void 0; +const maths_js_1 = require("../../utils/maths.js"); +const properties_js_1 = require("../../utils/properties.js"); +const logger_js_1 = require("../../utils/logger.js"); +const typed_js_1 = require("../typed.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +class NumberCoder extends abstract_coder_js_1.Coder { + size; + signed; + constructor(size, signed, localName) { + const name = ((signed ? "int" : "uint") + (size * 8)); + super(name, name, localName, false); + (0, properties_js_1.defineProperties)(this, { size, signed }, { size: "number", signed: "boolean" }); + } + defaultValue() { + return 0; + } + encode(writer, _value) { + let value = logger_js_1.logger.getBigInt(typed_js_1.Typed.dereference(_value, this.type)); + // Check bounds are safe for encoding + let maxUintValue = (0, maths_js_1.mask)(BN_MAX_UINT256, abstract_coder_js_1.WordSize * 8); + if (this.signed) { + let bounds = (0, maths_js_1.mask)(maxUintValue, (this.size * 8) - 1); + if (value > bounds || value < -(bounds + BN_1)) { + this._throwError("value out-of-bounds", _value); + } + } + else if (value < BN_0 || value > (0, maths_js_1.mask)(maxUintValue, this.size * 8)) { + this._throwError("value out-of-bounds", _value); + } + value = (0, maths_js_1.mask)((0, maths_js_1.toTwos)(value, this.size * 8), this.size * 8); + if (this.signed) { + value = (0, maths_js_1.toTwos)((0, maths_js_1.fromTwos)(value, this.size * 8), 8 * abstract_coder_js_1.WordSize); + } + return writer.writeValue(value); + } + decode(reader) { + let value = (0, maths_js_1.mask)(reader.readValue(), this.size * 8); + if (this.signed) { + value = (0, maths_js_1.fromTwos)(value, this.size * 8); + } + return value; + } +} +exports.NumberCoder = NumberCoder; +//# sourceMappingURL=number.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/number.js.map b/lib.commonjs/abi/coders/number.js.map new file mode 100644 index 000000000..f39817bfb --- /dev/null +++ b/lib.commonjs/abi/coders/number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"number.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/number.ts"],"names":[],"mappings":";;;AAAA,mDAA8D;AAC9D,6DAA6D;AAE7D,qDAA+C;AAC/C,0CAAoC;AACpC,2DAAsD;AAOtD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,cAAc,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAEpG,MAAa,WAAY,SAAQ,yBAAK;IACzB,IAAI,CAAU;IACd,MAAM,CAAW;IAE1B,YAAY,IAAY,EAAE,MAAe,EAAE,SAAiB;QACxD,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAA,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC;QACrD,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QAEpC,IAAA,gCAAgB,EAAc,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;IACjG,CAAC;IAED,YAAY;QACR,OAAO,CAAC,CAAC;IACb,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAA4B;QAC/C,IAAI,KAAK,GAAG,kBAAM,CAAC,SAAS,CAAC,gBAAK,CAAC,WAAW,CAAC,MAAM,EAAE,IA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K,GAAG,IAAA,mBAAQ,EAAC,KAAK,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;SAC1C;QAED,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AA/CD,kCA+CC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/string.js b/lib.commonjs/abi/coders/string.js new file mode 100644 index 000000000..c0e6309e2 --- /dev/null +++ b/lib.commonjs/abi/coders/string.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StringCoder = void 0; +const utf8_js_1 = require("../../utils/utf8.js"); +const typed_js_1 = require("../typed.js"); +const bytes_js_1 = require("./bytes.js"); +class StringCoder extends bytes_js_1.DynamicBytesCoder { + constructor(localName) { + super("string", localName); + } + defaultValue() { + return ""; + } + encode(writer, _value) { + return super.encode(writer, (0, utf8_js_1.toUtf8Bytes)(typed_js_1.Typed.dereference(_value, "string"))); + } + decode(reader) { + return (0, utf8_js_1.toUtf8String)(super.decode(reader)); + } +} +exports.StringCoder = StringCoder; +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/string.js.map b/lib.commonjs/abi/coders/string.js.map new file mode 100644 index 000000000..34823f3bf --- /dev/null +++ b/lib.commonjs/abi/coders/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/string.ts"],"names":[],"mappings":";;;AAAA,iDAAgE;AAEhE,0CAAoC;AACpC,yCAA+C;AAK/C,MAAa,WAAY,SAAQ,4BAAiB;IAE9C,YAAY,SAAiB;QACzB,KAAK,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC/B,CAAC;IAED,YAAY;QACR,OAAO,EAAE,CAAC;IACd,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAsB;QACzC,OAAO,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,IAAA,qBAAW,EAAC,gBAAK,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,IAAA,sBAAY,EAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAC9C,CAAC;CACJ;AAjBD,kCAiBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/coders/tuple.js b/lib.commonjs/abi/coders/tuple.js new file mode 100644 index 000000000..f6f73aa3e --- /dev/null +++ b/lib.commonjs/abi/coders/tuple.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TupleCoder = void 0; +const properties_js_1 = require("../../utils/properties.js"); +const typed_js_1 = require("../typed.js"); +const abstract_coder_js_1 = require("./abstract-coder.js"); +const array_js_1 = require("./array.js"); +class TupleCoder extends abstract_coder_js_1.Coder { + coders; + constructor(coders, localName) { + let dynamic = false; + const types = []; + coders.forEach((coder) => { + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + const type = ("tuple(" + types.join(",") + ")"); + super("tuple", type, localName, dynamic); + (0, properties_js_1.defineProperties)(this, { coders: Object.freeze(coders.slice()) }); + } + defaultValue() { + const values = []; + this.coders.forEach((coder) => { + values.push(coder.defaultValue()); + }); + // We only output named properties for uniquely named coders + const uniqueNames = this.coders.reduce((accum, coder) => { + const name = coder.localName; + if (name) { + if (!accum[name]) { + accum[name] = 0; + } + accum[name]++; + } + return accum; + }, {}); + // Add named values + this.coders.forEach((coder, index) => { + let name = coder.localName; + if (!name || uniqueNames[name] !== 1) { + return; + } + if (name === "length") { + name = "_length"; + } + if (values[name] != null) { + return; + } + values[name] = values[index]; + }); + return Object.freeze(values); + } + encode(writer, _value) { + const value = typed_js_1.Typed.dereference(_value, "tuple"); + return (0, array_js_1.pack)(writer, this.coders, value); + } + decode(reader) { + return (0, array_js_1.unpack)(reader, this.coders); + } +} +exports.TupleCoder = TupleCoder; +//# sourceMappingURL=tuple.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/coders/tuple.js.map b/lib.commonjs/abi/coders/tuple.js.map new file mode 100644 index 000000000..c08ab0bb1 --- /dev/null +++ b/lib.commonjs/abi/coders/tuple.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/tuple.ts"],"names":[],"mappings":";;;AAAA,6DAA6D;AAE7D,0CAAoC;AACpC,2DAA4C;AAE5C,yCAA0C;AAI1C,MAAa,UAAW,SAAQ,yBAAK;IACxB,MAAM,CAAwB;IAEvC,YAAY,MAAoB,EAAE,SAAiB;QAC/C,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,KAAK,GAAkB,EAAE,CAAC;QAChC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;YACrB,IAAI,KAAK,CAAC,OAAO,EAAE;gBAAE,OAAO,GAAG,IAAI,CAAC;aAAE;YACtC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;QACH,MAAM,IAAI,GAAG,CAAC,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC;QAEhD,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QACzC,IAAA,gCAAgB,EAAa,IAAI,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACR,MAAM,MAAM,GAAQ,EAAG,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;YAC1B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;QAEH,4DAA4D;QAC5D,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,M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ff --git a/lib.commonjs/abi/fragments.js b/lib.commonjs/abi/fragments.js new file mode 100644 index 000000000..5a086acdf --- /dev/null +++ b/lib.commonjs/abi/fragments.js @@ -0,0 +1,933 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StructFragment = exports.FunctionFragment = exports.ConstructorFragment = exports.EventFragment = exports.ErrorFragment = exports.NamedFragment = exports.Fragment = exports.FragmentType = exports.ParamType = exports.lex = exports.TokenString = exports.FormatType = void 0; +const logger_js_1 = require("../utils/logger.js"); +const index_js_1 = require("../utils/index.js"); +; +var FormatType; +(function (FormatType) { + // Bare formatting, as is needed for computing a sighash of an event or function + FormatType["sighash"] = "sighash"; + // Human-Readable with Minimal spacing and without names (compact human-readable) + FormatType["minimal"] = "minimal"; + // Human-Readable with nice spacing, including all names + FormatType["full"] = "full"; + // JSON-format a la Solidity + FormatType["json"] = "json"; +})(FormatType = exports.FormatType || (exports.FormatType = {})); +; +// [ "a", "b" ] => { "a": 1, "b": 1 } +function setify(items) { + const result = new Set(); + items.forEach((k) => result.add(k)); + return Object.freeze(result); +} +// Visibility Keywords +const _kwVisib = "constant external internal payable private public pure view"; +const KwVisib = setify(_kwVisib.split(" ")); +const _kwTypes = "constructor error event function struct"; +const KwTypes = setify(_kwTypes.split(" ")); +const _kwModifiers = "calldata memory storage payable indexed"; +const KwModifiers = setify(_kwModifiers.split(" ")); +const _kwOther = "tuple returns"; +// All Keywords +const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" "); +const Keywords = setify(_keywords.split(" ")); +// Single character tokens +const SimpleTokens = { + "(": "OPEN_PAREN", ")": "CLOSE_PAREN", + "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET", + ",": "COMMA", "@": "AT" +}; +// Parser regexes to consume the next token +const regexWhitespace = new RegExp("^(\\s*)"); +const regexNumber = new RegExp("^([0-9]+)"); +const regexIdentifier = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); +const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))"); +class TokenString { + #offset; + #tokens; + get offset() { return this.#offset; } + get length() { return this.#tokens.length - this.#offset; } + constructor(tokens) { + this.#offset = 0; + this.#tokens = tokens.slice(); + } + clone() { return new TokenString(this.#tokens); } + reset() { this.#offset = 0; } + #subTokenString(from = 0, to = 0) { + return new TokenString(this.#tokens.slice(from, to).map((t) => { + return Object.freeze(Object.assign({}, t, { + match: (t.match - from), + linkBack: (t.linkBack - from), + linkNext: (t.linkNext - from), + })); + return t; + })); + } + // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens + popKeyword(allowed) { + const top = this.peek(); + if (top.type !== "KEYWORD" || !allowed.has(top.text)) { + throw new Error(`expected keyword ${top.text}`); + } + return this.pop().text; + } + // Pops and returns the value of the next token if it is `type`; throws if out of tokens + popType(type) { + if (this.peek().type !== type) { + throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`); + } + return this.pop().text; + } + // Pops and returns a "(" TOKENS ")" + popParen() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = this.#subTokenString(this.#offset + 1, top.match + 1); + this.#offset = top.match + 1; + return result; + } + // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" + popParams() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = []; + while (this.#offset < top.match - 1) { + const link = this.peek().linkNext; + result.push(this.#subTokenString(this.#offset + 1, link)); + this.#offset = link; + } + this.#offset = top.match + 1; + return result; + } + // Returns the top Token, throwing if out of tokens + peek() { + if (this.#offset >= this.#tokens.length) { + throw new Error("out-of-bounds"); + } + return this.#tokens[this.#offset]; + } + // Returns the next value, if it is a keyword in `allowed` + peekKeyword(allowed) { + const top = this.peekType("KEYWORD"); + return (top != null && allowed.has(top)) ? top : null; + } + // Returns the value of the next token if it is `type` + peekType(type) { + if (this.length === 0) { + return null; + } + const top = this.peek(); + return (top.type === type) ? top.text : null; + } + // Returns the next token; throws if out of tokens + pop() { + const result = this.peek(); + this.#offset++; + return result; + } + toString() { + const tokens = []; + for (let i = this.#offset; i < this.#tokens.length; i++) { + const token = this.#tokens[i]; + tokens.push(`${token.type}:${token.text}`); + } + return ``; + } +} +exports.TokenString = TokenString; +function lex(text) { + const tokens = []; + const throwError = (message) => { + const token = (offset < text.length) ? JSON.stringify(text[offset]) : "$EOI"; + throw new Error(`invalid token ${token} at ${offset}: ${message}`); + }; + let brackets = []; + let commas = []; + let offset = 0; + while (offset < text.length) { + // Strip off any leading whitespace + let cur = text.substring(offset); + let match = cur.match(regexWhitespace); + if (match) { + offset += match[1].length; + cur = text.substring(offset); + } + const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 }; + tokens.push(token); + let type = (SimpleTokens[cur[0]] || ""); + if (type) { + token.type = type; + token.text = cur[0]; + offset++; + if (type === "OPEN_PAREN") { + brackets.push(tokens.length - 1); + commas.push(tokens.length - 1); + } + else if (type == "CLOSE_PAREN") { + if (brackets.length === 0) { + throwError("no matching open bracket"); + } + token.match = brackets.pop(); + (tokens[token.match]).match = tokens.length - 1; + token.depth--; + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + } + else if (type === "COMMA") { + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + commas.push(tokens.length - 1); + } + else if (type === "OPEN_BRACKET") { + token.type = "BRACKET"; + } + else if (type === "CLOSE_BRACKET") { + // Remove the CLOSE_BRACKET + let suffix = tokens.pop().text; + if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { + const value = tokens.pop().text; + suffix = value + suffix; + (tokens[tokens.length - 1]).value = logger_js_1.logger.getNumber(value); + } + if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { + throw new Error("missing opening bracket"); + } + (tokens[tokens.length - 1]).text += suffix; + } + continue; + } + match = cur.match(regexIdentifier); + if (match) { + token.text = match[1]; + offset += token.text.length; + if (Keywords.has(token.text)) { + token.type = "KEYWORD"; + continue; + } + if (token.text.match(regexType)) { + token.type = "TYPE"; + continue; + } + token.type = "ID"; + continue; + } + match = cur.match(regexNumber); + if (match) { + token.text = match[1]; + token.type = "NUMBER"; + offset += token.text.length; + continue; + } + throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); + } + return new TokenString(tokens.map((t) => Object.freeze(t))); +} +exports.lex = lex; +// Check only one of `allowed` is in `set` +function allowSingle(set, allowed) { + let included = []; + for (const key in allowed.keys()) { + if (set.has(key)) { + included.push(key); + } + } + if (included.length > 1) { + throw new Error(`conflicting types: ${included.join(", ")}`); + } +} +// Functions to process a Solidity Signature TokenString from left-to-right for... +// ...the name with an optional type, returning the name +function consumeName(type, tokens) { + if (tokens.peekKeyword(KwTypes)) { + const keyword = tokens.pop().text; + if (keyword !== type) { + throw new Error(`expected ${type}, got ${keyword}`); + } + } + return tokens.popType("ID"); +} +// ...all keywords matching allowed, returning the keywords +function consumeKeywords(tokens, allowed) { + const keywords = new Set(); + while (true) { + const keyword = tokens.peekType("KEYWORD"); + if (keyword == null || (allowed && !allowed.has(keyword))) { + break; + } + tokens.pop(); + if (keywords.has(keyword)) { + throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); + } + keywords.add(keyword); + } + return Object.freeze(keywords); +} +// ...all visibility keywords, returning the coalesced mutability +function consumeMutability(tokens) { + let modifiers = consumeKeywords(tokens, KwVisib); + // Detect conflicting modifiers + allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); + allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); + // Process mutability states + if (modifiers.has("view")) { + return "view"; + } + if (modifiers.has("pure")) { + return "pure"; + } + if (modifiers.has("payable")) { + return "payable"; + } + if (modifiers.has("nonpayable")) { + return "nonpayable"; + } + // Process legacy `constant` last + if (modifiers.has("constant")) { + return "view"; + } + return "nonpayable"; +} +// ...a parameter list, returning the ParamType list +function consumeParams(tokens, allowIndexed) { + return tokens.popParams().map((t) => ParamType.fromTokens(t, allowIndexed)); +} +// ...a gas limit, returning a BigNumber or null if none +function consumeGas(tokens) { + if (tokens.peekType("AT")) { + tokens.pop(); + if (tokens.peekType("NUMBER")) { + return logger_js_1.logger.getBigInt(tokens.pop().text); + } + throw new Error("invalid gas"); + } + return null; +} +function consumeEoi(tokens) { + if (tokens.length) { + throw new Error(`unexpected tokens: ${tokens.toString()}`); + } +} +const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); +function verifyBasicType(type) { + const match = type.match(regexType); + if (!match) { + return logger_js_1.logger.throwArgumentError("invalid type", "type", type); + } + if (type === "uint") { + return "uint256"; + } + if (type === "int") { + return "int256"; + } + if (match[2]) { + // bytesXX + const length = parseInt(match[2]); + if (length === 0 || length > 32) { + logger_js_1.logger.throwArgumentError("invalid bytes length", "type", type); + } + } + else if (match[3]) { + // intXX or uintXX + const size = parseInt(match[3]); + if (size === 0 || size > 256 || size % 8) { + logger_js_1.logger.throwArgumentError("invalid numeric width", "type", type); + } + } + return type; +} +// Make the Fragment constructors effectively private +const _guard = {}; +const internal = Symbol.for("_ethers_internal"); +const ParamTypeInternal = "_ParamTypeInternal"; +class ParamType { + // The local name of the parameter (of "" if unbound) + name; + // The fully qualified type (e.g. "address", "tuple(address)", "uint256[3][]" + type; + // The base type (e.g. "address", "tuple", "array") + baseType; + // Indexable Paramters ONLY (otherwise null) + indexed; + // Tuples ONLY: (otherwise null) + // - sub-components + components; + // Arrays ONLY: (otherwise null) + // - length of the array (-1 for dynamic length) + // - child type + arrayLength; + arrayChildren; + constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) { + logger_js_1.logger.assertPrivate(guard, _guard, "ParamType"); + Object.defineProperty(this, internal, { value: ParamTypeInternal }); + if (components) { + components = Object.freeze(components.slice()); + } + if (baseType === "array") { + if (arrayLength == null || arrayChildren == null) { + throw new Error(""); + } + } + else if (arrayLength != null || arrayChildren != null) { + throw new Error(""); + } + if (baseType === "tuple") { + if (components == null) { + throw new Error(""); + } + } + else if (components != null) { + throw new Error(""); + } + (0, index_js_1.defineProperties)(this, { + name, type, baseType, indexed, components, arrayLength, arrayChildren + }); + } + // Format the parameter fragment + // - sighash: "(uint256,address)" + // - minimal: "tuple(uint256,address) indexed" + // - full: "tuple(uint256 foo, address bar) indexed baz" + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger_js_1.logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + let result = { + type: ((this.baseType === "tuple") ? "tuple" : this.type), + name: (this.name || undefined) + }; + if (typeof (this.indexed) === "boolean") { + result.indexed = this.indexed; + } + if (this.isTuple()) { + result.components = this.components.map((c) => JSON.parse(c.format(format))); + } + return JSON.stringify(result); + } + let result = ""; + // Array + if (this.isArray()) { + result += this.arrayChildren.format(format); + result += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`; + } + else { + if (this.isTuple()) { + if (format !== FormatType.sighash) { + result += this.type; + } + result += "(" + this.components.map((comp) => comp.format(format)).join((format === FormatType.full) ? ", " : ",") + ")"; + } + else { + result += this.type; + } + } + if (format !== FormatType.sighash) { + if (this.indexed === true) { + result += " indexed"; + } + if (format === FormatType.full && this.name) { + result += " " + this.name; + } + } + return result; + } + static isArray(value) { + return value && (value.baseType === "array"); + } + isArray() { + return (this.baseType === "array"); + } + isTuple() { + return (this.baseType === "tuple"); + } + isIndexable() { + return (this.indexed != null); + } + walk(value, process) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invlaid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + return value.map((v) => (this.arrayChildren.walk(v, process))); + } + if (this.isTuple()) { + if (!Array.isArray(value)) { + throw new Error("invlaid tuple value"); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + return value.map((v, i) => (this.components[i].walk(v, process))); + } + return process(this.type, value); + } + #walkAsync(promises, value, process, setValue) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invlaid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const childType = this.arrayChildren; + const result = value.slice(); + result.forEach((value, index) => { + childType.#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + if (this.isTuple()) { + const components = this.components; + // Convert the object into an array + let result; + if (Array.isArray(value)) { + result = value.slice(); + } + else { + if (value == null || typeof (value) !== "object") { + throw new Error("invlaid tuple value"); + } + result = components.map((param) => { + if (!param.name) { + throw new Error("cannot use object value with unnamed components"); + } + if (!(param.name in value)) { + throw new Error(`missing value for component ${param.name}`); + } + return value[param.name]; + }); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + result.forEach((value, index) => { + components[index].#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + const result = process(this.type, value); + if (result.then) { + promises.push((async function () { setValue(await result); })()); + } + else { + setValue(result); + } + } + async walkAsync(value, process) { + const promises = []; + const result = [value]; + this.#walkAsync(promises, value, process, (value) => { + result[0] = value; + }); + if (promises.length) { + await Promise.all(promises); + } + return result[0]; + } + static from(obj, allowIndexed) { + if (ParamType.isParamType(obj)) { + return obj; + } + if (typeof (obj) === "string") { + return ParamType.fromTokens(lex(obj), allowIndexed); + } + if (obj instanceof TokenString) { + return ParamType.fromTokens(obj, allowIndexed); + } + const name = obj.name; + if (name && (typeof (name) !== "string" || !name.match(regexIdentifier))) { + logger_js_1.logger.throwArgumentError("invalid name", "obj.name", name); + } + let indexed = obj.indexed; + if (indexed != null) { + if (!allowIndexed) { + logger_js_1.logger.throwArgumentError("parameter cannot be indexed", "obj.indexed", obj.indexed); + } + indexed = !!indexed; + } + let type = obj.type; + let arrayMatch = type.match(regexArrayType); + if (arrayMatch) { + const arrayLength = arrayMatch[2]; + const arrayChildren = ParamType.from({ + type: arrayMatch[1], + components: obj.components + }); + return new ParamType(_guard, name, type, "array", indexed, null, arrayLength, arrayChildren); + } + if (type.substring(0, 5) === "tuple(" || type[0] === "(") { + const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null; + const tuple = new ParamType(_guard, name, type, "tuple", indexed, comps, null, null); + // @TODO: use lexer to validate and normalize type + return tuple; + } + type = verifyBasicType(obj.type); + return new ParamType(_guard, name, type, type, indexed, null, null, null); + } + static fromObject(obj, allowIndexed) { + throw new Error("@TODO"); + } + static fromTokens(tokens, allowIndexed) { + let type = "", baseType = ""; + let comps = null; + if (consumeKeywords(tokens, setify(["tuple"])).has("tuple") || tokens.peekType("OPEN_PAREN")) { + // Tuple + baseType = "tuple"; + comps = tokens.popParams().map((t) => ParamType.from(t)); + type = `tuple(${comps.map((c) => c.format()).join(",")})`; + } + else { + // Normal + type = verifyBasicType(tokens.popType("TYPE")); + baseType = type; + } + // Check for Array + let arrayChildren = null; + let arrayLength = null; + while (tokens.length && tokens.peekType("BRACKET")) { + const bracket = tokens.pop(); //arrays[i]; + arrayChildren = new ParamType(_guard, "", type, baseType, null, comps, arrayLength, arrayChildren); + arrayLength = bracket.value; + type += bracket.text; + baseType = "array"; + comps = null; + } + let indexed = null; + const keywords = consumeKeywords(tokens, KwModifiers); + if (keywords.has("indexed")) { + if (!allowIndexed) { + throw new Error(""); + } + indexed = true; + } + const name = (tokens.peekType("ID") ? tokens.pop().text : ""); + if (tokens.length) { + throw new Error("leftover tokens"); + } + return new ParamType(_guard, name, type, baseType, indexed, comps, arrayLength, arrayChildren); + } + static isParamType(value) { + return (value && value[internal] === ParamTypeInternal); + } +} +exports.ParamType = ParamType; +var FragmentType; +(function (FragmentType) { + FragmentType["constructor"] = "constructor"; + FragmentType["error"] = "error"; + FragmentType["event"] = "event"; + FragmentType["function"] = "function"; + FragmentType["struct"] = "struct"; +})(FragmentType = exports.FragmentType || (exports.FragmentType = {})); +; +class Fragment { + type; + inputs; + constructor(guard, type, inputs) { + logger_js_1.logger.assertPrivate(guard, _guard, "Fragment"); + inputs = Object.freeze(inputs.slice()); + (0, index_js_1.defineProperties)(this, { type, inputs }); + } + static from(obj) { + if (typeof (obj) === "string") { + return this.fromString(obj); + } + if (obj instanceof TokenString) { + return this.fromTokens(obj); + } + if (typeof (obj) === "object") { + return this.fromObject(obj); + } + throw new Error(`unsupported type: ${obj}`); + } + static fromObject(obj) { + switch (obj.type) { + case "constructor": return ConstructorFragment.fromObject(obj); + case "error": return ErrorFragment.fromObject(obj); + case "event": return EventFragment.fromObject(obj); + case "function": return FunctionFragment.fromObject(obj); + case "struct": return StructFragment.fromObject(obj); + } + throw new Error("not implemented yet"); + } + static fromString(text) { + try { + Fragment.from(JSON.parse(text)); + } + catch (e) { } + return Fragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const type = tokens.popKeyword(KwTypes); + switch (type) { + case "constructor": return ConstructorFragment.fromTokens(tokens); + case "error": return ErrorFragment.fromTokens(tokens); + case "event": return EventFragment.fromTokens(tokens); + case "function": return FunctionFragment.fromTokens(tokens); + case "struct": return StructFragment.fromTokens(tokens); + } + throw new Error(`unsupported type: ${type}`); + } + /* + static fromTokens(tokens: TokenString): Fragment { + const assertDone = () => { + if (tokens.length) { throw new Error(`unexpected tokens: ${ tokens.toString() }`); } + }); + + const type = (tokens.length && tokens.peek().type === "KEYWORD") ? tokens.peek().text: "unknown"; + + const name = consumeName("error", tokens); + const inputs = consumeParams(tokens, type === "event"); + + switch (type) { + case "event": case "struct": + assertDone(); + } + + } + */ + static isConstructor(value) { + return (value && value.type === "constructor"); + } + static isError(value) { + return (value && value.type === "error"); + } + static isEvent(value) { + return (value && value.type === "event"); + } + static isFunction(value) { + return (value && value.type === "function"); + } + static isStruct(value) { + return (value && value.type === "struct"); + } +} +exports.Fragment = Fragment; +class NamedFragment extends Fragment { + name; + constructor(guard, type, name, inputs) { + super(guard, type, inputs); + inputs = Object.freeze(inputs.slice()); + (0, index_js_1.defineProperties)(this, { name }); + } +} +exports.NamedFragment = NamedFragment; +function joinParams(format, params) { + return "(" + params.map((p) => p.format(format)).join((format === FormatType.full) ? ", " : ",") + ")"; +} +class ErrorFragment extends NamedFragment { + constructor(guard, name, inputs) { + super(guard, FragmentType.error, name, inputs); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger_js_1.logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input) => JSON.parse(input.format(format))), + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("error"); + } + result.push(this.name + joinParams(format, this.inputs)); + return result.join(" "); + } + static fromString(text) { + return ErrorFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("error", tokens); + const inputs = consumeParams(tokens); + consumeEoi(tokens); + return new ErrorFragment(_guard, name, inputs); + } +} +exports.ErrorFragment = ErrorFragment; +class EventFragment extends NamedFragment { + anonymous; + constructor(guard, name, inputs, anonymous) { + super(guard, FragmentType.event, name, inputs); + (0, index_js_1.defineProperties)(this, { anonymous }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger_js_1.logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("event"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== FormatType.sighash && this.anonymous) { + result.push("anonymous"); + } + return result.join(" "); + } + static fromString(text) { + return EventFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("event", tokens); + const inputs = consumeParams(tokens, true); + const anonymous = !!consumeKeywords(tokens, setify(["anonymous"])).has("anonymous"); + consumeEoi(tokens); + return new EventFragment(_guard, name, inputs, anonymous); + } +} +exports.EventFragment = EventFragment; +class ConstructorFragment extends Fragment { + payable; + gas; + constructor(guard, type, inputs, payable, gas) { + super(guard, type, inputs); + (0, index_js_1.defineProperties)(this, { payable, gas }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger_js_1.logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.sighash) { + logger_js_1.logger.throwError("cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { + operation: "format(sighash)" + }); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "constructor", + stateMutability: (this.payable ? "payable" : "undefined"), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = [`constructor${joinParams(format, this.inputs)}`]; + result.push((this.payable) ? "payable" : "nonpayable"); + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + return result.join(" "); + } + static fromString(text) { + return ConstructorFragment.fromTokens(lex(text)); + } + static fromObject(obj) { + throw new Error("TODO"); + } + static fromTokens(tokens) { + consumeKeywords(tokens, setify(["constructor"])); + const inputs = consumeParams(tokens); + const payable = !!consumeKeywords(tokens, setify(["payable"])).has("payable"); + const gas = consumeGas(tokens); + consumeEoi(tokens); + return new ConstructorFragment(_guard, FragmentType.constructor, inputs, payable, gas); + } +} +exports.ConstructorFragment = ConstructorFragment; +class FunctionFragment extends NamedFragment { + constant; + outputs; + stateMutability; + payable; + gas; + constructor(guard, name, stateMutability, inputs, outputs, gas) { + super(guard, FragmentType.function, name, inputs); + outputs = Object.freeze(outputs.slice()); + const constant = (stateMutability === "view" || stateMutability === "pure"); + const payable = (stateMutability === "payable"); + (0, index_js_1.defineProperties)(this, { constant, gas, outputs, payable, stateMutability }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger_js_1.logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))), + outputs: this.outputs.map((o) => JSON.parse(o.format(format))), + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("function"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== FormatType.sighash) { + if (this.stateMutability !== "nonpayable") { + result.push(this.stateMutability); + } + if (this.outputs && this.outputs.length) { + result.push("returns"); + result.push(joinParams(format, this.outputs)); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + } + return result.join(" "); + } + static fromString(text) { + return FunctionFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("function", tokens); + const inputs = consumeParams(tokens); + const mutability = consumeMutability(tokens); + let outputs = []; + if (consumeKeywords(tokens, setify(["returns"])).has("returns")) { + outputs = consumeParams(tokens); + } + const gas = consumeGas(tokens); + consumeEoi(tokens); + return new FunctionFragment(_guard, name, mutability, inputs, outputs, gas); + } +} +exports.FunctionFragment = FunctionFragment; +class StructFragment extends NamedFragment { + format() { + throw new Error("@TODO"); + } + static fromString(text) { + return StructFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("struct", tokens); + const inputs = consumeParams(tokens); + consumeEoi(tokens); + return new StructFragment(_guard, FragmentType.struct, name, inputs); + } +} +exports.StructFragment = StructFragment; +//# sourceMappingURL=fragments.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/fragments.js.map b/lib.commonjs/abi/fragments.js.map new file mode 100644 index 000000000..0ea1692e7 --- /dev/null +++ b/lib.commonjs/abi/fragments.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fragments.js","sourceRoot":"","sources":["../../src.ts/abi/fragments.ts"],"names":[],"mappings":";;;AAAA,kDAA4C;AAC5C,gDAAqD;AAyBpD,CAAC;AAEF,IAAY,UAYX;AAZD,WAAY,UAAU;IAClB,gFAAgF;IAChF,iCAAmB,CAAA;IAEnB,iFAAiF;IACjF,iCAAmB,CAAA;IAEnB,wDAAwD;IACxD,2BAAa,CAAA;IAEb,4BAA4B;IAC5B,2BAAa,CAAA;AACjB,CAAC,EAZW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAYrB;AAAA,CAAC;AAEF,qC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CAAC;QAC7C,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,UAAU,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;QAE7C,IAAI,OAAO,GAAqB,EAAG,CAAC;QACpC,IAAI,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,CAAE,SAAS,CAAE,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YAC/D,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;SACnC;QAED,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAE/B,UAAU,CAAC,MAAM,CAAC,CAAC;QAEnB,OAAO,IAAI,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAChF,CAAC;CACJ;AA3ED,4CA2EC;AAED,MAAa,cAAe,SAAQ,aAAa;IAC7C,MAAM;QACF,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,IAAY;QAC1B,OAAO,cAAc,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAmB;QACjC,MAAM,IAAI,GAAG,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC3C,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QACrC,UAAU,CAAC,MAAM,CAAC,CAAC;QAEnB,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACzE,CAAC;CACJ;AAhBD,wCAgBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/index.js b/lib.commonjs/abi/index.js new file mode 100644 index 000000000..e176cefb7 --- /dev/null +++ b/lib.commonjs/abi/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Typed = exports.TransactionDescription = exports.Result = exports.LogDescription = exports.Interface = exports.Indexed = exports.checkResultErrors = exports.ParamType = exports.FunctionFragment = exports.Fragment = exports.EventFragment = exports.ErrorFragment = exports.ConstructorFragment = exports.parseBytes32String = exports.formatBytes32String = exports.defaultAbiCoder = exports.AbiCoder = void 0; +var abi_coder_js_1 = require("./abi-coder.js"); +Object.defineProperty(exports, "AbiCoder", { enumerable: true, get: function () { return abi_coder_js_1.AbiCoder; } }); +Object.defineProperty(exports, "defaultAbiCoder", { enumerable: true, get: function () { return abi_coder_js_1.defaultAbiCoder; } }); +var bytes32_js_1 = require("./bytes32.js"); +Object.defineProperty(exports, "formatBytes32String", { enumerable: true, get: function () { return bytes32_js_1.formatBytes32String; } }); +Object.defineProperty(exports, "parseBytes32String", { enumerable: true, get: function () { return bytes32_js_1.parseBytes32String; } }); +var fragments_js_1 = require("./fragments.js"); +Object.defineProperty(exports, "ConstructorFragment", { enumerable: true, get: function () { return fragments_js_1.ConstructorFragment; } }); +Object.defineProperty(exports, "ErrorFragment", { enumerable: true, get: function () { return fragments_js_1.ErrorFragment; } }); +Object.defineProperty(exports, "EventFragment", { enumerable: true, get: function () { return fragments_js_1.EventFragment; } }); +Object.defineProperty(exports, "Fragment", { enumerable: true, get: function () { return fragments_js_1.Fragment; } }); +Object.defineProperty(exports, "FunctionFragment", { enumerable: true, get: function () { return fragments_js_1.FunctionFragment; } }); +Object.defineProperty(exports, "ParamType", { enumerable: true, get: function () { return fragments_js_1.ParamType; } }); +var interface_js_1 = require("./interface.js"); +Object.defineProperty(exports, "checkResultErrors", { enumerable: true, get: function () { return interface_js_1.checkResultErrors; } }); +Object.defineProperty(exports, "Indexed", { enumerable: true, get: function () { return interface_js_1.Indexed; } }); +Object.defineProperty(exports, "Interface", { enumerable: true, get: function () { return interface_js_1.Interface; } }); +Object.defineProperty(exports, "LogDescription", { enumerable: true, get: function () { return interface_js_1.LogDescription; } }); +Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return interface_js_1.Result; } }); +Object.defineProperty(exports, "TransactionDescription", { enumerable: true, get: function () { return interface_js_1.TransactionDescription; } }); +var typed_js_1 = require("./typed.js"); +Object.defineProperty(exports, "Typed", { enumerable: true, get: function () { return typed_js_1.Typed; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/index.js.map b/lib.commonjs/abi/index.js.map new file mode 100644 index 000000000..3f3864e34 --- /dev/null +++ b/lib.commonjs/abi/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/abi/index.ts"],"names":[],"mappings":";;;AACA,+CAGwB;AAFpB,wGAAA,QAAQ,OAAA;AACR,+GAAA,eAAe,OAAA;AAGnB,2CAAuE;AAA9D,iHAAA,mBAAmB,OAAA;AAAE,gHAAA,kBAAkB,OAAA;AAEhD,+CAOwB;AANpB,mHAAA,mBAAmB,OAAA;AACnB,6GAAA,aAAa,OAAA;AACb,6GAAA,aAAa,OAAA;AACb,wGAAA,QAAQ,OAAA;AACR,gHAAA,gBAAgB,OAAA;AAChB,yGAAA,SAAS,OAAA;AAGb,+CAOwB;AANpB,iHAAA,iBAAiB,OAAA;AACjB,uGAAA,OAAO,OAAA;AACP,yGAAA,SAAS,OAAA;AACT,8GAAA,cAAc,OAAA;AACd,sGAAA,MAAM,OAAA;AACN,sHAAA,sBAAsB,OAAA;AAG1B,uCAAmC;AAA1B,iGAAA,KAAK,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/abi/interface.js b/lib.commonjs/abi/interface.js new file mode 100644 index 000000000..fe90acde1 --- /dev/null +++ b/lib.commonjs/abi/interface.js @@ -0,0 +1,817 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Interface = exports.Indexed = exports.ErrorDescription = exports.TransactionDescription = exports.LogDescription = exports.Result = exports.checkResultErrors = void 0; +const data_js_1 = require("../utils/data.js"); +const index_js_1 = require("../crypto/index.js"); +const index_js_2 = require("../hash/index.js"); +const logger_js_1 = require("../utils/logger.js"); +const properties_js_1 = require("../utils/properties.js"); +const maths_js_1 = require("../utils/maths.js"); +const abi_coder_js_1 = require("./abi-coder.js"); +const abstract_coder_js_1 = require("./coders/abstract-coder.js"); +Object.defineProperty(exports, "checkResultErrors", { enumerable: true, get: function () { return abstract_coder_js_1.checkResultErrors; } }); +Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return abstract_coder_js_1.Result; } }); +const fragments_js_1 = require("./fragments.js"); +const typed_js_1 = require("./typed.js"); +class LogDescription { + fragment; + name; + signature; + topic; + args; + constructor(fragment, topic, args) { + const name = fragment.name, signature = fragment.format(); + (0, properties_js_1.defineProperties)(this, { + fragment, name, signature, topic, args + }); + } +} +exports.LogDescription = LogDescription; +class TransactionDescription { + fragment; + name; + args; + signature; + selector; + value; + constructor(fragment, selector, args, value) { + const name = fragment.name, signature = fragment.format(); + (0, properties_js_1.defineProperties)(this, { + fragment, name, args, signature, selector, value + }); + } +} +exports.TransactionDescription = TransactionDescription; +class ErrorDescription { + fragment; + name; + args; + signature; + selector; + constructor(fragment, selector, args) { + const name = fragment.name, signature = fragment.format(); + (0, properties_js_1.defineProperties)(this, { + fragment, name, args, signature, selector + }); + } +} +exports.ErrorDescription = ErrorDescription; +class Indexed { + hash; + _isIndexed; + static isIndexed(value) { + return !!(value && value._isIndexed); + } + constructor(hash) { + (0, properties_js_1.defineProperties)(this, { hash, _isIndexed: true }); + } +} +exports.Indexed = Indexed; +// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require +const PanicReasons = { + "0": "generic panic", + "1": "assert(false)", + "17": "arithmetic overflow", + "18": "division or modulo by zero", + "33": "enum overflow", + "34": "invalid encoded storage byte array accessed", + "49": "out-of-bounds array access; popping on an empty array", + "50": "out-of-bounds access of an array or bytesN", + "65": "out of memory", + "81": "uninitialized function", +}; +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: ["string"], + reason: (message) => { + return `reverted with reason string ${JSON.stringify(message)}`; + } + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: ["uint256"], + reason: (code) => { + let reason = "unknown panic code"; + if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) { + reason = PanicReasons[code.toString()]; + } + return `reverted with panic code 0x${code.toString(16)} (${reason})`; + } + } +}; +class Interface { + fragments; + deploy; + #errors; + #events; + #functions; + // #structs: Map; + #abiCoder; + constructor(fragments) { + let abi = []; + if (typeof (fragments) === "string") { + abi = JSON.parse(fragments); + } + else { + abi = fragments; + } + this.#functions = new Map(); + this.#errors = new Map(); + this.#events = new Map(); + // this.#structs = new Map(); + (0, properties_js_1.defineProperties)(this, { + fragments: Object.freeze(abi.map((f) => fragments_js_1.Fragment.from(f)).filter((f) => (f != null))), + }); + this.#abiCoder = this.getAbiCoder(); + // Add all fragments by their signature + this.fragments.forEach((fragment) => { + let bucket; + switch (fragment.type) { + case "constructor": + if (this.deploy) { + logger_js_1.logger.warn("duplicate definition - constructor"); + return; + } + //checkNames(fragment, "input", fragment.inputs); + (0, properties_js_1.defineProperties)(this, { deploy: fragment }); + return; + case "function": + //checkNames(fragment, "input", fragment.inputs); + //checkNames(fragment, "output", (fragment).outputs); + bucket = this.#functions; + break; + case "event": + //checkNames(fragment, "input", fragment.inputs); + bucket = this.#events; + break; + case "error": + bucket = this.#errors; + break; + default: + return; + } + const signature = fragment.format(); + if (bucket.has(signature)) { + logger_js_1.logger.warn("duplicate definition - " + signature); + return; + } + bucket.set(signature, fragment); + }); + // If we do not have a constructor add a default + if (!this.deploy) { + (0, properties_js_1.defineProperties)(this, { + deploy: fragments_js_1.ConstructorFragment.fromString("constructor()") + }); + } + } + // @TODO: multi sig? + format(format) { + if (!format) { + format = fragments_js_1.FormatType.full; + } + if (format === fragments_js_1.FormatType.sighash) { + logger_js_1.logger.throwArgumentError("interface does not support formatting sighash", "format", format); + } + const abi = this.fragments.map((f) => f.format(format)); + // We need to re-bundle the JSON fragments a bit + if (format === fragments_js_1.FormatType.json) { + return JSON.stringify(abi.map((j) => JSON.parse(j))); + } + return abi; + } + getAbiCoder() { + return abi_coder_js_1.defaultAbiCoder; + } + //static getAddress(address: string): string { + // return getAddress(address); + //} + //static getSelector(fragment: ErrorFragment | FunctionFragment): string { + // return dataSlice(id(fragment.format()), 0, 4); + //} + //static getEventTopic(eventFragment: EventFragment): string { + // return id(eventFragment.format()); + //} + // Find a function definition by any means necessary (unless it is ambiguous) + #getFunction(key, values, forceUnique) { + // Selector + if ((0, data_js_1.isHexString)(key)) { + const selector = key.toLowerCase(); + for (const fragment of this.#functions.values()) { + if (selector === this.getSelector(fragment)) { + return fragment; + } + } + logger_js_1.logger.throwArgumentError("no matching function", "selector", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#functions) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + const lastValue = (values.length > 0) ? values[values.length - 1] : null; + let valueLength = values.length; + let allowOptions = true; + if (typed_js_1.Typed.isTyped(lastValue) && lastValue.type === "overrides") { + allowOptions = false; + valueLength--; + } + // Remove all matches that don't have a compatible length. The args + // may contain an overrides, so the match may have n or n - 1 parameters + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs.length; + if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!typed_js_1.Typed.isTyped(values[j])) { + continue; + } + // We are past the inputs + if (j >= inputs.length) { + if (values[j].type === "overrides") { + continue; + } + matching.splice(i, 1); + break; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + // We found a single matching signature with an overrides, but the + // last value is something that cannot possibly be an options + if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { + const lastArg = values[values.length - 1]; + if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== "object") { + matching.splice(0, 1); + } + } + if (matching.length === 0) { + logger_js_1.logger.throwArgumentError("no matching function", "name", key); + } + else if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", "); + logger_js_1.logger.throwArgumentError(`multiple matching functions (i.e. ${matchStr})`, "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#functions.get(fragments_js_1.FunctionFragment.fromString(key).format()); + if (result) { + return result; + } + return logger_js_1.logger.throwArgumentError("no matching function", "signature", key); + } + getFunctionName(key) { + return (this.#getFunction(key, null, false)).name; + } + getFunction(key, values) { + return this.#getFunction(key, values || null, true); + } + // Find an event definition by any means necessary (unless it is ambiguous) + #getEvent(key, values, forceUnique) { + // EventTopic + if ((0, data_js_1.isHexString)(key)) { + const eventTopic = key.toLowerCase(); + for (const fragment of this.#events.values()) { + if (eventTopic === this.getEventTopic(fragment)) { + return fragment; + } + } + logger_js_1.logger.throwArgumentError("no matching event", "eventTopic", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#events) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + // Remove all matches that don't have a compatible length. + for (let i = matching.length - 1; i >= 0; i--) { + if (matching[i].inputs.length < values.length) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!typed_js_1.Typed.isTyped(values[j])) { + continue; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 0) { + logger_js_1.logger.throwArgumentError("no matching event", "name", key); + } + else if (matching.length > 1 && forceUnique) { + // @TODO: refine by Typed + logger_js_1.logger.throwArgumentError("multiple matching events", "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#events.get(fragments_js_1.EventFragment.fromString(key).format()); + if (result) { + return result; + } + return logger_js_1.logger.throwArgumentError("no matching event", "signature", key); + } + getEventName(key) { + return (this.#getEvent(key, null, false)).name; + } + getEvent(key, values) { + return this.#getEvent(key, values || null, true); + } + // Find a function definition by any means necessary (unless it is ambiguous) + getError(key, values) { + if ((0, data_js_1.isHexString)(key)) { + const selector = key.toLowerCase(); + if (BuiltinErrors[selector]) { + return fragments_js_1.ErrorFragment.fromString(BuiltinErrors[selector].signature); + } + for (const fragment of this.#errors.values()) { + if (selector === this.getSelector(fragment)) { + return fragment; + } + } + logger_js_1.logger.throwArgumentError("no matching error", "selector", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#errors) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (matching.length === 0) { + if (key === "Error") { + return fragments_js_1.ErrorFragment.fromString("error Error(string)"); + } + if (key === "Panic") { + return fragments_js_1.ErrorFragment.fromString("error Panic(uint256)"); + } + logger_js_1.logger.throwArgumentError("no matching error", "name", key); + } + else if (matching.length > 1) { + // @TODO: refine by Typed + logger_js_1.logger.throwArgumentError("multiple matching errors", "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + key = fragments_js_1.ErrorFragment.fromString(key).format(); + if (key === "Error(string)") { + return fragments_js_1.ErrorFragment.fromString("error Error(string)"); + } + if (key === "Panic(uint256)") { + return fragments_js_1.ErrorFragment.fromString("error Panic(uint256)"); + } + const result = this.#errors.get(key); + if (result) { + return result; + } + return logger_js_1.logger.throwArgumentError("no matching error", "signature", key); + } + // Get the 4-byte selector used by Solidity to identify a function + getSelector(fragment) { + /* + if (typeof(fragment) === "string") { + const matches: Array = [ ]; + + try { matches.push(this.getFunction(fragment)); } catch (error) { } + try { matches.push(this.getError(fragment)); } catch (_) { } + + if (matches.length === 0) { + logger.throwArgumentError("unknown fragment", "key", fragment); + } else if (matches.length > 1) { + logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment); + } + + fragment = matches[0]; + } + */ + return (0, data_js_1.dataSlice)((0, index_js_2.id)(fragment.format()), 0, 4); + } + // Get the 32-byte topic hash used by Solidity to identify an event + getEventTopic(fragment) { + //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); } + return (0, index_js_2.id)(fragment.format()); + } + _decodeParams(params, data) { + return this.#abiCoder.decode(params, data); + } + _encodeParams(params, values) { + return this.#abiCoder.encode(params, values); + } + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); + } + decodeErrorResult(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getError(fragment); + } + if ((0, data_js_1.dataSlice)(data, 0, 4) !== this.getSelector(fragment)) { + logger_js_1.logger.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", data); + } + return this._decodeParams(fragment.inputs, (0, data_js_1.dataSlice)(data, 4)); + } + encodeErrorResult(fragment, values) { + if (typeof (fragment) === "string") { + fragment = this.getError(fragment); + } + return (0, data_js_1.concat)([ + this.getSelector(fragment), + this._encodeParams(fragment.inputs, values || []) + ]); + } + // Decode the data for a function call (e.g. tx.data) + decodeFunctionData(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + if ((0, data_js_1.dataSlice)(data, 0, 4) !== this.getSelector(fragment)) { + logger_js_1.logger.throwArgumentError(`data signature does not match function ${fragment.name}.`, "data", data); + } + return this._decodeParams(fragment.inputs, (0, data_js_1.dataSlice)(data, 4)); + } + // Encode the data for a function call (e.g. tx.data) + encodeFunctionData(fragment, values) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + return (0, data_js_1.concat)([ + this.getSelector(fragment), + this._encodeParams(fragment.inputs, values || []) + ]); + } + // Decode the result from a function call (e.g. from eth_call) + decodeFunctionResult(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + let message = "invalid length for result data"; + const bytes = logger_js_1.logger.getBytesCopy(data); + if ((bytes.length % 32) === 0) { + try { + return this.#abiCoder.decode(fragment.outputs, bytes); + } + catch (error) { + message = "could not decode result data"; + } + } + // Call returned data with no error, but the data is junk + return logger_js_1.logger.throwError(message, "BAD_DATA", { + value: (0, data_js_1.hexlify)(bytes), + info: { method: fragment.name, signature: fragment.format() } + }); + } + makeError(fragment, _data, tx) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + const data = logger_js_1.logger.getBytes(_data); + let args = undefined; + if (tx) { + try { + args = this.#abiCoder.decode(fragment.inputs, tx.data || "0x"); + } + catch (error) { + console.log(error); + } + } + let errorArgs = undefined; + let errorName = undefined; + let errorSignature = undefined; + let reason = "unknown reason"; + if (data.length === 0) { + reason = "missing error reason"; + } + else if ((data.length % 32) === 4) { + const selector = (0, data_js_1.hexlify)(data.slice(0, 4)); + const builtin = BuiltinErrors[selector]; + if (builtin) { + try { + errorName = builtin.name; + errorSignature = builtin.signature; + errorArgs = this.#abiCoder.decode(builtin.inputs, data.slice(4)); + reason = builtin.reason(...errorArgs); + } + catch (error) { + console.log(error); // @TODO: remove + } + } + else { + reason = "unknown custom error"; + try { + const error = this.getError(selector); + errorName = error.name; + errorSignature = error.format(); + reason = `custom error: ${errorSignature}`; + try { + errorArgs = this.#abiCoder.decode(error.inputs, data.slice(4)); + } + catch (error) { + reason = `custom error: ${errorSignature} (coult not decode error data)`; + } + } + catch (error) { + console.log(error); // @TODO: remove + } + } + } + return logger_js_1.logger.makeError("call revert exception", "CALL_EXCEPTION", { + data: (0, data_js_1.hexlify)(data), transaction: null, + method: fragment.name, signature: fragment.format(), args, + errorArgs, errorName, errorSignature, reason + }); + } + // Encode the result for a function call (e.g. for eth_call) + encodeFunctionResult(functionFragment, values) { + if (typeof (functionFragment) === "string") { + functionFragment = this.getFunction(functionFragment); + } + return (0, data_js_1.hexlify)(this.#abiCoder.encode(functionFragment.outputs, values || [])); + } + /* + spelunk(inputs: Array, values: ReadonlyArray, processfunc: (type: string, value: any) => Promise): Promise> { + const promises: Array> = [ ]; + const process = function(type: ParamType, value: any): any { + if (type.baseType === "array") { + return descend(type.child + } + if (type. === "address") { + } + }; + + const descend = function (inputs: Array, values: ReadonlyArray) { + if (inputs.length !== values.length) { throw new Error("length mismatch"); } + + }; + + const result: Array = [ ]; + values.forEach((value, index) => { + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + } + */ + // Create the filter for the event with search criteria (e.g. for eth_filterLog) + encodeFilterTopics(eventFragment, values) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (values.length > eventFragment.inputs.length) { + logger_js_1.logger.throwError("too many arguments for " + eventFragment.format(), "UNEXPECTED_ARGUMENT", { + count: values.length, + expectedCount: eventFragment.inputs.length + }); + } + const topics = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + // @TODO: Use the coders for this; to properly support tuples, etc. + const encodeTopic = (param, value) => { + if (param.type === "string") { + return (0, index_js_2.id)(value); + } + else if (param.type === "bytes") { + return (0, index_js_1.keccak256)((0, data_js_1.hexlify)(value)); + } + if (param.type === "bool" && typeof (value) === "boolean") { + value = (value ? "0x01" : "0x00"); + } + if (param.type.match(/^u?int/)) { + value = (0, maths_js_1.toHex)(value); + } + // Check addresses are valid + if (param.type === "address") { + this.#abiCoder.encode(["address"], [value]); + } + return (0, data_js_1.zeroPadValue)((0, data_js_1.hexlify)(value), 32); + //@TOOD should probably be return toHex(value, 32) + }; + values.forEach((value, index) => { + const param = eventFragment.inputs[index]; + if (!param.indexed) { + if (value != null) { + logger_js_1.logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value); + } + return; + } + if (value == null) { + topics.push(null); + } + else if (param.baseType === "array" || param.baseType === "tuple") { + logger_js_1.logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } + else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } + else { + topics.push(encodeTopic(param, value)); + } + }); + // Trim off trailing nulls + while (topics.length && topics[topics.length - 1] === null) { + topics.pop(); + } + return topics; + } + encodeEventLog(eventFragment, values) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + if (values.length !== eventFragment.inputs.length) { + logger_js_1.logger.throwArgumentError("event arguments/values mismatch", "values", values); + } + eventFragment.inputs.forEach((param, index) => { + const value = values[index]; + if (param.indexed) { + if (param.type === "string") { + topics.push((0, index_js_2.id)(value)); + } + else if (param.type === "bytes") { + topics.push((0, index_js_1.keccak256)(value)); + } + else if (param.baseType === "tuple" || param.baseType === "array") { + // @TODO + throw new Error("not implemented"); + } + else { + topics.push(this.#abiCoder.encode([param.type], [value])); + } + } + else { + dataTypes.push(param); + dataValues.push(value); + } + }); + return { + data: this.#abiCoder.encode(dataTypes, dataValues), + topics: topics + }; + } + // Decode a filter for the event and the search criteria + decodeEventLog(eventFragment, data, topics) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (topics != null && !eventFragment.anonymous) { + const eventTopic = this.getEventTopic(eventFragment); + if (!(0, data_js_1.isHexString)(topics[0], 32) || topics[0].toLowerCase() !== eventTopic) { + logger_js_1.logger.throwArgumentError("fragment/topic mismatch", "topics[0]", topics[0]); + } + topics = topics.slice(1); + } + const indexed = []; + const nonIndexed = []; + const dynamic = []; + eventFragment.inputs.forEach((param, index) => { + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(fragments_js_1.ParamType.fromObject({ type: "bytes32", name: param.name })); + dynamic.push(true); + } + else { + indexed.push(param); + dynamic.push(false); + } + } + else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, (0, data_js_1.concat)(topics)) : null; + const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); + //const result: (Array & { [ key: string ]: any }) = [ ]; + const values = []; + const keys = []; + let nonIndexedIndex = 0, indexedIndex = 0; + eventFragment.inputs.forEach((param, index) => { + let value = null; + if (param.indexed) { + if (resultIndexed == null) { + value = new Indexed(null); + } + else if (dynamic[index]) { + value = new Indexed(resultIndexed[indexedIndex++]); + } + else { + try { + value = resultIndexed[indexedIndex++]; + } + catch (error) { + value = error; + } + } + } + else { + try { + value = resultNonIndexed[nonIndexedIndex++]; + } + catch (error) { + value = error; + } + } + values.push(value); + keys.push(param.name || null); + }); + return abstract_coder_js_1.Result.fromItems(values, keys); + } + // Given a transaction, find the matching function fragment (if any) and + // determine all its properties and call parameters + parseTransaction(tx) { + const data = logger_js_1.logger.getBytes(tx.data, "tx.data"); + const value = logger_js_1.logger.getBigInt((tx.value != null) ? tx.value : 0, "tx.value"); + const fragment = this.getFunction((0, data_js_1.hexlify)(data.slice(0, 4))); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); + return new TransactionDescription(fragment, this.getSelector(fragment), args, value); + } + // @TODO + //parseCallResult(data: BytesLike): ?? + // Given an event log, find the matching event fragment (if any) and + // determine all its properties and values + parseLog(log) { + const fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; + } + // @TODO: If anonymous, and the only method, and the input count matches, should we parse? + // Probably not, because just because it is the only event in the ABI does + // not mean we have the full ABI; maybe just a fragment? + return new LogDescription(fragment, this.getEventTopic(fragment), this.decodeEventLog(fragment, log.data, log.topics)); + } + parseError(data) { + const hexData = (0, data_js_1.hexlify)(data); + const fragment = this.getError((0, data_js_1.dataSlice)(hexData, 0, 4)); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, (0, data_js_1.dataSlice)(hexData, 4)); + return new ErrorDescription(fragment, this.getSelector(fragment), args); + } + static from(value) { + // Already an Interface, which is immutable + if (value instanceof Interface) { + return value; + } + // JSON + if (typeof (value) === "string") { + return new Interface(JSON.parse(value)); + } + // Maybe an interface from an older version, or from a symlinked copy + if (typeof (value.format) === "function") { + return new Interface(value.format(fragments_js_1.FormatType.json)); + } + // Array of fragments + return new Interface(value); + } +} +exports.Interface = Interface; +//# sourceMappingURL=interface.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/interface.js.map b/lib.commonjs/abi/interface.js.map new file mode 100644 index 000000000..f1d514109 --- /dev/null +++ b/lib.commonjs/abi/interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interface.js","sourceRoot":"","sources":["../../src.ts/abi/interface.ts"],"names":[],"mappings":";;;AAAA,8CAAyF;AACzF,iDAA8C;AAC9C,+CAAqC;AACrC,kDAA4C;AAC5C,0DAA0D;AAC1D,gDAA0C;AAE1C,iDAA2D;AAC3D,kEAAuE;AAS9D,kGATA,qCAAiB,OASA;AAAE,uFATA,0BAAM,OASA;AARlC,iDAAsI;AACtI,yCAAmC;AASnC,MAAa,cAAc;IACd,QAAQ,CAAiB;IACzB,IAAI,CAAU;IACd,SAAS,CAAU;IACnB,KAAK,CAAU;IACf,IAAI,CAAS;IAEtB,YAAY,QAAuB,EAAE,KAAa,EAAE,IAAY;QAC5D,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC1D,IAAA,gCAAgB,EAAiB,IAAI,EAAE;YACnC,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI;SACzC,CAAC,CAAC;IACP,CAAC;CACJ;AAbD,wCAaC;AAED,MAAa,sBAAsB;IACtB,QAAQ,CAAoB;IAC5B,IA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AAS,EAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAEzD,IAAI,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QAE/B,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAA,mBAAS,EAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;QAC3E,OAAO,IAAI,gBAAgB,CAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5E,CAAC;IAGD,MAAM,CAAC,IAAI,CAAC,KAA2E;QACnF,2CAA2C;QAC3C,IAAI,KAAK,YAAY,SAAS,EAAE;YAAE,OAAO,KAAK,CAAC;SAAE;QAEjD,OAAO;QACP,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;YAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAAE;QAE5E,qEAAqE;QACrE,IAAI,OAAM,CAAO,KAAM,CAAC,MAAM,CAAC,KAAK,UAAU,EAAE;YAC5C,OAAO,IAAI,SAAS,CAAO,KAAM,CAAC,MAAM,CAAC,yBAAU,CAAC,IAAI,CAAC,CAAC,CAAC;SAC9D;QAED,qBAAqB;QACrB,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,CAAC;CACJ;AArvBD,8BAqvBC"} \ No newline at end of file diff --git a/lib.commonjs/abi/typed.js b/lib.commonjs/abi/typed.js new file mode 100644 index 000000000..944a8b85b --- /dev/null +++ b/lib.commonjs/abi/typed.js @@ -0,0 +1,216 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Typed = void 0; +const properties_js_1 = require("../utils/properties.js"); +const _gaurd = {}; +function n(value, width) { + let signed = false; + if (width < 0) { + signed = true; + width *= -1; + } + // @TODO: Check range is valid for value + return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { signed, width }); +} +function b(value, size) { + // @TODO: Check range is valid for value + return new Typed(_gaurd, `bytes${(size) ? size : ""}`, value, { size }); +} +const _typedSymbol = Symbol.for("_ethers_typed"); +class Typed { + type; + value; + #options; + _typedSymbol; + constructor(gaurd, type, value, options = null) { + if (gaurd !== _gaurd) { + throw new Error("private constructor"); + } + (0, properties_js_1.defineProperties)(this, { _typedSymbol, type, value }); + this.#options = options; + // Check the value is valid + this.format(); + } + format() { + if (this.type === "array") { + throw new Error(""); + } + else if (this.type === "dynamicArray") { + throw new Error(""); + } + else if (this.type === "tuple") { + return `tuple(${this.value.map((v) => v.format()).join(",")})`; + } + return this.type; + } + defaultValue() { + return 0; + } + minValue() { + return 0; + } + maxValue() { + return 0; + } + isBigInt() { + return !!(this.type.match(/^u?int[0-9]+$/)); + } + isData() { + return (this.type.substring(0, 5) === "bytes"); + } + isString() { + return (this.type === "string"); + } + get tupleName() { + if (this.type !== "tuple") { + throw TypeError("not a tuple"); + } + return this.#options; + } + // Returns the length of this type as an array + // - `null` indicates the length is unforced, it could be dynamic + // - `-1` indicates the length is dynamic + // - any other value indicates it is a static array and is its length + get arrayLength() { + if (this.type !== "array") { + throw TypeError("not an array"); + } + if (this.#options === true) { + return -1; + } + if (this.#options === false) { + return (this.value).length; + } + return null; + } + static from(type, value) { + return new Typed(_gaurd, type, value); + } + static uint8(v) { return n(v, 8); } + static uint16(v) { return n(v, 16); } + static uint24(v) { return n(v, 24); } + static uint32(v) { return n(v, 32); } + static uint40(v) { return n(v, 40); } + static uint48(v) { return n(v, 46); } + static uint56(v) { return n(v, 56); } + static uint64(v) { return n(v, 64); } + static uint72(v) { return n(v, 72); } + static uint80(v) { return n(v, 80); } + static uint88(v) { return n(v, 88); } + static uint96(v) { return n(v, 96); } + static uint104(v) { return n(v, 104); } + static uint112(v) { return n(v, 112); } + static uint120(v) { return n(v, 120); } + static uint128(v) { return n(v, 128); } + static uint136(v) { return n(v, 136); } + static uint144(v) { return n(v, 144); } + static uint152(v) { return n(v, 152); } + static uint160(v) { return n(v, 160); } + static uint168(v) { return n(v, 168); } + static uint176(v) { return n(v, 176); } + static uint184(v) { return n(v, 184); } + static uint192(v) { return n(v, 192); } + static uint200(v) { return n(v, 200); } + static uint208(v) { return n(v, 208); } + static uint216(v) { return n(v, 216); } + static uint224(v) { return n(v, 224); } + static uint232(v) { return n(v, 232); } + static uint240(v) { return n(v, 240); } + static uint248(v) { return n(v, 248); } + static uint256(v) { return n(v, 256); } + static uint(v) { return n(v, 256); } + static int8(v) { return n(v, -8); } + static int16(v) { return n(v, -16); } + static int24(v) { return n(v, -24); } + static int32(v) { return n(v, -32); } + static int40(v) { return n(v, -40); } + static int48(v) { return n(v, -46); } + static int56(v) { return n(v, -56); } + static int64(v) { return n(v, -64); } + static int72(v) { return n(v, -72); } + static int80(v) { return n(v, -80); } + static int88(v) { return n(v, -88); } + static int96(v) { return n(v, -96); } + static int104(v) { return n(v, -104); } + static int112(v) { return n(v, -112); } + static int120(v) { return n(v, -120); } + static int128(v) { return n(v, -128); } + static int136(v) { return n(v, -136); } + static int144(v) { return n(v, -144); } + static int152(v) { return n(v, -152); } + static int160(v) { return n(v, -160); } + static int168(v) { return n(v, -168); } + static int176(v) { return n(v, -176); } + static int184(v) { return n(v, -184); } + static int192(v) { return n(v, -192); } + static int200(v) { return n(v, -200); } + static int208(v) { return n(v, -208); } + static int216(v) { return n(v, -216); } + static int224(v) { return n(v, -224); } + static int232(v) { return n(v, -232); } + static int240(v) { return n(v, -240); } + static int248(v) { return n(v, -248); } + static int256(v) { return n(v, -256); } + static int(v) { return n(v, -256); } + static bytes(v) { return b(v); } + static bytes1(v) { return b(v, 1); } + static bytes2(v) { return b(v, 2); } + static bytes3(v) { return b(v, 3); } + static bytes4(v) { return b(v, 4); } + static bytes5(v) { return b(v, 5); } + static bytes6(v) { return b(v, 6); } + static bytes7(v) { return b(v, 7); } + static bytes8(v) { return b(v, 8); } + static bytes9(v) { return b(v, 9); } + static bytes10(v) { return b(v, 10); } + static bytes11(v) { return b(v, 11); } + static bytes12(v) { return b(v, 12); } + static bytes13(v) { return b(v, 13); } + static bytes14(v) { return b(v, 14); } + static bytes15(v) { return b(v, 15); } + static bytes16(v) { return b(v, 16); } + static bytes17(v) { return b(v, 17); } + static bytes18(v) { return b(v, 18); } + static bytes19(v) { return b(v, 19); } + static bytes20(v) { return b(v, 20); } + static bytes21(v) { return b(v, 21); } + static bytes22(v) { return b(v, 22); } + static bytes23(v) { return b(v, 23); } + static bytes24(v) { return b(v, 24); } + static bytes25(v) { return b(v, 25); } + static bytes26(v) { return b(v, 26); } + static bytes27(v) { return b(v, 27); } + static bytes28(v) { return b(v, 28); } + static bytes29(v) { return b(v, 29); } + static bytes30(v) { return b(v, 30); } + static bytes31(v) { return b(v, 31); } + static bytes32(v) { return b(v, 32); } + static address(v) { return new Typed(_gaurd, "address", v); } + static bool(v) { return new Typed(_gaurd, "bool", !!v); } + static string(v) { return new Typed(_gaurd, "string", v); } + static array(v, dynamic) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "array", v, dynamic); + } + static tuple(v, name) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "tuple", v, name); + } + static overrides(v) { + return new Typed(_gaurd, "overrides", Object.assign({}, v)); + } + static isTyped(value) { + return (value && value._typedSymbol === _typedSymbol); + } + static dereference(value, type) { + if (Typed.isTyped(value)) { + if (value.type !== type) { + throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); + } + return value.value; + } + return value; + } +} +exports.Typed = Typed; +//# sourceMappingURL=typed.js.map \ No newline at end of file diff --git a/lib.commonjs/abi/typed.js.map b/lib.commonjs/abi/typed.js.map new file mode 100644 index 000000000..65df63375 --- /dev/null +++ b/lib.commonjs/abi/typed.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typed.js","sourceRoot":"","sources":["../../src.ts/abi/typed.ts"],"names":[],"mappings":";;;AAAA,0DAA0D;AAO1D,MAAM,MAAM,GAA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AC,CAAC,CAAC;IAE1E,MAAM,CAAC,KAAK,CAAC,CAAqB,EAAE,OAAwB;QACxD,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;QACvC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,CAAmD,EAAE,IAAa;QAC3E,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;QACvC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,CAAC,SAAS,CAAC,CAAsB;QACnC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,EAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IACjE,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,KAAU;QACrB,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,YAAY,KAAK,YAAY,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,CAAC,WAAW,CAAI,KAAgB,EAAE,IAAY;QAChD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACtB,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,EAAE;gBACrB,MAAM,IAAI,KAAK,CAAC,0BAA2B,IAAK,SAAU,KAAK,CAAC,IAAK,EAAE,CAAC,CAAC;aAC5E;YACD,OAAO,KAAK,CAAC,KAAK,CAAC;SACtB;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AA9MD,sBA8MC"} \ No newline at end of file diff --git a/lib.commonjs/address/address.js b/lib.commonjs/address/address.js new file mode 100644 index 000000000..a32a779b4 --- /dev/null +++ b/lib.commonjs/address/address.js @@ -0,0 +1,114 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getIcapAddress = exports.getAddress = void 0; +const keccak_js_1 = require("../crypto/keccak.js"); +const logger_js_1 = require("../utils/logger.js"); +const BN_0 = BigInt(0); +const BN_36 = BigInt(36); +function getChecksumAddress(address) { + // if (!isHexString(address, 20)) { + // logger.throwArgumentError("invalid address", "address", address); + // } + address = address.toLowerCase(); + const chars = address.substring(2).split(""); + const expanded = new Uint8Array(40); + for (let i = 0; i < 40; i++) { + expanded[i] = chars[i].charCodeAt(0); + } + const hashed = logger_js_1.logger.getBytes((0, keccak_js_1.keccak256)(expanded)); + for (let i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return "0x" + chars.join(""); +} +// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number +// Create lookup table +const ibanLookup = {}; +for (let i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); +} +for (let i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +} +// How many decimal digits can we process? (for 64-bit float, this is 15) +// i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER)); +const safeDigits = 15; +function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + "00"; + let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join(""); + // Javascript can handle integers safely up to 15 (decimal) digits + while (expanded.length >= safeDigits) { + let block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + let checksum = String(98 - (parseInt(expanded, 10) % 97)); + while (checksum.length < 2) { + checksum = "0" + checksum; + } + return checksum; +} +; +const Base36 = (function () { + ; + const result = {}; + for (let i = 0; i < 36; i++) { + const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; + result[key] = BigInt(i); + } + return result; +})(); +function fromBase36(value) { + value = value.toLowerCase(); + let result = BN_0; + for (let i = 0; i < value.length; i++) { + result = result * BN_36 + Base36[value[i]]; + } + return result; +} +function getAddress(address) { + if (typeof (address) !== "string") { + logger_js_1.logger.throwArgumentError("invalid address", "address", address); + } + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + // Missing the 0x prefix + if (address.substring(0, 2) !== "0x") { + address = "0x" + address; + } + const result = getChecksumAddress(address); + // It is a checksummed address with a bad checksum + if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { + logger_js_1.logger.throwArgumentError("bad address checksum", "address", address); + } + return result; + } + // Maybe ICAP? (we only support direct mode) + if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + // It is an ICAP address with a bad checksum + if (address.substring(2, 4) !== ibanChecksum(address)) { + logger_js_1.logger.throwArgumentError("bad icap checksum", "address", address); + } + let result = fromBase36(address.substring(4)).toString(16); + while (result.length < 40) { + result = "0" + result; + } + return getChecksumAddress("0x" + result); + } + return logger_js_1.logger.throwArgumentError("invalid address", "address", address); +} +exports.getAddress = getAddress; +function getIcapAddress(address) { + //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase(); + let base36 = BigInt(getAddress(address)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = "0" + base36; + } + return "XE" + ibanChecksum("XE00" + base36) + base36; +} +exports.getIcapAddress = getIcapAddress; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/lib.commonjs/address/address.js.map b/lib.commonjs/address/address.js.map new file mode 100644 index 000000000..23f26ccae --- /dev/null +++ b/lib.commonjs/address/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../src.ts/address/address.ts"],"names":[],"mappings":";;;AAAA,mDAAgD;AAChD,kDAA4C;AAG5C,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzB,SAAS,kBAAkB,CAAC,OAAe;IAC3C,sCAAsC;IACtC,2EAA2E;IAC3E,OAAO;I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onjs/address/checks.js new file mode 100644 index 000000000..a22315f58 --- /dev/null +++ b/lib.commonjs/address/checks.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveAddress = exports.isAddress = exports.isAddressable = void 0; +const logger_js_1 = require("../utils/logger.js"); +const address_js_1 = require("./address.js"); +function isAddressable(value) { + return (value && typeof (value.getAddress) === "function"); +} +exports.isAddressable = isAddressable; +function isAddress(value) { + try { + (0, address_js_1.getAddress)(value); + return true; + } + catch (error) { } + return false; +} +exports.isAddress = isAddress; +async function checkAddress(target, promise) { + const result = await promise; + if (result == null || result === "0x0000000000000000000000000000000000000000") { + if (typeof (target) === "string") { + return logger_js_1.logger.throwError("unconfigured name", "UNCONFIGURED_NAME", { value: target }); + } + return logger_js_1.logger.throwArgumentError("invalid AddressLike value; did not resolve to a value address", "target", target); + } + return (0, address_js_1.getAddress)(result); +} +// Resolves an Ethereum address, ENS name or Addressable object, +// throwing if the result is null. +function resolveAddress(target, resolver) { + if (typeof (target) === "string") { + if (target.match(/^0x[0-9a-f]{40}$/i)) { + return (0, address_js_1.getAddress)(target); + } + if (resolver == null) { + return logger_js_1.logger.throwError("ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + }); + } + return checkAddress(target, resolver.resolveName(target)); + } + else if (isAddressable(target)) { + return checkAddress(target, target.getAddress()); + } + else if (typeof (target.then) === "function") { + return checkAddress(target, target); + } + return logger_js_1.logger.throwArgumentError("unsupported addressable value", "target", target); +} +exports.resolveAddress = resolveAddress; +//# sourceMappingURL=checks.js.map \ No newline at end of file diff --git a/lib.commonjs/address/checks.js.map b/lib.commonjs/address/checks.js.map new file mode 100644 index 000000000..344337728 --- /dev/null +++ b/lib.commonjs/address/checks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"checks.js","sourceRoot":"","sources":["../../src.ts/address/checks.ts"],"names":[],"mappings":";;;AAAA,kDAA4C;AAE5C,6CAA0C;AAK1C,SAAgB,aAAa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AQ,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;KAE7D;SAAM,IAAI,aAAa,CAAC,MAAM,CAAC,EAAE;QAC9B,OAAO,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;KAEpD;SAAM,IAAI,OAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,UAAU,EAAE;QAC3C,OAAO,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KACvC;IAED,OAAO,kBAAM,CAAC,kBAAkB,CAAC,+BAA+B,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACxF,CAAC;AArBD,wCAqBC"} \ No newline at end of file diff --git a/lib.commonjs/address/contract-address.js b/lib.commonjs/address/contract-address.js new file mode 100644 index 000000000..7e72dc8bd --- /dev/null +++ b/lib.commonjs/address/contract-address.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getCreate2Address = exports.getCreateAddress = void 0; +const keccak_js_1 = require("../crypto/keccak.js"); +const index_js_1 = require("../utils/index.js"); +const address_js_1 = require("./address.js"); +// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed +function getCreateAddress(tx) { + const from = (0, address_js_1.getAddress)(tx.from); + const nonce = index_js_1.logger.getBigInt(tx.nonce, "tx.nonce"); + let nonceHex = nonce.toString(16); + if (nonceHex === "0") { + nonceHex = "0x"; + } + else if (nonceHex.length % 2) { + nonceHex = "0x0" + nonceHex; + } + else { + nonceHex = "0x" + nonceHex; + } + return (0, address_js_1.getAddress)((0, index_js_1.dataSlice)((0, keccak_js_1.keccak256)((0, index_js_1.encodeRlp)([from, nonceHex])), 12)); +} +exports.getCreateAddress = getCreateAddress; +function getCreate2Address(_from, _salt, _initCodeHash) { + const from = (0, address_js_1.getAddress)(_from); + const salt = index_js_1.logger.getBytes(_salt, "salt"); + const initCodeHash = index_js_1.logger.getBytes(_initCodeHash, "initCodeHash"); + if (salt.length !== 32) { + index_js_1.logger.throwArgumentError("salt must be 32 bytes", "salt", _salt); + } + if (initCodeHash.length !== 32) { + index_js_1.logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); + } + return (0, address_js_1.getAddress)((0, index_js_1.dataSlice)((0, keccak_js_1.keccak256)((0, index_js_1.concat)(["0xff", from, salt, initCodeHash])), 12)); +} +exports.getCreate2Address = getCreate2Address; +//# sourceMappingURL=contract-address.js.map \ No newline at end of file diff --git a/lib.commonjs/address/contract-address.js.map b/lib.commonjs/address/contract-address.js.map new file mode 100644 index 000000000..628fbb45c --- /dev/null +++ b/lib.commonjs/address/contract-address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract-address.js","sourceRoot":"","sources":["../../src.ts/address/contract-address.ts"],"names":[],"mappings":";;;AAAA,mDAAgD;AAChD,gDAAyE;AAEzE,6CAA0C;AAK1C,sGAAsG;AACtG,SAAgB,gBAAgB,CAAC,EAAyC;IACtE,MAAM,IAAI,GAAG,IAAA,uBAAU,EAAC,EAAE,CAAC,IAAI,CAAC,CAAC;IACjC,MAAM,KAAK,GAAG,iBAAM,CAAC,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAErD,IAAI,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAClC,IAAI,QAAQ,KAAK,GAAG,EAAE;QAClB,QAAQ,GAAG,IAAI,CAAC;KACnB;SAAM,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,QAAQ,GAAG,KAAK,GAAG,QAAQ,CAAC;KAC/B;SAAM;QACH,QAAQ,GAAG,IAAI,GAAG,QAAQ,CAAC;KAC9B;IAED,OAAO,IAAA,uBAAU,EAAC,IAAA,oBAAS,EAAC,IAAA,qBAAS,EAAC,IAAA,oBAAS,EAAC,CAAE,IAAI,EAAE,QAAQ,CAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC/E,CAAC;AAdD,4CAcC;AAED,SAAgB,iBAAiB,CAAC,KAAa,EAAE,KAAgB,EAAE,aAAwB;IACvF,MAAM,IAAI,GAAG,IAAA,uBAAU,EAAC,KAAK,CAAC,CAAC;IAC/B,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,MAAM,YAAY,GAAG,iBAAM,CAAC,QAAQ,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;IAEpE,IAAI,IAAI,CAAC,MAAM,KAAK,EAAE,EAAE;QACpB,iBAAM,CAAC,kBAAkB,CAAC,uBAAuB,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;KACrE;IAED,IAAI,YAAY,CAAC,MAAM,KAAK,EAAE,EAAE;QAC5B,iBAAM,CAAC,kBAAkB,CAAC,+BAA+B,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC;KAC7F;IAED,OAAO,IAAA,uBAAU,EAAC,IAAA,oBAAS,EAAC,IAAA,qBAAS,EAAC,IAAA,iBAAM,EAAC,CAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,YAAY,CAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAC7F,CAAC;AAdD,8CAcC"} \ No newline at end of file diff --git a/lib.commonjs/address/index.js b/lib.commonjs/address/index.js new file mode 100644 index 000000000..27947c274 --- /dev/null +++ b/lib.commonjs/address/index.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveAddress = exports.isAddress = exports.isAddressable = exports.getCreate2Address = exports.getCreateAddress = exports.getIcapAddress = exports.getAddress = void 0; +var address_js_1 = require("./address.js"); +Object.defineProperty(exports, "getAddress", { enumerable: true, get: function () { return address_js_1.getAddress; } }); +Object.defineProperty(exports, "getIcapAddress", { enumerable: true, get: function () { return address_js_1.getIcapAddress; } }); +var contract_address_js_1 = require("./contract-address.js"); +Object.defineProperty(exports, "getCreateAddress", { enumerable: true, get: function () { return contract_address_js_1.getCreateAddress; } }); +Object.defineProperty(exports, "getCreate2Address", { enumerable: true, get: function () { return contract_address_js_1.getCreate2Address; } }); +var checks_js_1 = require("./checks.js"); +Object.defineProperty(exports, "isAddressable", { enumerable: true, get: function () { return checks_js_1.isAddressable; } }); +Object.defineProperty(exports, "isAddress", { enumerable: true, get: function () { return checks_js_1.isAddress; } }); +Object.defineProperty(exports, "resolveAddress", { enumerable: true, get: function () { return checks_js_1.resolveAddress; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/address/index.js.map b/lib.commonjs/address/index.js.map new file mode 100644 index 000000000..b4c09a669 --- /dev/null +++ b/lib.commonjs/address/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/address/index.ts"],"names":[],"mappings":";;;AAUA,2CAA0D;AAAjD,wGAAA,UAAU,OAAA;AAAE,4GAAA,cAAc,OAAA;AAEnC,6DAA4E;AAAnE,uHAAA,gBAAgB,OAAA;AAAE,wHAAA,iBAAiB,OAAA;AAG5C,yCAAuE;AAA9D,0GAAA,aAAa,OAAA;AAAE,sGAAA,SAAS,OAAA;AAAE,2GAAA,cAAc,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/constants/addresses.js b/lib.commonjs/constants/addresses.js new file mode 100644 index 000000000..148faee07 --- /dev/null +++ b/lib.commonjs/constants/addresses.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ZeroAddress = void 0; +/** + * A constant for the zero address. + */ +exports.ZeroAddress = "0x0000000000000000000000000000000000000000"; +//# sourceMappingURL=addresses.js.map \ No newline at end of file diff --git a/lib.commonjs/constants/addresses.js.map b/lib.commonjs/constants/addresses.js.map new file mode 100644 index 000000000..b0960711a --- /dev/null +++ b/lib.commonjs/constants/addresses.js.map @@ -0,0 +1 @@ +{"version":3,"file":"addresses.js","sourceRoot":"","sources":["../../src.ts/constants/addresses.ts"],"names":[],"mappings":";;;AACA;;GAEG;AACU,QAAA,WAAW,GAAG,4CAA4C,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/constants/hashes.js b/lib.commonjs/constants/hashes.js new file mode 100644 index 000000000..aa102b11c --- /dev/null +++ b/lib.commonjs/constants/hashes.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ZeroHash = void 0; +/** + * A constant for the zero hash. + */ +exports.ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; +//# sourceMappingURL=hashes.js.map \ No newline at end of file diff --git a/lib.commonjs/constants/hashes.js.map b/lib.commonjs/constants/hashes.js.map new file mode 100644 index 000000000..3d479e0b9 --- /dev/null +++ b/lib.commonjs/constants/hashes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hashes.js","sourceRoot":"","sources":["../../src.ts/constants/hashes.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,QAAQ,GAAG,oEAAoE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/constants/index.js b/lib.commonjs/constants/index.js new file mode 100644 index 000000000..4ff592898 --- /dev/null +++ b/lib.commonjs/constants/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessagePrefix = exports.EtherSymbol = exports.MaxInt256 = exports.MinInt256 = exports.MaxUint256 = exports.WeiPerEther = exports.N = exports.Two = exports.One = exports.Zero = exports.NegativeOne = exports.ZeroHash = exports.ZeroAddress = void 0; +var addresses_js_1 = require("./addresses.js"); +Object.defineProperty(exports, "ZeroAddress", { enumerable: true, get: function () { return addresses_js_1.ZeroAddress; } }); +var hashes_js_1 = require("./hashes.js"); +Object.defineProperty(exports, "ZeroHash", { enumerable: true, get: function () { return hashes_js_1.ZeroHash; } }); +var numbers_js_1 = require("./numbers.js"); +Object.defineProperty(exports, "NegativeOne", { enumerable: true, get: function () { return numbers_js_1.NegativeOne; } }); +Object.defineProperty(exports, "Zero", { enumerable: true, get: function () { return numbers_js_1.Zero; } }); +Object.defineProperty(exports, "One", { enumerable: true, get: function () { return numbers_js_1.One; } }); +Object.defineProperty(exports, "Two", { enumerable: true, get: function () { return numbers_js_1.Two; } }); +Object.defineProperty(exports, "N", { enumerable: true, get: function () { return numbers_js_1.N; } }); +Object.defineProperty(exports, "WeiPerEther", { enumerable: true, get: function () { return numbers_js_1.WeiPerEther; } }); +Object.defineProperty(exports, "MaxUint256", { enumerable: true, get: function () { return numbers_js_1.MaxUint256; } }); +Object.defineProperty(exports, "MinInt256", { enumerable: true, get: function () { return numbers_js_1.MinInt256; } }); +Object.defineProperty(exports, "MaxInt256", { enumerable: true, get: function () { return numbers_js_1.MaxInt256; } }); +var strings_js_1 = require("./strings.js"); +Object.defineProperty(exports, "EtherSymbol", { enumerable: true, get: function () { return strings_js_1.EtherSymbol; } }); +Object.defineProperty(exports, "MessagePrefix", { enumerable: true, get: function () { return strings_js_1.MessagePrefix; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/constants/index.js.map b/lib.commonjs/constants/index.js.map new file mode 100644 index 000000000..fee2ef10c --- /dev/null +++ b/lib.commonjs/constants/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/constants/index.ts"],"names":[],"mappings":";;;AAAA,+CAA6C;AAApC,2GAAA,WAAW,OAAA;AACpB,yCAAuC;AAA9B,qGAAA,QAAQ,OAAA;AACjB,2CAUsB;AATlB,yGAAA,WAAW,OAAA;AACX,kGAAA,IAAI,OAAA;AACJ,iGAAA,GAAG,OAAA;AACH,iGAAA,GAAG,OAAA;AACH,+FAAA,CAAC,OAAA;AACD,yGAAA,WAAW,OAAA;AACX,wGAAA,UAAU,OAAA;AACV,uGAAA,SAAS,OAAA;AACT,uGAAA,SAAS,OAAA;AAEb,2CAA0D;AAAjD,yGAAA,WAAW,OAAA;AAAE,2GAAA,aAAa,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/constants/numbers.js b/lib.commonjs/constants/numbers.js new file mode 100644 index 000000000..80f2cffdf --- /dev/null +++ b/lib.commonjs/constants/numbers.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MaxInt256 = exports.MinInt256 = exports.MaxUint256 = exports.WeiPerEther = exports.N = exports.Two = exports.One = exports.Zero = exports.NegativeOne = void 0; +/** + * A constant for the BigInt of -1. + */ +const NegativeOne = BigInt(-1); +exports.NegativeOne = NegativeOne; +/** + * A constant for the BigInt of 0. + */ +const Zero = BigInt(0); +exports.Zero = Zero; +/** + * A constant for the BigInt of 1. + */ +const One = BigInt(1); +exports.One = One; +/** + * A constant for the BigInt of 2. + */ +const Two = BigInt(2); +exports.Two = Two; +/** + * A constant for the order N for the secp256k1 curve. + */ +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +exports.N = N; +/** + * A constant for the number of wei in a single ether. + */ +const WeiPerEther = BigInt("1000000000000000000"); +exports.WeiPerEther = WeiPerEther; +/** + * A constant for the maximum value for a ``uint256``. + */ +const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +exports.MaxUint256 = MaxUint256; +/** + * A constant for the minimum value for an ``int256``. + */ +const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * NegativeOne; +exports.MinInt256 = MinInt256; +/** + * A constant for the maximum value for an ``int256``. + */ +const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +exports.MaxInt256 = MaxInt256; +//# sourceMappingURL=numbers.js.map \ No newline at end of file diff --git a/lib.commonjs/constants/numbers.js.map b/lib.commonjs/constants/numbers.js.map new file mode 100644 index 000000000..e5bef3d0b --- /dev/null +++ b/lib.commonjs/constants/numbers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numbers.js","sourceRoot":"","sources":["../../src.ts/constants/numbers.ts"],"names":[],"mappings":";;;AACA;;GAEG;AACH,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AA2C3B,kCAAW;AAzCf;;GAEG;AACH,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAuCnB,oBAAI;AArCR;;GAEG;AACH,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAmClB,kBAAG;AAjCP;;GAEG;AACH,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AA+BlB,kBAAG;AA7BP;;GAEG;AACH,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AA2BnF,cAAC;AAzBL;;GAEG;AACH,MAAM,WAAW,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAuB9C,kCAAW;AArBf;;GAEG;AACH,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAmB5F,gCAAU;AAjBd;;GAEG;AACH,MAAM,SAAS,GAAG,MAAM,CAAC,oEAAoE,CAAC,GAAG,WAAW,CAAC;AAezG,8BAAS;AAbb;;GAEG;AACH,MAAM,SAAS,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAW3F,8BAAS"} \ No newline at end of file diff --git a/lib.commonjs/constants/strings.js b/lib.commonjs/constants/strings.js new file mode 100644 index 000000000..0b92ee2dc --- /dev/null +++ b/lib.commonjs/constants/strings.js @@ -0,0 +1,10 @@ +"use strict"; +// NFKC (composed) // (decomposed) +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MessagePrefix = exports.EtherSymbol = void 0; +/** + * A constant for the ether symbol (normalized using NFKC). + */ +exports.EtherSymbol = "\u039e"; // "\uD835\uDF63"; +exports.MessagePrefix = "\x19Ethereum Signed Message:\n"; +//# sourceMappingURL=strings.js.map \ No newline at end of file diff --git a/lib.commonjs/constants/strings.js.map b/lib.commonjs/constants/strings.js.map new file mode 100644 index 000000000..36a8fc3ca --- /dev/null +++ b/lib.commonjs/constants/strings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.js","sourceRoot":"","sources":["../../src.ts/constants/strings.ts"],"names":[],"mappings":";AAAA,8CAA8C;;;AAE9C;;GAEG;AACU,QAAA,WAAW,GAAG,QAAQ,CAAC,CAAE,kBAAkB;AAG3C,QAAA,aAAa,GAAG,gCAAgC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/contract/contract.js b/lib.commonjs/contract/contract.js new file mode 100644 index 000000000..8f7e4eb2b --- /dev/null +++ b/lib.commonjs/contract/contract.js @@ -0,0 +1,649 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Contract = exports.BaseContract = exports.resolveArgs = exports.copyOverrides = void 0; +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../abi/index.js"); +const index_js_3 = require("../utils/index.js"); +const index_js_4 = require("../providers/index.js"); +const wrappers_js_1 = require("./wrappers.js"); +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 concisify(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +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) => { + return param.walkAsync(args[index], (type, value) => { + if (type === "address") { + return (0, index_js_1.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 _WrappedMethodBase() { + return Function; +} +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; +} +async function copyOverrides(arg) { + // Create a shallow copy (we'll deep-ify anything needed during normalizing) + const overrides = (0, index_js_4.copyRequest)(index_js_2.Typed.dereference(arg, "overrides")); + // Some sanity checking; these are what these methods adds + //if ((overrides).to) { + if (overrides.to) { + index_js_3.logger.throwArgumentError("cannot override to", "overrides.to", overrides.to); + } + else if (overrides.data) { + index_js_3.logger.throwArgumentError("cannot override data", "overrides.data", overrides.data); + } + // Resolve any from + if (overrides.from) { + overrides.from = await (0, index_js_1.resolveAddress)(overrides.from); + } + return overrides; +} +exports.copyOverrides = copyOverrides; +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) => { + if (type === "address") { + return (0, index_js_1.resolveAddress)(value, resolver); + } + return value; + }); + })); +} +exports.resolveArgs = resolveArgs; +class WrappedMethod extends _WrappedMethodBase() { + name = ""; // Investigate! + _contract; + _key; + constructor(contract, key) { + super(); + (0, index_js_3.defineProperties)(this, { + name: contract.interface.getFunctionName(key), + _contract: contract, _key: key + }); + const proxy = new Proxy(this, { + // Perform the default operation for this fragment type + apply: async (target, thisArg, args) => { + const fragment = target.getFragment(...args); + if (fragment.constant) { + return await target.staticCall(...args); + } + return await target.send(...args); + }, + }); + return proxy; + } + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + get fragment() { + return this._contract.interface.getFunction(this._key); + } + getFragment(...args) { + return this._contract.interface.getFunction(this._key, args); + } + async populateTransaction(...args) { + const fragment = this.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()); + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(this._contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await (0, index_js_3.resolveProperties)({ + to: this._contract.getAddress(), + data: this._contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + } + async staticCall(...args) { + const result = await this.staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + } + async send(...args) { + const runner = this._contract.runner; + if (!canSend(runner)) { + return index_js_3.logger.throwError("contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + } + const tx = await runner.sendTransaction(await this.populateTransaction(...args)); + const provider = getProvider(this._contract.runner); + return new wrappers_js_1.ContractTransactionResponse(this._contract.interface, provider, tx); + } + async estimateGas(...args) { + const runner = getRunner(this._contract.runner, "estimateGas"); + if (!canEstimate(runner)) { + return index_js_3.logger.throwError("contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { + operation: "estimateGas" + }); + } + return await runner.estimateGas(await this.populateTransaction(...args)); + } + async staticCallResult(...args) { + const runner = getRunner(this._contract.runner, "call"); + if (!canCall(runner)) { + return index_js_3.logger.throwError("contract runner does not support calling", "UNSUPPORTED_OPERATION", { + operation: "call" + }); + } + const fragment = this.getFragment(...args); + const tx = await this.populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } + catch (error) { + if ((0, index_js_3.isCallException)(error)) { + throw this._contract.interface.makeError(fragment, error.data, tx); + } + throw error; + } + return this._contract.interface.decodeFunctionResult(fragment, result); + } +} +function _WrappedEventBase() { + return Function; +} +class WrappedEvent extends _WrappedEventBase() { + name = ""; // @TODO: investigate + _contract; + _key; + constructor(contract, key) { + super(); + (0, index_js_3.defineProperties)(this, { + name: contract.interface.getEventName(key), + _contract: contract, _key: key + }); + return new Proxy(this, { + // Perform the default operation for this fragment type + apply: async (target, thisArg, args) => { + return new PreparedTopicFilter(contract, target.getFragment(...args), args); + }, + }); + } + // Only works on non-ambiguous keys + get fragment() { + return this._contract.interface.getEvent(this._key); + } + getFragment(...args) { + return this._contract.interface.getEvent(this._key, args); + } +} +; +// 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("_ethersInternal_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 getSubTag(contract, event) { + let fragment; + let topics; + if (Array.isArray(event)) { + // Topics; e.g. `[ "0x1234...89ab" ]` + fragment = contract.interface.getEvent(event[0]); + topics = event; + } + else if (typeof (event) === "string") { + // Event name (name or signature); `"Transfer"` + fragment = contract.interface.getEvent(event); + topics = [contract.interface.getEventTopic(fragment)]; + } + else if (isDeferred(event)) { + // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` + fragment = event.fragment; + topics = await event.getTopicFilter(); + } + else if ("fragment" in event) { + // ContractEvent; e.g. `contract.filter.Transfer` + fragment = event.fragment; + topics = [contract.interface.getEventTopic(fragment)]; + } + else { + console.log(event); + throw new Error("TODO"); + } + // Normalize topics and sort TopicSets + topics = topics.map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + 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 getSubTag(contract, event)).tag) || null; +} +async function getSub(contract, event) { + // Make sure our runner can actually subscribe to events + const provider = getProvider(contract.runner); + if (!provider) { + return index_js_3.logger.throwError("contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { + operation: "on" + }); + } + const { fragment, tag, topics } = await getSubTag(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) => { + const payload = new wrappers_js_1.ContractEventPayload(contract, null, event, fragment, log); + emit(contract, event, payload.args, payload); + }; + let started = false; + const start = () => { + if (started) { + return; + } + provider.on(filter, listener); + started = true; + }; + const stop = () => { + if (!started) { + return; + } + provider.off(filter, listener); + started = false; + }; + 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, payload) { + 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 = args.slice(); + if (payload) { + passArgs.push(new wrappers_js_1.ContractEventPayload(contract, (once ? null : listener), event, payload.fragment, payload.log)); + } + try { + listener.call(contract, ...passArgs); + } + catch (error) { } + return !once; + }); + return (count > 0); +} +async function emit(contract, event, args, payload) { + try { + await lastEmit; + } + catch (error) { } + const resultPromise = _emit(contract, event, args, payload); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +class BaseContract { + target; + interface; + runner; + filters; + [internal]; + constructor(target, abi, runner = null, _deployTx) { + const iface = index_js_2.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); + 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 index_js_3.logger.makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr) => { + if (addr == null) { + throw new Error("TODO"); + } + 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 (passProperties.indexOf(_prop) >= 0) { + return Reflect.get(target, _prop, receiver); + } + const prop = String(_prop); + const result = this.getEvent(prop); + if (result) { + return result; + } + throw new Error(`unknown contract event: ${prop}`); + } + }); + (0, index_js_3.defineProperties)(this, { filters }); + // Return a Proxy that will respond to functions + return new Proxy(this, { + get: (target, _prop, receiver) => { + if (_prop in target || passProperties.indexOf(_prop) >= 0) { + return Reflect.get(target, _prop, receiver); + } + const prop = String(_prop); + const result = target.getFunction(prop); + if (result) { + return result; + } + throw new Error(`unknown contract method: ${prop}`); + } + }); + } + async getAddress() { return await getInternal(this).addrPromise; } + async getDeployedCode() { + const provider = getProvider(this.runner); + if (!provider) { + return index_js_3.logger.throwError("runner does not support .provider", "UNSUPPORTED_OPERATION", { + operation: "getDeployedCode" + }); + } + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; + } + return code; + } + 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); + if (provider == null) { + return index_js_3.logger.throwError("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(); + }); + } + deploymentTransaction() { + return getInternal(this).deployTx; + } + getFunction(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return (new WrappedMethod(this, key)); + } + getEvent(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return (new WrappedEvent(this, key)); + } + async queryTransaction(hash) { + // Is this useful? + throw new Error("@TODO"); + } + async queryFilter(event, fromBlock = 0, toBlock = "latest") { + const { addr, addrPromise } = getInternal(this); + const address = (addr ? addr : (await addrPromise)); + const { fragment, topics } = await getSubTag(this, event); + const filter = { address, topics, fromBlock, toBlock }; + const provider = getProvider(this.runner); + if (!provider) { + return index_js_3.logger.throwError("contract runner does not have a provider", "UNSUPPORTED_OPERATION", { + operation: "queryFilter" + }); + } + return (await provider.getLogs(filter)).map((log) => { + return new wrappers_js_1.EventLog(log, this.interface, fragment); + }); + } + async on(event, listener) { + const sub = await getSub(this, event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + async once(event, listener) { + const sub = await getSub(this, event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + async emit(event, ...args) { + return await emit(this, event, args, null); + } + 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; + } + 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; + } + 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; + } + 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); + } + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null) { + super(address, abi, runner); + } + } + return CustomContract; + } + ; + static from(target, abi, runner = null) { + const contract = new this(target, abi, runner); + return contract; + } +} +exports.BaseContract = BaseContract; +function _ContractBase() { + return BaseContract; +} +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 000000000..e32aa8cdb --- /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,kDAAqD;AACrD,8CAAmD;AACnD,gDAE2B;AAC3B,oDAA8E;AAE9E,+CAIuB;AAqCvB,SAAS,OAAO,CAAC,KAAU;IACvB,OAAO,CAAC,KAAK,IAAI,OAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,UAAU,CAAC,CAAC;AACxD,CAAC;AAED,SAAS,WAAW,CAAC,KAAU;IAC3B,OAAO,CAAC,KAAK,IAAI,OAAM,CAAC,KAAK,CAAC,WAAW,CAAC,KAAK,UAAU,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,UAAU,CAAC,KAAU;IAC1B,OAAO,CAAC,KAAK,IAAI,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AwB,MAAc,EAAE,GAAiB,EAAE,SAAgC,IAAI;QACtG,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,QAAe,CAAC;IAC3B,CAAC;CACJ;AA7RD,oCA6RC;AAED,SAAS,aAAa;IAClB,OAAO,YAAmB,CAAC;AAC/B,CAAC;AAED,MAAa,QAAS,SAAQ,aAAa,EAAE;CAAI;AAAjD,4BAAiD"} \ 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 000000000..eae147d44 --- /dev/null +++ b/lib.commonjs/contract/factory.js @@ -0,0 +1,79 @@ +"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("../address/index.js"); +const index_js_3 = require("../utils/index.js"); +const contract_js_1 = require("./contract.js"); +// A = Arguments to the constructor +// I = Interface of deployed contracts +class ContractFactory { + interface; + bytecode; + runner; + 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_3.hexlify)(index_js_3.logger.getBytes(bytecode)); + } + else { + if (typeof (bytecode) === "object") { + bytecode = bytecode.object; + } + if (bytecode.substring(0, 2) !== "0x") { + bytecode = "0x" + bytecode; + } + bytecode = (0, index_js_3.hexlify)(index_js_3.logger.getBytes(bytecode)); + } + (0, index_js_3.defineProperties)(this, { + bytecode, interface: iface, runner: (runner || null) + }); + } + 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()); + } + 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_3.concat)([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); + return Object.assign({}, overrides, { data }); + } + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + if (!this.runner || typeof (this.runner.sendTransaction) !== "function") { + return index_js_3.logger.throwError("factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + } + const sentTx = await this.runner.sendTransaction(tx); + const address = (0, index_js_2.getCreateAddress)(sentTx); + return new contract_js_1.BaseContract(address, this.interface, this.runner, sentTx); + } + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); + } + static fromSolidity(output, runner) { + if (output == null) { + index_js_3.logger.throwArgumentError("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 000000000..32efc134a --- /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,kDAAuD;AACvD,gDAA8E;AAE9E,+CAAyE;AAYzE,mCAAmC;AACnC,sCAAsC;AACtC,MAAa,eAAe;IACf,SAAS,CAAa;IACtB,QAAQ,CAAU;IAClB,MAAM,CAAyB;IAExC,YAAY,GAA6B,EAAE,QAAwC,EAAE,MAA8B;QAC/G,MAAM,KAAK,GAAG,oBAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAElC,wEAAwE;QACxE,IAAI,QAAQ,YAAY,UAAU,EAAE;YAChC,QAAQ,GAAG,IAAA,kBAAO,EAAC,iBAAM,CAAC,QAAQ,CAAC,QAAQ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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;AA7ED,0CA6EC"} \ No newline at end of file diff --git a/lib.commonjs/contract/index.js b/lib.commonjs/contract/index.js new file mode 100644 index 000000000..a9a4197b7 --- /dev/null +++ b/lib.commonjs/contract/index.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventLog = exports.ContractTransactionResponse = exports.ContractTransactionReceipt = exports.ContractEventPayload = exports.ContractFactory = exports.Contract = exports.BaseContract = void 0; +var contract_js_1 = require("./contract.js"); +Object.defineProperty(exports, "BaseContract", { enumerable: true, get: function () { return contract_js_1.BaseContract; } }); +Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return contract_js_1.Contract; } }); +var factory_js_1 = require("./factory.js"); +Object.defineProperty(exports, "ContractFactory", { enumerable: true, get: function () { return factory_js_1.ContractFactory; } }); +var wrappers_js_1 = require("./wrappers.js"); +Object.defineProperty(exports, "ContractEventPayload", { enumerable: true, get: function () { return wrappers_js_1.ContractEventPayload; } }); +Object.defineProperty(exports, "ContractTransactionReceipt", { enumerable: true, get: function () { return wrappers_js_1.ContractTransactionReceipt; } }); +Object.defineProperty(exports, "ContractTransactionResponse", { enumerable: true, get: function () { return wrappers_js_1.ContractTransactionResponse; } }); +Object.defineProperty(exports, "EventLog", { enumerable: true, get: function () { return wrappers_js_1.EventLog; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/contract/index.js.map b/lib.commonjs/contract/index.js.map new file mode 100644 index 000000000..d2a7812d1 --- /dev/null +++ b/lib.commonjs/contract/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/contract/index.ts"],"names":[],"mappings":";;;AACA,6CAEuB;AADnB,2GAAA,YAAY,OAAA;AAAE,uGAAA,QAAQ,OAAA;AAG1B,2CAEsB;AADlB,6GAAA,eAAe,OAAA;AAGnB,6CAGuB;AAFnB,mHAAA,oBAAoB,OAAA;AAAE,yHAAA,0BAA0B,OAAA;AAAE,0HAAA,2BAA2B,OAAA;AAC7E,uGAAA,QAAQ,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/contract/types.js b/lib.commonjs/contract/types.js new file mode 100644 index 000000000..c1325264f --- /dev/null +++ b/lib.commonjs/contract/types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +; +; +; +//# sourceMappingURL=types.js.map \ 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 000000000..8429d5ddd --- /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":";;AAeC,CAAC;AAiBqE,CAAC;AAkDvE,CAAC"} \ 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 000000000..8e1ee858e --- /dev/null +++ b/lib.commonjs/contract/wrappers.js @@ -0,0 +1,80 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractEventPayload = exports.ContractTransactionResponse = exports.ContractTransactionReceipt = exports.EventLog = void 0; +const index_js_1 = require("../providers/index.js"); +const index_js_2 = require("../utils/index.js"); +class EventLog extends index_js_1.Log { + interface; + fragment; + args; + constructor(log, iface, fragment) { + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + (0, index_js_2.defineProperties)(this, { args, fragment, interface: iface }); + } + get eventName() { return this.fragment.name; } + get eventSignature() { return this.fragment.format(); } +} +exports.EventLog = EventLog; +class ContractTransactionReceipt extends index_js_1.TransactionReceipt { + #interface; + constructor(iface, provider, tx) { + super(tx, provider); + this.#interface = iface; + } + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? this.#interface.getEvent(log.topics[0]) : null; + if (fragment) { + return new EventLog(log, this.#interface, fragment); + } + else { + return log; + } + }); + } +} +exports.ContractTransactionReceipt = ContractTransactionReceipt; +class ContractTransactionResponse extends index_js_1.TransactionResponse { + #interface; + constructor(iface, provider, tx) { + super(tx, provider); + this.#interface = iface; + } + async wait(confirms) { + const receipt = await super.wait(); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(this.#interface, this.provider, receipt); + } +} +exports.ContractTransactionResponse = ContractTransactionResponse; +class ContractEventPayload extends index_js_2.EventPayload { + fragment; + log; + args; + constructor(contract, listener, filter, fragment, _log) { + super(contract, listener, filter); + const log = new EventLog(_log, contract.interface, fragment); + const args = contract.interface.decodeEventLog(fragment, log.data, log.topics); + (0, index_js_2.defineProperties)(this, { args, fragment, log }); + } + get eventName() { + return this.fragment.name; + } + get eventSignature() { + return this.fragment.format(); + } + async getBlock() { + return await this.log.getBlock(); + } + async getTransaction() { + return await this.log.getTransaction(); + } + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); + } +} +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 000000000..4fb24f990 --- /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,oDAE+B;AAC/B,gDAAmE;AAYnE,MAAa,QAAS,SAAQ,cAAG;IACpB,SAAS,CAAa;IACtB,QAAQ,CAAiB;IACzB,IAAI,CAAU;IAEvB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,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,cAAc;QAChB,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,qBAAqB,EAAE,CAAC;IAClD,CAAC;CACJ;AAhCD,oDAgCC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/crypto-browser.js b/lib.commonjs/crypto/crypto-browser.js new file mode 100644 index 000000000..80c2a2599 --- /dev/null +++ b/lib.commonjs/crypto/crypto-browser.js @@ -0,0 +1,63 @@ +"use strict"; +/* Browser Crypto Shims */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.pbkdf2Sync = exports.createHmac = exports.createHash = void 0; +const hmac_1 = require("@noble/hashes/hmac"); +const pbkdf2_1 = require("@noble/hashes/pbkdf2"); +const sha256_1 = require("@noble/hashes/sha256"); +const sha512_1 = require("@noble/hashes/sha512"); +const logger_js_1 = require("../utils/logger.js"); +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const anyGlobal = getGlobal(); +const crypto = anyGlobal.crypto || anyGlobal.msCrypto; +function createHash(algo) { + switch (algo) { + case "sha256": return sha256_1.sha256.create(); + case "sha512": return sha512_1.sha512.create(); + } + return logger_js_1.logger.throwArgumentError("invalid hashing algorithm name", "algorithm", algo); +} +exports.createHash = createHash; +function createHmac(_algo, key) { + const algo = ({ sha256: sha256_1.sha256, sha512: sha512_1.sha512 }[_algo]); + if (algo == null) { + return logger_js_1.logger.throwArgumentError("invalid hmac algorithm", "algorithm", _algo); + } + return hmac_1.hmac.create(algo, key); +} +exports.createHmac = createHmac; +function pbkdf2Sync(password, salt, iterations, keylen, _algo) { + const algo = ({ sha256: sha256_1.sha256, sha512: sha512_1.sha512 }[_algo]); + if (algo == null) { + return logger_js_1.logger.throwArgumentError("invalid pbkdf2 algorithm", "algorithm", _algo); + } + return (0, pbkdf2_1.pbkdf2)(algo, password, salt, { c: iterations, dkLen: keylen }); +} +exports.pbkdf2Sync = pbkdf2Sync; +function randomBytes(length) { + if (crypto == null) { + return logger_js_1.logger.throwError("platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { + operation: "randomBytes" + }); + } + if (!Number.isInteger(length) || length <= 0 || length > 1024) { + logger_js_1.logger.throwArgumentError("invalid length", "length", length); + } + const result = new Uint8Array(length); + crypto.getRandomValues(result); + return result; +} +exports.randomBytes = randomBytes; +//# sourceMappingURL=crypto-browser.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/crypto-browser.js.map b/lib.commonjs/crypto/crypto-browser.js.map new file mode 100644 index 000000000..33a8c1e33 --- /dev/null +++ b/lib.commonjs/crypto/crypto-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto-browser.js","sourceRoot":"","sources":["../../src.ts/crypto/crypto-browser.ts"],"names":[],"mappings":";AAAA,0BAA0B;;;AAE1B,6CAA0C;AAC1C,iDAA8C;AAC9C,iDAA8C;AAC9C,iDAA8C;AAE9C,kDAA4C;AAW5C,SAAS,SAAS;IAChB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IACjD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAAE,OAAO,MAAM,CAAC;KAAE;IACrD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAAE,OAAO,MAAM,CAAC;KAAE;IACrD,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,CAAC;AAAA,CAAC;AAEF,MAAM,SAAS,GAAG,SAAS,EAAE,CAAC;AAC9B,MAAM,MAAM,GAAQ,SAAS,CAAC,MAAM,IAAI,SAAS,CAAC,QAAQ,CAAC;AAQ3D,SAAgB,UAAU,C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,CAAC,iDAAiD,EAAE,uBAAuB,EAAE;YACjG,SAAS,EAAE,aAAa;SAC3B,CAAC,CAAC;KACN;IAED,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,GAAG,IAAI,EAAE;QAC3D,kBAAM,CAAC,kBAAkB,CAAC,gBAAgB,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;KACjE;IAED,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACtC,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC;AAClB,CAAC;AAdD,kCAcC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/crypto.js b/lib.commonjs/crypto/crypto.js new file mode 100644 index 000000000..31e54d522 --- /dev/null +++ b/lib.commonjs/crypto/crypto.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.pbkdf2Sync = exports.createHmac = exports.createHash = void 0; +var crypto_1 = require("crypto"); +Object.defineProperty(exports, "createHash", { enumerable: true, get: function () { return crypto_1.createHash; } }); +Object.defineProperty(exports, "createHmac", { enumerable: true, get: function () { return crypto_1.createHmac; } }); +Object.defineProperty(exports, "pbkdf2Sync", { enumerable: true, get: function () { return crypto_1.pbkdf2Sync; } }); +Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function () { return crypto_1.randomBytes; } }); +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/crypto.js.map b/lib.commonjs/crypto/crypto.js.map new file mode 100644 index 000000000..5978cca69 --- /dev/null +++ b/lib.commonjs/crypto/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src.ts/crypto/crypto.ts"],"names":[],"mappings":";;;AACA,iCAEgB;AADZ,oGAAA,UAAU,OAAA;AAAE,oGAAA,UAAU,OAAA;AAAE,oGAAA,UAAU,OAAA;AAAE,qGAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/crypto/hmac.js b/lib.commonjs/crypto/hmac.js new file mode 100644 index 000000000..8436073db --- /dev/null +++ b/lib.commonjs/crypto/hmac.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.computeHmac = void 0; +const crypto_js_1 = require("./crypto.js"); +const index_js_1 = require("../utils/index.js"); +let locked = false; +const _computeHmac = function (algorithm, key, data) { + return "0x" + (0, crypto_js_1.createHmac)(algorithm, key).update(data).digest("hex"); +}; +let __computeHmac = _computeHmac; +function computeHmac(algorithm, _key, _data) { + const key = index_js_1.logger.getBytes(_key, "key"); + const data = index_js_1.logger.getBytes(_data, "data"); + return (0, index_js_1.hexlify)(__computeHmac(algorithm, key, data)); +} +exports.computeHmac = computeHmac; +computeHmac._ = _computeHmac; +computeHmac.lock = function () { locked = true; }; +computeHmac.register = function (func) { + if (locked) { + throw new Error("computeHmac is locked"); + } + __computeHmac = func; +}; +Object.freeze(computeHmac); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/hmac.js.map b/lib.commonjs/crypto/hmac.js.map new file mode 100644 index 000000000..0df1df4be --- /dev/null +++ b/lib.commonjs/crypto/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../../src.ts/crypto/hmac.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AACzC,gDAAoD;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,YAAY,GAAG,UAAS,SAA8B,EAAE,GAAe,EAAE,IAAgB;IAC3F,OAAO,IAAI,GAAG,IAAA,sBAAU,EAAC,SAAS,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACxE,CAAC,CAAA;AAED,IAAI,aAAa,GAAG,YAAY,CAAC;AAEjC,SAAgB,WAAW,CAAC,SAA8B,EAAE,IAAe,EAAE,KAAgB;IACzF,MAAM,GAAG,GAAG,iBAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACzC,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAO,EAAC,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAJD,kCAIC;AACD,WAAW,CAAC,CAAC,GAAG,YAAY,CAAC;AAC7B,WAAW,CAAC,IAAI,GAAI,cAAa,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACjD,WAAW,CAAC,QAAQ,GAAG,UAAS,IAAsF;IAClH,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;KAAE;IACzD,aAAa,GAAG,IAAI,CAAC;AACzB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/index.js b/lib.commonjs/crypto/index.js new file mode 100644 index 000000000..2000645b6 --- /dev/null +++ b/lib.commonjs/crypto/index.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lock = exports.Signature = exports.SigningKey = exports.scryptSync = exports.scrypt = exports.pbkdf2 = exports.sha512 = exports.sha256 = exports.ripemd160 = exports.keccak256 = exports.randomBytes = exports.computeHmac = void 0; +// We import all these so we can export lock() +const hmac_js_1 = require("./hmac.js"); +Object.defineProperty(exports, "computeHmac", { enumerable: true, get: function () { return hmac_js_1.computeHmac; } }); +const keccak_js_1 = require("./keccak.js"); +Object.defineProperty(exports, "keccak256", { enumerable: true, get: function () { return keccak_js_1.keccak256; } }); +const ripemd160_js_1 = require("./ripemd160.js"); +Object.defineProperty(exports, "ripemd160", { enumerable: true, get: function () { return ripemd160_js_1.ripemd160; } }); +const pbkdf2_js_1 = require("./pbkdf2.js"); +Object.defineProperty(exports, "pbkdf2", { enumerable: true, get: function () { return pbkdf2_js_1.pbkdf2; } }); +const random_js_1 = require("./random.js"); +Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function () { return random_js_1.randomBytes; } }); +const scrypt_js_1 = require("./scrypt.js"); +Object.defineProperty(exports, "scrypt", { enumerable: true, get: function () { return scrypt_js_1.scrypt; } }); +Object.defineProperty(exports, "scryptSync", { enumerable: true, get: function () { return scrypt_js_1.scryptSync; } }); +const sha2_js_1 = require("./sha2.js"); +Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return sha2_js_1.sha256; } }); +Object.defineProperty(exports, "sha512", { enumerable: true, get: function () { return sha2_js_1.sha512; } }); +var signing_key_js_1 = require("./signing-key.js"); +Object.defineProperty(exports, "SigningKey", { enumerable: true, get: function () { return signing_key_js_1.SigningKey; } }); +var signature_js_1 = require("./signature.js"); +Object.defineProperty(exports, "Signature", { enumerable: true, get: function () { return signature_js_1.Signature; } }); +function lock() { + hmac_js_1.computeHmac.lock(); + keccak_js_1.keccak256.lock(); + pbkdf2_js_1.pbkdf2.lock(); + random_js_1.randomBytes.lock(); + ripemd160_js_1.ripemd160.lock(); + scrypt_js_1.scrypt.lock(); + scrypt_js_1.scryptSync.lock(); + sha2_js_1.sha256.lock(); + sha2_js_1.sha512.lock(); +} +exports.lock = lock; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/index.js.map b/lib.commonjs/crypto/index.js.map new file mode 100644 index 000000000..4f47df95a --- /dev/null +++ b/lib.commonjs/crypto/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/crypto/index.ts"],"names":[],"mappings":";;;AAAA,8CAA8C;AAC9C,uCAAwC;AASpC,4FATK,qBAAW,OASL;AARf,2CAAwC;AAYpC,0FAZK,qBAAS,OAYL;AAXb,iDAA2C;AAYvC,0FAZK,wBAAS,OAYL;AAXb,2CAAqC;AAcjC,uFAdK,kBAAM,OAcL;AAbV,2CAA0C;AAOtC,4FAPK,uBAAW,OAOL;AANf,2CAAiD;AAa7C,uFAbK,kBAAM,OAaL;AAAE,2FAbK,sBAAU,OAaL;AAZtB,uCAA2C;AASvC,uFATK,gBAAM,OASL;AAAE,uFATK,gBAAM,OASL;AAMlB,mDAA8C;AAArC,4GAAA,UAAU,OAAA;AACnB,+CAA2C;AAAlC,yGAAA,SAAS,OAAA;AAElB,SAAS,IAAI;IACT,qBAAW,CAAC,IAAI,EAAE,CAAC;IACnB,qBAAS,CAAC,IAAI,EAAE,CAAC;IACjB,kBAAM,CAAC,IAAI,EAAE,CAAC;IACd,uBAAW,CAAC,IAAI,EAAE,CAAC;IACnB,wBAAS,CAAC,IAAI,EAAE,CAAC;IACjB,kBAAM,CAAC,IAAI,EAAE,CAAC;IACd,sBAAU,CAAC,IAAI,EAAE,CAAC;IAClB,gBAAM,CAAC,IAAI,EAAE,CAAC;IACd,gBAAM,CAAC,IAAI,EAAE,CAAC;AAClB,CAAC;AAEQ,oBAAI"} \ No newline at end of file diff --git a/lib.commonjs/crypto/keccak.js b/lib.commonjs/crypto/keccak.js new file mode 100644 index 000000000..e6245a271 --- /dev/null +++ b/lib.commonjs/crypto/keccak.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.keccak256 = void 0; +const sha3_1 = require("@noble/hashes/sha3"); +const index_js_1 = require("../utils/index.js"); +let locked = false; +const _keccak256 = function (data) { + return (0, sha3_1.keccak_256)(data); +}; +let __keccak256 = _keccak256; +function keccak256(_data) { + const data = index_js_1.logger.getBytes(_data, "data"); + return (0, index_js_1.hexlify)(__keccak256(data)); +} +exports.keccak256 = keccak256; +keccak256._ = _keccak256; +keccak256.lock = function () { locked = true; }; +keccak256.register = function (func) { + if (locked) { + throw new TypeError("keccak256 is locked"); + } + __keccak256 = func; +}; +Object.freeze(keccak256); +//# sourceMappingURL=keccak.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/keccak.js.map b/lib.commonjs/crypto/keccak.js.map new file mode 100644 index 000000000..03cba5ef0 --- /dev/null +++ b/lib.commonjs/crypto/keccak.js.map @@ -0,0 +1 @@ +{"version":3,"file":"keccak.js","sourceRoot":"","sources":["../../src.ts/crypto/keccak.ts"],"names":[],"mappings":";;;AAAA,6CAAgD;AAEhD,gDAAoD;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,UAAU,GAAG,UAAS,IAAgB;IACxC,OAAO,IAAA,iBAAU,EAAC,IAAI,CAAC,CAAC;AAC5B,CAAC,CAAA;AAED,IAAI,WAAW,GAAoC,UAAU,CAAC;AAE9D,SAAgB,SAAS,CAAC,KAAgB;IACtC,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAO,EAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AAHD,8BAGC;AACD,SAAS,CAAC,CAAC,GAAG,UAAU,CAAC;AACzB,SAAS,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,SAAS,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC/D,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;KAAE;IAC3D,WAAW,GAAG,IAAI,CAAC;AACvB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/pbkdf2.js b/lib.commonjs/crypto/pbkdf2.js new file mode 100644 index 000000000..bb9456e3e --- /dev/null +++ b/lib.commonjs/crypto/pbkdf2.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pbkdf2 = void 0; +const crypto_js_1 = require("./crypto.js"); +const index_js_1 = require("../utils/index.js"); +let locked = false; +const _pbkdf2 = function (password, salt, iterations, keylen, algo) { + return (0, crypto_js_1.pbkdf2Sync)(password, salt, iterations, keylen, algo); +}; +let __pbkdf2 = _pbkdf2; +function pbkdf2(_password, _salt, iterations, keylen, algo) { + const password = index_js_1.logger.getBytes(_password, "password"); + const salt = index_js_1.logger.getBytes(_salt, "salt"); + return (0, index_js_1.hexlify)(__pbkdf2(password, salt, iterations, keylen, algo)); +} +exports.pbkdf2 = pbkdf2; +pbkdf2._ = _pbkdf2; +pbkdf2.lock = function () { locked = true; }; +pbkdf2.register = function (func) { + if (locked) { + throw new Error("pbkdf2 is locked"); + } + __pbkdf2 = func; +}; +Object.freeze(pbkdf2); +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/pbkdf2.js.map b/lib.commonjs/crypto/pbkdf2.js.map new file mode 100644 index 000000000..6ee06854d --- /dev/null +++ b/lib.commonjs/crypto/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../../src.ts/crypto/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAEzC,gDAAoD;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,OAAO,GAAG,UAAS,QAAoB,EAAE,IAAgB,EAAE,UAAkB,EAAE,MAAc,EAAE,IAAyB;IAC1H,OAAO,IAAA,sBAAU,EAAC,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AAChE,CAAC,CAAA;AAED,IAAI,QAAQ,GAAG,OAAO,CAAC;AAEvB,SAAgB,MAAM,CAAC,SAAoB,EAAE,KAAgB,EAAE,UAAkB,EAAE,MAAc,EAAE,IAAyB;IACxH,MAAM,QAAQ,GAAG,iBAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IACxD,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAO,EAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;AACvE,CAAC;AAJD,wBAIC;AACD,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC;AACnB,MAAM,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACjD,MAAM,CAAC,QAAQ,GAAG,UAAS,IAA0H;IACjJ,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACpD,QAAQ,GAAG,IAAI,CAAC;AACpB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/random.js b/lib.commonjs/crypto/random.js new file mode 100644 index 000000000..00c012bfb --- /dev/null +++ b/lib.commonjs/crypto/random.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = void 0; +const crypto_js_1 = require("./crypto.js"); +let locked = false; +const _randomBytes = function (length) { + return new Uint8Array((0, crypto_js_1.randomBytes)(length)); +}; +let __randomBytes = _randomBytes; +function randomBytes(length) { + return __randomBytes(length); +} +exports.randomBytes = randomBytes; +randomBytes._ = _randomBytes; +randomBytes.lock = function () { locked = true; }; +randomBytes.register = function (func) { + if (locked) { + throw new Error("random is locked"); + } + __randomBytes = func; +}; +Object.freeze(randomBytes); +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/random.js.map b/lib.commonjs/crypto/random.js.map new file mode 100644 index 000000000..ef155940f --- /dev/null +++ b/lib.commonjs/crypto/random.js.map @@ -0,0 +1 @@ +{"version":3,"file":"random.js","sourceRoot":"","sources":["../../src.ts/crypto/random.ts"],"names":[],"mappings":";;;AAAA,2CAA2D;AAE3D,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,YAAY,GAAG,UAAS,MAAc;IACxC,OAAO,IAAI,UAAU,CAAC,IAAA,uBAAa,EAAC,MAAM,CAAC,CAAC,CAAC;AACjD,CAAC,CAAA;AAED,IAAI,aAAa,GAAG,YAAY,CAAC;AAEjC,SAAgB,WAAW,CAAC,MAAc;IACtC,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC;AACjC,CAAC;AAFD,kCAEC;AAED,WAAW,CAAC,CAAC,GAAG,YAAY,CAAC;AAC7B,WAAW,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACtD,WAAW,CAAC,QAAQ,GAAG,UAAS,IAAoC;IAChE,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACpD,aAAa,GAAG,IAAI,CAAC;AACzB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/ripemd160.js b/lib.commonjs/crypto/ripemd160.js new file mode 100644 index 000000000..d790d1b70 --- /dev/null +++ b/lib.commonjs/crypto/ripemd160.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ripemd160 = void 0; +const ripemd160_1 = require("@noble/hashes/ripemd160"); +const index_js_1 = require("../utils/index.js"); +let locked = false; +const _ripemd160 = function (data) { + return (0, ripemd160_1.ripemd160)(data); +}; +let __ripemd160 = _ripemd160; +function ripemd160(_data) { + const data = index_js_1.logger.getBytes(_data, "data"); + return (0, index_js_1.hexlify)(__ripemd160(data)); +} +exports.ripemd160 = ripemd160; +ripemd160._ = _ripemd160; +ripemd160.lock = function () { locked = true; }; +ripemd160.register = function (func) { + if (locked) { + throw new TypeError("ripemd160 is locked"); + } + __ripemd160 = func; +}; +Object.freeze(ripemd160); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/ripemd160.js.map b/lib.commonjs/crypto/ripemd160.js.map new file mode 100644 index 000000000..be54f8355 --- /dev/null +++ b/lib.commonjs/crypto/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../../src.ts/crypto/ripemd160.ts"],"names":[],"mappings":";;;AAAA,uDAAuE;AAEvE,gDAAoD;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,UAAU,GAAG,UAAS,IAAgB;IACxC,OAAO,IAAA,qBAAe,EAAC,IAAI,CAAC,CAAC;AACjC,CAAC,CAAA;AAED,IAAI,WAAW,GAAoC,UAAU,CAAC;AAE9D,SAAgB,SAAS,CAAC,KAAgB;IACtC,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAO,EAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AAHD,8BAGC;AACD,SAAS,CAAC,CAAC,GAAG,UAAU,CAAC;AACzB,SAAS,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,SAAS,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC/D,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;KAAE;IAC3D,WAAW,GAAG,IAAI,CAAC;AACvB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/scrypt.js b/lib.commonjs/crypto/scrypt.js new file mode 100644 index 000000000..fa6eb118c --- /dev/null +++ b/lib.commonjs/crypto/scrypt.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptSync = exports.scrypt = void 0; +const scrypt_1 = require("@noble/hashes/scrypt"); +const index_js_1 = require("../utils/index.js"); +let lockedSync = false, lockedAsync = false; +const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) { + return await (0, scrypt_1.scryptAsync)(passwd, salt, { N, r, p, dkLen, onProgress }); +}; +const _scryptSync = function (passwd, salt, N, r, p, dkLen) { + return (0, scrypt_1.scrypt)(passwd, salt, { N, r, p, dkLen }); +}; +let __scryptAsync = _scryptAsync; +let __scryptSync = _scryptSync; +async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) { + const passwd = index_js_1.logger.getBytes(_passwd, "passwd"); + const salt = index_js_1.logger.getBytes(_salt, "salt"); + return (0, index_js_1.hexlify)(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); +} +exports.scrypt = scrypt; +scrypt._ = _scryptAsync; +scrypt.lock = function () { lockedAsync = true; }; +scrypt.register = function (func) { + if (lockedAsync) { + throw new Error("scrypt is locked"); + } + __scryptAsync = func; +}; +Object.freeze(scrypt); +function scryptSync(_passwd, _salt, N, r, p, dkLen) { + const passwd = index_js_1.logger.getBytes(_passwd, "passwd"); + const salt = index_js_1.logger.getBytes(_salt, "salt"); + return (0, index_js_1.hexlify)(__scryptSync(passwd, salt, N, r, p, dkLen)); +} +exports.scryptSync = scryptSync; +scryptSync._ = _scryptSync; +scryptSync.lock = function () { lockedSync = true; }; +scryptSync.register = function (func) { + if (lockedSync) { + throw new Error("scryptSync is locked"); + } + __scryptSync = func; +}; +Object.freeze(scryptSync); +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/scrypt.js.map b/lib.commonjs/crypto/scrypt.js.map new file mode 100644 index 000000000..c23bcac60 --- /dev/null +++ b/lib.commonjs/crypto/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../../src.ts/crypto/scrypt.ts"],"names":[],"mappings":";;;AAAA,iDAAwF;AAExF,gDAAyD;AAQzD,IAAI,UAAU,GAAG,KAAK,EA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+I;IACtK,IAAI,WAAW,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACzD,aAAa,GAAG,IAAI,CAAC;AACzB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAEtB,SAAgB,UAAU,CAAC,OAAkB,EAAE,KAAgB,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,KAAa;IAC3G,MAAM,MAAM,GAAG,iBAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAClD,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAC,EAAC,YAAY,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AACzD,CAAC;AAJD,gCAIC;AACD,UAAU,CAAC,CAAC,GAAG,WAAW,CAAC;AAC3B,UAAU,CAAC,IAAI,GAAG,cAAmB,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACzD,UAAU,CAAC,QAAQ,GAAG,UAAS,IAAyG;IACpI,IAAI,UAAU,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KAAE;IAC5D,YAAY,GAAG,IAAI,CAAC;AACxB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/sha2.js b/lib.commonjs/crypto/sha2.js new file mode 100644 index 000000000..0ab9dc957 --- /dev/null +++ b/lib.commonjs/crypto/sha2.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sha512 = exports.sha256 = void 0; +const crypto_js_1 = require("./crypto.js"); +const index_js_1 = require("../utils/index.js"); +const _sha256 = function (data) { + return (0, crypto_js_1.createHash)("sha256").update(data).digest(); +}; +const _sha512 = function (data) { + return (0, crypto_js_1.createHash)("sha512").update(data).digest(); +}; +let __sha256 = _sha256; +let __sha512 = _sha512; +let locked256 = false, locked512 = false; +function sha256(_data) { + const data = index_js_1.logger.getBytes(_data, "data"); + return (0, index_js_1.hexlify)(__sha256(data)); +} +exports.sha256 = sha256; +sha256._ = _sha256; +sha256.lock = function () { locked256 = true; }; +sha256.register = function (func) { + if (locked256) { + throw new Error("sha256 is locked"); + } + __sha256 = func; +}; +Object.freeze(sha256); +function sha512(_data) { + const data = index_js_1.logger.getBytes(_data, "data"); + return (0, index_js_1.hexlify)(__sha512(data)); +} +exports.sha512 = sha512; +sha512._ = _sha512; +sha512.lock = function () { locked512 = true; }; +sha512.register = function (func) { + if (locked512) { + throw new Error("sha512 is locked"); + } + __sha512 = func; +}; +Object.freeze(sha256); +//# sourceMappingURL=sha2.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/sha2.js.map b/lib.commonjs/crypto/sha2.js.map new file mode 100644 index 000000000..b3f756fe7 --- /dev/null +++ b/lib.commonjs/crypto/sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.js","sourceRoot":"","sources":["../../src.ts/crypto/sha2.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAEzC,gDAAoD;AAKpD,MAAM,OAAO,GAAG,UAAS,IAAgB;IACrC,OAAO,IAAA,sBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;AACtD,CAAC,CAAA;AAED,MAAM,OAAO,GAAG,UAAS,IAAgB;IACrC,OAAO,IAAA,sBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;AACtD,CAAC,CAAA;AAED,IAAI,QAAQ,GAAoC,OAAO,CAAC;AACxD,IAAI,QAAQ,GAAoC,OAAO,CAAC;AAExD,IAAI,SAAS,GAAG,KAAK,EAAE,SAAS,GAAG,KAAK,CAAC;AAGzC,SAAgB,MAAM,CAAC,KAAgB;IACnC,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAO,EAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AACnC,CAAC;AAHD,wBAGC;AACD,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC;AACnB,MAAM,CAAC,IAAI,GAAG,cAAmB,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,MAAM,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC5D,IAAI,SAAS,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACvD,QAAQ,GAAG,IAAI,CAAC;AACpB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAEtB,SAAgB,MAAM,CAAC,KAAgB;IACnC,MAAM,IAAI,GAAG,iBAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,IAAA,kBAAO,EAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AACnC,CAAC;AAHD,wBAGC;AACD,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC;AACnB,MAAM,CAAC,IAAI,GAAG,cAAmB,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,MAAM,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC5D,IAAI,SAAS,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACvD,QAAQ,GAAG,IAAI,CAAC;AACpB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/signature.js b/lib.commonjs/crypto/signature.js new file mode 100644 index 000000000..7efb10c98 --- /dev/null +++ b/lib.commonjs/crypto/signature.js @@ -0,0 +1,233 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signature = void 0; +const index_js_1 = require("../constants/index.js"); +const index_js_2 = require("../utils/index.js"); +// Constants +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const _guard = {}; +class Signature { + #props; + get r() { return (0, index_js_2.getStore)(this.#props, "r"); } + set r(value) { + if ((0, index_js_2.dataLength)(value) !== 32) { + index_js_2.logger.throwArgumentError("invalid r", "value", value); + } + (0, index_js_2.setStore)(this.#props, "r", (0, index_js_2.hexlify)(value)); + } + get s() { return (0, index_js_2.getStore)(this.#props, "s"); } + set s(value) { + if ((0, index_js_2.dataLength)(value) !== 32) { + index_js_2.logger.throwArgumentError("invalid r", "value", value); + } + else if (index_js_2.logger.getBytes(value)[0] & 0x80) { + index_js_2.logger.throwArgumentError("non-canonical s", "value", value); + } + (0, index_js_2.setStore)(this.#props, "s", (0, index_js_2.hexlify)(value)); + } + get v() { return (0, index_js_2.getStore)(this.#props, "v"); } + set v(value) { + const v = index_js_2.logger.getNumber(value, "value"); + if (v !== 27 && v !== 28) { + throw new Error("@TODO"); + } + (0, index_js_2.setStore)(this.#props, "v", v); + } + get networkV() { return (0, index_js_2.getStore)(this.#props, "networkV"); } + get legacyChainId() { + const v = this.networkV; + if (v == null) { + return null; + } + return Signature.getChainId(v); + } + get yParity() { + if (this.v === 27) { + return 0; + } + return 1; + /* + // When v is 0 or 1 it is the recid directly + if (this.v.isZero()) { return 0; } + if (this.v.eq(1)) { return 1; } + + // Otherwise, odd (e.g. 27) is 0 and even (e.g. 28) is 1 + return this.v.and(1).isZero() ? 1: 0; + */ + } + get yParityAndS() { + // The EIP-2098 compact representation + const yParityAndS = index_js_2.logger.getBytes(this.s); + if (this.yParity) { + yParityAndS[0] |= 0x80; + } + return (0, index_js_2.hexlify)(yParityAndS); + } + get compactSerialized() { + return (0, index_js_2.concat)([this.r, this.yParityAndS]); + } + get serialized() { + return (0, index_js_2.concat)([this.r, this.s, (this.yParity ? "0x1c" : "0x1b")]); + } + constructor(guard, r, s, v) { + index_js_2.logger.assertPrivate(guard, _guard, "Signature"); + this.#props = { r, s, v, networkV: null }; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; + } + clone() { + const clone = new Signature(_guard, this.r, this.s, this.v); + if (this.networkV) { + (0, index_js_2.setStore)(clone.#props, "networkV", this.networkV); + } + return clone; + } + freeze() { + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + toJSON() { + const networkV = this.networkV; + return { + _type: "signature", + networkV: ((networkV != null) ? networkV.toString() : null), + r: this.r, s: this.s, v: this.v, + }; + } + static create() { + return new Signature(_guard, index_js_1.ZeroHash, index_js_1.ZeroHash, 27); + } + // Get the chain ID from an EIP-155 v + static getChainId(v) { + const bv = index_js_2.logger.getBigInt(v, "v"); + // The v is not an EIP-155 v, so it is the unspecified chain ID + if ((bv == BN_27) || (bv == BN_28)) { + return BN_0; + } + // Bad value for an EIP-155 v + if (bv < BN_35) { + index_js_2.logger.throwArgumentError("invalid EIP-155 v", "v", v); + } + return (bv - BN_35) / BN_2; + } + // Get the EIP-155 v transformed for a given chainId + static getChainIdV(chainId, v) { + return (index_js_2.logger.getBigInt(chainId) * BN_2) + BigInt(35 + v - 27); + } + // Convert an EIP-155 v into a normalized v + static getNormalizedV(v) { + const bv = index_js_2.logger.getBigInt(v); + if (bv == BN_0) { + return 27; + } + if (bv == BN_1) { + return 28; + } + // Otherwise, EIP-155 v means odd is 27 and even is 28 + return (bv & BN_1) ? 27 : 28; + } + static from(sig) { + const throwError = (message) => { + return index_js_2.logger.throwArgumentError(message, "signature", sig); + }; + if (typeof (sig) === "string") { + const bytes = index_js_2.logger.getBytes(sig, "signature"); + if (bytes.length === 64) { + const r = (0, index_js_2.hexlify)(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + const v = (s[0] & 0x80) ? 28 : 27; + s[0] &= 0x7f; + return new Signature(_guard, r, (0, index_js_2.hexlify)(s), v); + } + if ((0, index_js_2.dataLength)(sig) !== 65) { + const r = (0, index_js_2.hexlify)(sig.slice(0, 32)); + const s = bytes.slice(32, 64); + if (s[0] & 0x80) { + throwError("non-canonical s"); + } + const v = Signature.getNormalizedV(bytes[64]); + return new Signature(_guard, r, (0, index_js_2.hexlify)(s), v); + } + return throwError("invlaid raw signature length"); + } + if (sig instanceof Signature) { + return sig.clone(); + } + // Get r + const r = sig.r; + if (r == null) { + throwError("missing r"); + } + if (!(0, index_js_2.isHexString)(r, 32)) { + throwError("invalid r"); + } + // Get s; by any means necessary (we check consistency below) + const s = (function (s, yParityAndS) { + if (s != null) { + if (!(0, index_js_2.isHexString)(s, 32)) { + throwError("invalid s"); + } + return s; + } + if (yParityAndS != null) { + if (!(0, index_js_2.isHexString)(yParityAndS, 32)) { + throwError("invalid yParityAndS"); + } + const bytes = index_js_2.logger.getBytes(yParityAndS); + bytes[0] &= 0x7f; + return (0, index_js_2.hexlify)(bytes); + } + return throwError("missing s"); + })(sig.s, sig.yParityAndS); + if (index_js_2.logger.getBytes(s)[0] & 0x80) { + throwError("non-canonical s"); + } + // Get v; by any means necessary (we check consistency below) + const { networkV, v } = (function (_v, yParityAndS, yParity) { + if (_v != null) { + const v = index_js_2.logger.getBigInt(_v); + return { + networkV: ((v >= BN_35) ? v : undefined), + v: Signature.getNormalizedV(v) + }; + } + if (yParityAndS != null) { + if (!(0, index_js_2.isHexString)(yParityAndS, 32)) { + throwError("invalid yParityAndS"); + } + return { v: ((index_js_2.logger.getBytes(yParityAndS)[0] & 0x80) ? 28 : 27) }; + } + if (yParity != null) { + switch (yParity) { + case 0: return { v: 27 }; + case 1: return { v: 28 }; + } + return throwError("invalid yParity"); + } + return throwError("missing v"); + })(sig.v, sig.yParityAndS, sig.yParity); + const result = new Signature(_guard, r, s, v); + if (networkV) { + (0, index_js_2.setStore)(result.#props, "networkV", networkV); + } + // If multiple of v, yParity, yParityAndS we given, check they match + if ("yParity" in sig && sig.yParity !== result.yParity) { + throwError("yParity mismatch"); + } + else if ("yParityAndS" in sig && sig.yParityAndS !== result.yParityAndS) { + throwError("yParityAndS mismatch"); + } + return result; + } +} +exports.Signature = Signature; +//# sourceMappingURL=signature.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/signature.js.map b/lib.commonjs/crypto/signature.js.map new file mode 100644 index 000000000..1f0cbccfb --- /dev/null +++ b/lib.commonjs/crypto/signature.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signature.js","sourceRoot":"","sources":["../../src.ts/crypto/signature.ts"],"names":[],"mappings":";;;AAAA,oDAAiD;AACjD,gDAE2B;AAK3B,YAAY;AACZ,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAGzB,MAAM,MAAM,GAAG,EAAG,CAAC;AAwBnB,MAAa,SAAS;IAClB,MAAM,CAAgE;IAEtE,IAAI,CAAC,KAAa,OAAO,IAAA,mBAAQ,EAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACtD,IAAI,CAAC,CAAC,KAAgB;QAClB,IAAI,IAAA,qBAAU,EAAC,KAAK,CAAC,KAAK,EAAE,EAAE;YAC1B,iBAAM,CAAC,kBAAkB,CAAC,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC1D;QACD,IAAA,mBAAQ,EAAC,IAAI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E;QACpE,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO,EAAE;YACpD,UAAU,CAAC,kBAAkB,CAAC,CAAC;SAClC;aAAM,IAAI,aAAa,IAAI,GAAG,IAAI,GAAG,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW,EAAE;YACvE,UAAU,CAAC,sBAAsB,CAAC,CAAC;SACtC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AA1ND,8BA0NC"} \ No newline at end of file diff --git a/lib.commonjs/crypto/signing-key.js b/lib.commonjs/crypto/signing-key.js new file mode 100644 index 000000000..a38c72df4 --- /dev/null +++ b/lib.commonjs/crypto/signing-key.js @@ -0,0 +1,133 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SigningKey = void 0; +const secp256k1 = __importStar(require("@noble/secp256k1")); +const index_js_1 = require("../utils/index.js"); +const hmac_js_1 = require("./hmac.js"); +const signature_js_1 = require("./signature.js"); +//const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +// Make noble-secp256k1 sync +secp256k1.utils.hmacSha256Sync = function (key, ...messages) { + return index_js_1.logger.getBytes((0, hmac_js_1.computeHmac)("sha256", key, (0, index_js_1.concat)(messages))); +}; +class SigningKey { + #privateKey; + constructor(privateKey) { + /* @TODO + logger.assertArgument(() => { + if (dataLength(privateKey) !== 32) { throw new Error("bad length"); } + return toBigInt(privateKey) < N; + }, "invalid private key", "privateKey", "[REDACTED]"); + */ + this.#privateKey = (0, index_js_1.hexlify)(privateKey); + } + get privateKey() { return this.#privateKey; } + get publicKey() { return SigningKey.computePublicKey(this.#privateKey); } + get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); } + sign(digest) { + /* @TODO + logger.assertArgument(() => (dataLength(digest) === 32), "invalid digest length", "digest", digest); + */ + const [sigDer, recid] = secp256k1.signSync(index_js_1.logger.getBytesCopy(digest), index_js_1.logger.getBytesCopy(this.#privateKey), { + recovered: true, + canonical: true + }); + const sig = secp256k1.Signature.fromHex(sigDer); + return signature_js_1.Signature.from({ + r: (0, index_js_1.toHex)("0x" + sig.r.toString(16), 32), + s: (0, index_js_1.toHex)("0x" + sig.s.toString(16), 32), + v: (recid ? 0x1c : 0x1b) + }).freeze(); + } + computeShardSecret(other) { + const pubKey = SigningKey.computePublicKey(other); + return (0, index_js_1.hexlify)(secp256k1.getSharedSecret(index_js_1.logger.getBytesCopy(this.#privateKey), pubKey)); + } + static computePublicKey(key, compressed) { + let bytes = index_js_1.logger.getBytes(key, "key"); + if (bytes.length === 32) { + const pubKey = secp256k1.getPublicKey(bytes, !!compressed); + return (0, index_js_1.hexlify)(pubKey); + } + if (bytes.length === 64) { + const pub = new Uint8Array(65); + pub[0] = 0x04; + pub.set(bytes, 1); + bytes = pub; + } + const point = secp256k1.Point.fromHex(bytes); + return (0, index_js_1.hexlify)(point.toRawBytes(compressed)); + } + static recoverPublicKey(digest, signature) { + const sig = signature_js_1.Signature.from(signature); + const der = secp256k1.Signature.fromCompact(index_js_1.logger.getBytesCopy((0, index_js_1.concat)([sig.r, sig.s]))).toDERRawBytes(); + const pubKey = secp256k1.recoverPublicKey(index_js_1.logger.getBytesCopy(digest), der, sig.yParity); + if (pubKey != null) { + return (0, index_js_1.hexlify)(pubKey); + } + return index_js_1.logger.throwArgumentError("invalid signautre for digest", "signature", signature); + } + static _addPoints(p0, p1, compressed) { + const pub0 = secp256k1.Point.fromHex(SigningKey.computePublicKey(p0).substring(2)); + const pub1 = secp256k1.Point.fromHex(SigningKey.computePublicKey(p1).substring(2)); + return "0x" + pub0.add(pub1).toHex(!!compressed); + } +} +exports.SigningKey = SigningKey; +/* +const key = new SigningKey("0x1234567890123456789012345678901234567890123456789012345678901234"); +console.log(key); +console.log(key.sign("0x1234567890123456789012345678901234567890123456789012345678901234")); +{ + const privKey = "0x1234567812345678123456781234567812345678123456781234567812345678"; + const signingKey = new SigningKey(privKey); + console.log("0", signingKey, signingKey.publicKey, signingKey.publicKeyCompressed); + + let pubKey = SigningKey.computePublicKey(privKey); + let pubKeyComp = SigningKey.computePublicKey(privKey, true); + let pubKeyRaw = "0x" + SigningKey.computePublicKey(privKey).substring(4); + console.log("A", pubKey, pubKeyComp); + + let a = SigningKey.computePublicKey(pubKey); + let b = SigningKey.computePublicKey(pubKey, true); + console.log("B", a, b); + + a = SigningKey.computePublicKey(pubKeyComp); + b = SigningKey.computePublicKey(pubKeyComp, true); + console.log("C", a, b); + + a = SigningKey.computePublicKey(pubKeyRaw); + b = SigningKey.computePublicKey(pubKeyRaw, true); + console.log("D", a, b); + + const digest = "0x1122334411223344112233441122334411223344112233441122334411223344"; + const sig = signingKey.sign(digest); + console.log("SS", sig, sig.r, sig.s, sig.yParity); + + console.log("R", SigningKey.recoverPublicKey(digest, sig)); +} +*/ +//# sourceMappingURL=signing-key.js.map \ No newline at end of file diff --git a/lib.commonjs/crypto/signing-key.js.map b/lib.commonjs/crypto/signing-key.js.map new file mode 100644 index 000000000..709772aa5 --- /dev/null +++ b/lib.commonjs/crypto/signing-key.js.map @@ -0,0 +1 @@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CAAA;IACpD,CAAC;CACJ;AA3ED,gCA2EC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCE"} \ No newline at end of file diff --git a/lib.commonjs/ethers.js b/lib.commonjs/ethers.js new file mode 100644 index 000000000..8bcf584b2 --- /dev/null +++ b/lib.commonjs/ethers.js @@ -0,0 +1,148 @@ +"use strict"; +///////////////////////////// +// +Object.defineProperty(exports, "__esModule", { value: true }); +exports.scryptSync = exports.scrypt = exports.pbkdf2 = exports.sha512 = exports.sha256 = exports.ripemd160 = exports.keccak256 = exports.randomBytes = exports.computeHmac = exports.EventLog = exports.ContractTransactionResponse = exports.ContractTransactionReceipt = exports.ContractEventPayload = exports.ContractFactory = exports.Contract = exports.BaseContract = exports.MessagePrefix = exports.EtherSymbol = exports.ZeroHash = exports.MaxInt256 = exports.MinInt256 = exports.MaxUint256 = exports.WeiPerEther = exports.Two = exports.One = exports.Zero = exports.NegativeOne = exports.ZeroAddress = exports.getCreate2Address = exports.getCreateAddress = exports.getIcapAddress = exports.getAddress = exports.Typed = exports.TransactionDescription = exports.Result = exports.LogDescription = exports.Interface = exports.Indexed = exports.checkResultErrors = exports.ParamType = exports.FunctionFragment = exports.Fragment = exports.EventFragment = exports.ErrorFragment = exports.ConstructorFragment = exports.defaultAbiCoder = exports.AbiCoder = exports.parseBytes32String = exports.formatBytes32String = exports.version = void 0; +exports.isCrowdsaleJson = exports.HDNodeWalletManager = exports.HDNodeVoidWallet = exports.HDNodeWallet = exports.getAccountPath = exports.defaultPath = exports.encodeRlp = exports.decodeRlp = exports.Utf8ErrorFuncs = exports.toUtf8String = exports.toUtf8CodePoints = exports.toUtf8Bytes = exports._toEscapedUtf8String = exports.parseUnits = exports.formatUnits = exports.parseEther = exports.formatEther = exports.toNumber = exports.toHex = exports.toBigInt = exports.toArray = exports.mask = exports.toTwos = exports.fromTwos = exports.logger = exports.Logger = exports.assertArgument = exports.parseFixed = exports.formatFixed = exports.FixedNumber = exports.FixedFormat = exports.FetchResponse = exports.FetchRequest = exports.isError = exports.isCallException = exports.encodeBase58 = exports.decodeBase58 = exports.Transaction = exports.recoverAddress = exports.computeAddress = exports.accessListify = exports.TypedDataEncoder = exports.solidityPackedSha256 = exports.solidityPackedKeccak256 = exports.solidityPacked = exports.hashMessage = exports.id = exports.SigningKey = exports.Signature = exports.lock = void 0; +exports.Network = exports.WebSocketProvider = exports.SocketProvider = exports.IpcSocketProvider = exports.InfuraProvider = exports.EtherscanProvider = exports.CloudflareProvider = exports.AnkrProvider = exports.AlchemyProvider = exports.JsonRpcSigner = exports.JsonRpcProvider = exports.JsonRpcApiProvider = exports.FallbackProvider = exports.WordlistOwlA = exports.WordlistOwl = exports.wordlists = exports.LangEn = exports.langEn = exports.Wordlist = exports.Wallet = exports.Mnemonic = exports.encryptKeystoreJson = exports.decryptKeystoreJson = exports.decryptKeystoreJsonSync = exports.isKeystoreJson = exports.decryptCrowdsaleJson = void 0; +var _version_js_1 = require("./_version.js"); +Object.defineProperty(exports, "version", { enumerable: true, get: function () { return _version_js_1.version; } }); +var index_js_1 = require("./abi/index.js"); +Object.defineProperty(exports, "formatBytes32String", { enumerable: true, get: function () { return index_js_1.formatBytes32String; } }); +Object.defineProperty(exports, "parseBytes32String", { enumerable: true, get: function () { return index_js_1.parseBytes32String; } }); +Object.defineProperty(exports, "AbiCoder", { enumerable: true, get: function () { return index_js_1.AbiCoder; } }); +Object.defineProperty(exports, "defaultAbiCoder", { enumerable: true, get: function () { return index_js_1.defaultAbiCoder; } }); +Object.defineProperty(exports, "ConstructorFragment", { enumerable: true, get: function () { return index_js_1.ConstructorFragment; } }); +Object.defineProperty(exports, "ErrorFragment", { enumerable: true, get: function () { return index_js_1.ErrorFragment; } }); +Object.defineProperty(exports, "EventFragment", { enumerable: true, get: function () { return index_js_1.EventFragment; } }); +Object.defineProperty(exports, "Fragment", { enumerable: true, get: function () { return index_js_1.Fragment; } }); +Object.defineProperty(exports, "FunctionFragment", { enumerable: true, get: function () { return index_js_1.FunctionFragment; } }); +Object.defineProperty(exports, "ParamType", { enumerable: true, get: function () { return index_js_1.ParamType; } }); +Object.defineProperty(exports, "checkResultErrors", { enumerable: true, get: function () { return index_js_1.checkResultErrors; } }); +Object.defineProperty(exports, "Indexed", { enumerable: true, get: function () { return index_js_1.Indexed; } }); +Object.defineProperty(exports, "Interface", { enumerable: true, get: function () { return index_js_1.Interface; } }); +Object.defineProperty(exports, "LogDescription", { enumerable: true, get: function () { return index_js_1.LogDescription; } }); +Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return index_js_1.Result; } }); +Object.defineProperty(exports, "TransactionDescription", { enumerable: true, get: function () { return index_js_1.TransactionDescription; } }); +Object.defineProperty(exports, "Typed", { enumerable: true, get: function () { return index_js_1.Typed; } }); +var index_js_2 = require("./address/index.js"); +Object.defineProperty(exports, "getAddress", { enumerable: true, get: function () { return index_js_2.getAddress; } }); +Object.defineProperty(exports, "getIcapAddress", { enumerable: true, get: function () { return index_js_2.getIcapAddress; } }); +Object.defineProperty(exports, "getCreateAddress", { enumerable: true, get: function () { return index_js_2.getCreateAddress; } }); +Object.defineProperty(exports, "getCreate2Address", { enumerable: true, get: function () { return index_js_2.getCreate2Address; } }); +var index_js_3 = require("./constants/index.js"); +Object.defineProperty(exports, "ZeroAddress", { enumerable: true, get: function () { return index_js_3.ZeroAddress; } }); +Object.defineProperty(exports, "NegativeOne", { enumerable: true, get: function () { return index_js_3.NegativeOne; } }); +Object.defineProperty(exports, "Zero", { enumerable: true, get: function () { return index_js_3.Zero; } }); +Object.defineProperty(exports, "One", { enumerable: true, get: function () { return index_js_3.One; } }); +Object.defineProperty(exports, "Two", { enumerable: true, get: function () { return index_js_3.Two; } }); +Object.defineProperty(exports, "WeiPerEther", { enumerable: true, get: function () { return index_js_3.WeiPerEther; } }); +Object.defineProperty(exports, "MaxUint256", { enumerable: true, get: function () { return index_js_3.MaxUint256; } }); +Object.defineProperty(exports, "MinInt256", { enumerable: true, get: function () { return index_js_3.MinInt256; } }); +Object.defineProperty(exports, "MaxInt256", { enumerable: true, get: function () { return index_js_3.MaxInt256; } }); +Object.defineProperty(exports, "ZeroHash", { enumerable: true, get: function () { return index_js_3.ZeroHash; } }); +Object.defineProperty(exports, "EtherSymbol", { enumerable: true, get: function () { return index_js_3.EtherSymbol; } }); +Object.defineProperty(exports, "MessagePrefix", { enumerable: true, get: function () { return index_js_3.MessagePrefix; } }); +var index_js_4 = require("./contract/index.js"); +Object.defineProperty(exports, "BaseContract", { enumerable: true, get: function () { return index_js_4.BaseContract; } }); +Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return index_js_4.Contract; } }); +Object.defineProperty(exports, "ContractFactory", { enumerable: true, get: function () { return index_js_4.ContractFactory; } }); +Object.defineProperty(exports, "ContractEventPayload", { enumerable: true, get: function () { return index_js_4.ContractEventPayload; } }); +Object.defineProperty(exports, "ContractTransactionReceipt", { enumerable: true, get: function () { return index_js_4.ContractTransactionReceipt; } }); +Object.defineProperty(exports, "ContractTransactionResponse", { enumerable: true, get: function () { return index_js_4.ContractTransactionResponse; } }); +Object.defineProperty(exports, "EventLog", { enumerable: true, get: function () { return index_js_4.EventLog; } }); +var index_js_5 = require("./crypto/index.js"); +Object.defineProperty(exports, "computeHmac", { enumerable: true, get: function () { return index_js_5.computeHmac; } }); +Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function () { return index_js_5.randomBytes; } }); +Object.defineProperty(exports, "keccak256", { enumerable: true, get: function () { return index_js_5.keccak256; } }); +Object.defineProperty(exports, "ripemd160", { enumerable: true, get: function () { return index_js_5.ripemd160; } }); +Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return index_js_5.sha256; } }); +Object.defineProperty(exports, "sha512", { enumerable: true, get: function () { return index_js_5.sha512; } }); +Object.defineProperty(exports, "pbkdf2", { enumerable: true, get: function () { return index_js_5.pbkdf2; } }); +Object.defineProperty(exports, "scrypt", { enumerable: true, get: function () { return index_js_5.scrypt; } }); +Object.defineProperty(exports, "scryptSync", { enumerable: true, get: function () { return index_js_5.scryptSync; } }); +Object.defineProperty(exports, "lock", { enumerable: true, get: function () { return index_js_5.lock; } }); +Object.defineProperty(exports, "Signature", { enumerable: true, get: function () { return index_js_5.Signature; } }); +Object.defineProperty(exports, "SigningKey", { enumerable: true, get: function () { return index_js_5.SigningKey; } }); +var index_js_6 = require("./hash/index.js"); +Object.defineProperty(exports, "id", { enumerable: true, get: function () { return index_js_6.id; } }); +//isValidName, namehash, dnsEncode +Object.defineProperty(exports, "hashMessage", { enumerable: true, get: function () { return index_js_6.hashMessage; } }); +Object.defineProperty(exports, "solidityPacked", { enumerable: true, get: function () { return index_js_6.solidityPacked; } }); +Object.defineProperty(exports, "solidityPackedKeccak256", { enumerable: true, get: function () { return index_js_6.solidityPackedKeccak256; } }); +Object.defineProperty(exports, "solidityPackedSha256", { enumerable: true, get: function () { return index_js_6.solidityPackedSha256; } }); +Object.defineProperty(exports, "TypedDataEncoder", { enumerable: true, get: function () { return index_js_6.TypedDataEncoder; } }); +var index_js_7 = require("./transaction/index.js"); +Object.defineProperty(exports, "accessListify", { enumerable: true, get: function () { return index_js_7.accessListify; } }); +Object.defineProperty(exports, "computeAddress", { enumerable: true, get: function () { return index_js_7.computeAddress; } }); +Object.defineProperty(exports, "recoverAddress", { enumerable: true, get: function () { return index_js_7.recoverAddress; } }); +Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return index_js_7.Transaction; } }); +var index_js_8 = require("./utils/index.js"); +Object.defineProperty(exports, "decodeBase58", { enumerable: true, get: function () { return index_js_8.decodeBase58; } }); +Object.defineProperty(exports, "encodeBase58", { enumerable: true, get: function () { return index_js_8.encodeBase58; } }); +Object.defineProperty(exports, "isCallException", { enumerable: true, get: function () { return index_js_8.isCallException; } }); +Object.defineProperty(exports, "isError", { enumerable: true, get: function () { return index_js_8.isError; } }); +Object.defineProperty(exports, "FetchRequest", { enumerable: true, get: function () { return index_js_8.FetchRequest; } }); +Object.defineProperty(exports, "FetchResponse", { enumerable: true, get: function () { return index_js_8.FetchResponse; } }); +Object.defineProperty(exports, "FixedFormat", { enumerable: true, get: function () { return index_js_8.FixedFormat; } }); +Object.defineProperty(exports, "FixedNumber", { enumerable: true, get: function () { return index_js_8.FixedNumber; } }); +Object.defineProperty(exports, "formatFixed", { enumerable: true, get: function () { return index_js_8.formatFixed; } }); +Object.defineProperty(exports, "parseFixed", { enumerable: true, get: function () { return index_js_8.parseFixed; } }); +Object.defineProperty(exports, "assertArgument", { enumerable: true, get: function () { return index_js_8.assertArgument; } }); +Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return index_js_8.Logger; } }); +Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return index_js_8.logger; } }); +Object.defineProperty(exports, "fromTwos", { enumerable: true, get: function () { return index_js_8.fromTwos; } }); +Object.defineProperty(exports, "toTwos", { enumerable: true, get: function () { return index_js_8.toTwos; } }); +Object.defineProperty(exports, "mask", { enumerable: true, get: function () { return index_js_8.mask; } }); +Object.defineProperty(exports, "toArray", { enumerable: true, get: function () { return index_js_8.toArray; } }); +Object.defineProperty(exports, "toBigInt", { enumerable: true, get: function () { return index_js_8.toBigInt; } }); +Object.defineProperty(exports, "toHex", { enumerable: true, get: function () { return index_js_8.toHex; } }); +Object.defineProperty(exports, "toNumber", { enumerable: true, get: function () { return index_js_8.toNumber; } }); +Object.defineProperty(exports, "formatEther", { enumerable: true, get: function () { return index_js_8.formatEther; } }); +Object.defineProperty(exports, "parseEther", { enumerable: true, get: function () { return index_js_8.parseEther; } }); +Object.defineProperty(exports, "formatUnits", { enumerable: true, get: function () { return index_js_8.formatUnits; } }); +Object.defineProperty(exports, "parseUnits", { enumerable: true, get: function () { return index_js_8.parseUnits; } }); +Object.defineProperty(exports, "_toEscapedUtf8String", { enumerable: true, get: function () { return index_js_8._toEscapedUtf8String; } }); +Object.defineProperty(exports, "toUtf8Bytes", { enumerable: true, get: function () { return index_js_8.toUtf8Bytes; } }); +Object.defineProperty(exports, "toUtf8CodePoints", { enumerable: true, get: function () { return index_js_8.toUtf8CodePoints; } }); +Object.defineProperty(exports, "toUtf8String", { enumerable: true, get: function () { return index_js_8.toUtf8String; } }); +Object.defineProperty(exports, "Utf8ErrorFuncs", { enumerable: true, get: function () { return index_js_8.Utf8ErrorFuncs; } }); +Object.defineProperty(exports, "decodeRlp", { enumerable: true, get: function () { return index_js_8.decodeRlp; } }); +Object.defineProperty(exports, "encodeRlp", { enumerable: true, get: function () { return index_js_8.encodeRlp; } }); +var index_js_9 = require("./wallet/index.js"); +Object.defineProperty(exports, "defaultPath", { enumerable: true, get: function () { return index_js_9.defaultPath; } }); +Object.defineProperty(exports, "getAccountPath", { enumerable: true, get: function () { return index_js_9.getAccountPath; } }); +Object.defineProperty(exports, "HDNodeWallet", { enumerable: true, get: function () { return index_js_9.HDNodeWallet; } }); +Object.defineProperty(exports, "HDNodeVoidWallet", { enumerable: true, get: function () { return index_js_9.HDNodeVoidWallet; } }); +Object.defineProperty(exports, "HDNodeWalletManager", { enumerable: true, get: function () { return index_js_9.HDNodeWalletManager; } }); +Object.defineProperty(exports, "isCrowdsaleJson", { enumerable: true, get: function () { return index_js_9.isCrowdsaleJson; } }); +Object.defineProperty(exports, "decryptCrowdsaleJson", { enumerable: true, get: function () { return index_js_9.decryptCrowdsaleJson; } }); +Object.defineProperty(exports, "isKeystoreJson", { enumerable: true, get: function () { return index_js_9.isKeystoreJson; } }); +Object.defineProperty(exports, "decryptKeystoreJsonSync", { enumerable: true, get: function () { return index_js_9.decryptKeystoreJsonSync; } }); +Object.defineProperty(exports, "decryptKeystoreJson", { enumerable: true, get: function () { return index_js_9.decryptKeystoreJson; } }); +Object.defineProperty(exports, "encryptKeystoreJson", { enumerable: true, get: function () { return index_js_9.encryptKeystoreJson; } }); +Object.defineProperty(exports, "Mnemonic", { enumerable: true, get: function () { return index_js_9.Mnemonic; } }); +Object.defineProperty(exports, "Wallet", { enumerable: true, get: function () { return index_js_9.Wallet; } }); +var index_js_10 = require("./wordlists/index.js"); +Object.defineProperty(exports, "Wordlist", { enumerable: true, get: function () { return index_js_10.Wordlist; } }); +Object.defineProperty(exports, "langEn", { enumerable: true, get: function () { return index_js_10.langEn; } }); +Object.defineProperty(exports, "LangEn", { enumerable: true, get: function () { return index_js_10.LangEn; } }); +Object.defineProperty(exports, "wordlists", { enumerable: true, get: function () { return index_js_10.wordlists; } }); +Object.defineProperty(exports, "WordlistOwl", { enumerable: true, get: function () { return index_js_10.WordlistOwl; } }); +Object.defineProperty(exports, "WordlistOwlA", { enumerable: true, get: function () { return index_js_10.WordlistOwlA; } }); +var index_js_11 = require("./providers/index.js"); +Object.defineProperty(exports, "FallbackProvider", { enumerable: true, get: function () { return index_js_11.FallbackProvider; } }); +Object.defineProperty(exports, "JsonRpcApiProvider", { enumerable: true, get: function () { return index_js_11.JsonRpcApiProvider; } }); +Object.defineProperty(exports, "JsonRpcProvider", { enumerable: true, get: function () { return index_js_11.JsonRpcProvider; } }); +Object.defineProperty(exports, "JsonRpcSigner", { enumerable: true, get: function () { return index_js_11.JsonRpcSigner; } }); +Object.defineProperty(exports, "AlchemyProvider", { enumerable: true, get: function () { return index_js_11.AlchemyProvider; } }); +Object.defineProperty(exports, "AnkrProvider", { enumerable: true, get: function () { return index_js_11.AnkrProvider; } }); +Object.defineProperty(exports, "CloudflareProvider", { enumerable: true, get: function () { return index_js_11.CloudflareProvider; } }); +Object.defineProperty(exports, "EtherscanProvider", { enumerable: true, get: function () { return index_js_11.EtherscanProvider; } }); +Object.defineProperty(exports, "InfuraProvider", { enumerable: true, get: function () { return index_js_11.InfuraProvider; } }); +//PocketProvider } from "./provider-pocket.js"; +Object.defineProperty(exports, "IpcSocketProvider", { enumerable: true, get: function () { return index_js_11.IpcSocketProvider; } }); +Object.defineProperty(exports, "SocketProvider", { enumerable: true, get: function () { return index_js_11.SocketProvider; } }); +Object.defineProperty(exports, "WebSocketProvider", { enumerable: true, get: function () { return index_js_11.WebSocketProvider; } }); +Object.defineProperty(exports, "Network", { enumerable: true, get: function () { return index_js_11.Network; } }); +//# sourceMappingURL=ethers.js.map \ No newline at end of file diff --git a/lib.commonjs/ethers.js.map b/lib.commonjs/ethers.js.map new file mode 100644 index 000000000..256359ec1 --- /dev/null +++ b/lib.commonjs/ethers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ethers.js","sourceRoot":"","sources":["../src.ts/ethers.ts"],"names":[],"mappings":";AAEA,6BAA6B;AAC7B,EAAE;;;;;AAEF,6CAAwC;AAA/B,sGAAA,OAAO,OAAA;AAEhB,2CAQwB;AAPpB,+GAAA,mBAAmB,OAAA;AAAE,8GAAA,kBAAkB,OAAA;AAEvC,oGAAA,QAAQ,OAAA;AAAE,2GAAA,eAAe,OAAA;AACzB,+GAAA,mBAAmB,OAAA;AAAE,yGAAA,aAAa,OAAA;AAAE,yGAAA,aAAa,OAAA;AAAE,oGAAA,QAAQ,OAAA;AAAE,4GAAA,gBAAgB,OAAA;AAAE,qGAAA,SAAS,OAAA;AAExF,6GAAA,iBAAiB,OAAA;AAAE,mGAAA,OAAO,OAAA;AAAE,qGAAA,SAAS,OAAA;AAAE,0GAAA,cAAc,OAAA;AAAE,kGAAA,MAAM,OAAA;AAAE,kHAAA,sBAAsB,OAAA;AACrF,iGAAA,KAAK,OAAA;AAGT,+CAG4B;AAFxB,sGAAA,UAAU,OAAA;AAAE,0GAAA,cAAc,OAAA;AAC1B,4GAAA,gBAAgB,OAAA;AAAE,6GAAA,iBAAiB,OAAA;AAGvC,iDAK8B;AAJ1B,uGAAA,WAAW,OAAA;AACX,uGAAA,WAAW,OAAA;AAAE,gGAAA,IAAI,OAAA;AAAE,+FAAA,GAAG,OAAA;AAAE,+FAAA,GAAG,OAAA;AAAE,uGAAA,WAAW,OAAA;AAAE,sGAAA,UAAU,OAAA;AAAE,qGAAA,SAAS,OAAA;AAAE,qGAAA,SAAS,OAAA;AAC1E,oGAAA,QAAQ,OAAA;AACR,uGAAA,WAAW,OAAA;AAAE,yGAAA,aAAa,OAAA;AAG9B,gDAI6B;AAHzB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8GAAA,iBAAiB,OAAA;AAEpD,oGAAA,OAAO,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/hash/id.js b/lib.commonjs/hash/id.js new file mode 100644 index 000000000..39a1e5cc3 --- /dev/null +++ b/lib.commonjs/hash/id.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.id = void 0; +const keccak_js_1 = require("../crypto/keccak.js"); +const index_js_1 = require("../utils/index.js"); +function id(value) { + return (0, keccak_js_1.keccak256)((0, index_js_1.toUtf8Bytes)(value)); +} +exports.id = id; +//# sourceMappingURL=id.js.map \ No newline at end of file diff --git a/lib.commonjs/hash/id.js.map b/lib.commonjs/hash/id.js.map new file mode 100644 index 000000000..ae8a4adb8 --- /dev/null +++ b/lib.commonjs/hash/id.js.map @@ -0,0 +1 @@ +{"version":3,"file":"id.js","sourceRoot":"","sources":["../../src.ts/hash/id.ts"],"names":[],"mappings":";;;AAAA,mDAAgD;AAChD,gDAAgD;AAEhD,SAAgB,EAAE,CAAC,KAAa;IAC5B,OAAO,IAAA,qBAAS,EAAC,IAAA,sBAAW,EAAC,KAAK,CAAC,CAAC,CAAC;AACzC,CAAC;AAFD,gBAEC"} \ No newline at end of file diff --git a/lib.commonjs/hash/index.js b/lib.commonjs/hash/index.js new file mode 100644 index 000000000..a16684a7f --- /dev/null +++ b/lib.commonjs/hash/index.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypedDataEncoder = exports.solidityPackedSha256 = exports.solidityPackedKeccak256 = exports.solidityPacked = exports.hashMessage = exports.dnsEncode = exports.namehash = exports.isValidName = exports.id = void 0; +var id_js_1 = require("./id.js"); +Object.defineProperty(exports, "id", { enumerable: true, get: function () { return id_js_1.id; } }); +var namehash_js_1 = require("./namehash.js"); +Object.defineProperty(exports, "isValidName", { enumerable: true, get: function () { return namehash_js_1.isValidName; } }); +Object.defineProperty(exports, "namehash", { enumerable: true, get: function () { return namehash_js_1.namehash; } }); +Object.defineProperty(exports, "dnsEncode", { enumerable: true, get: function () { return namehash_js_1.dnsEncode; } }); +var message_js_1 = require("./message.js"); +Object.defineProperty(exports, "hashMessage", { enumerable: true, get: function () { return message_js_1.hashMessage; } }); +var solidity_js_1 = require("./solidity.js"); +Object.defineProperty(exports, "solidityPacked", { enumerable: true, get: function () { return solidity_js_1.solidityPacked; } }); +Object.defineProperty(exports, "solidityPackedKeccak256", { enumerable: true, get: function () { return solidity_js_1.solidityPackedKeccak256; } }); +Object.defineProperty(exports, "solidityPackedSha256", { enumerable: true, get: function () { return solidity_js_1.solidityPackedSha256; } }); +var typed_data_js_1 = require("./typed-data.js"); +Object.defineProperty(exports, "TypedDataEncoder", { enumerable: true, get: function () { return typed_data_js_1.TypedDataEncoder; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/hash/index.js.map b/lib.commonjs/hash/index.js.map new file mode 100644 index 000000000..3e339ae15 --- /dev/null +++ b/lib.commonjs/hash/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/hash/index.ts"],"names":[],"mappings":";;;AACA,iCAA4B;AAAnB,2FAAA,EAAE,OAAA;AACX,6CAAiE;AAAxD,0GAAA,WAAW,OAAA;AAAE,uGAAA,QAAQ,OAAA;AAAE,wGAAA,SAAS,OAAA;AACzC,2CAA2C;AAAlC,yGAAA,WAAW,OAAA;AACpB,6CAEuB;AADnB,6GAAA,cAAc,OAAA;AAAE,sHAAA,uBAAuB,OAAA;AAAE,mHAAA,oBAAoB,OAAA;AAEjE,iDAAmD;AAA1C,iHAAA,gBAAgB,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/hash/message.js b/lib.commonjs/hash/message.js new file mode 100644 index 000000000..dcff4afa9 --- /dev/null +++ b/lib.commonjs/hash/message.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hashMessage = void 0; +const keccak_js_1 = require("../crypto/keccak.js"); +const index_js_1 = require("../constants/index.js"); +const index_js_2 = require("../utils/index.js"); +function hashMessage(message) { + if (typeof (message) === "string") { + message = (0, index_js_2.toUtf8Bytes)(message); + } + return (0, keccak_js_1.keccak256)((0, index_js_2.concat)([ + (0, index_js_2.toUtf8Bytes)(index_js_1.MessagePrefix), + (0, index_js_2.toUtf8Bytes)(String(message.length)), + message + ])); +} +exports.hashMessage = hashMessage; +//# sourceMappingURL=message.js.map \ No newline at end of file diff --git a/lib.commonjs/hash/message.js.map b/lib.commonjs/hash/message.js.map new file mode 100644 index 000000000..53fe07186 --- /dev/null +++ b/lib.commonjs/hash/message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"message.js","sourceRoot":"","sources":["../../src.ts/hash/message.ts"],"names":[],"mappings":";;;AAAA,mDAAgD;AAChD,oDAAsD;AACtD,gDAAwD;AAGxD,SAAgB,WAAW,CAAC,OAA4B;IACpD,IAAI,OAAM,CAAC,OAAO,CAAC,KAAK,QAAQ,EAAE;QAAE,OAAO,GAAG,IAAA,sBAAW,EAAC,OAAO,CAAC,CAAC;KAAE;IACrE,OAAO,IAAA,qBAAS,EAAC,IAAA,iBAAM,EAAC;QACpB,IAAA,sBAAW,EAAC,wBAAa,CAAC;QAC1B,IAAA,sBAAW,EAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACnC,OAAO;KACV,CAAC,CAAC,CAAC;AACR,CAAC;AAPD,kCAOC"} \ No newline at end of file diff --git a/lib.commonjs/hash/namehash.js b/lib.commonjs/hash/namehash.js new file mode 100644 index 000000000..687e84b19 --- /dev/null +++ b/lib.commonjs/hash/namehash.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dnsEncode = exports.namehash = exports.isValidName = exports.ensNormalize = void 0; +const keccak_js_1 = require("../crypto/keccak.js"); +const index_js_1 = require("../utils/index.js"); +//import { ens_normalize } from "./ens-normalize/lib"; +// @TOOD: +function ens_normalize(name) { + return name; +} +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + if (comp.length === 0) { + throw new Error("invalid ENS name; empty component"); + } + return comp; +} +function ensNameSplit(name) { + const bytes = (0, index_js_1.toUtf8Bytes)(ens_normalize(name)); + const comps = []; + if (name.length === 0) { + return comps; + } + let last = 0; + for (let i = 0; i < bytes.length; i++) { + const d = bytes[i]; + // A separator (i.e. "."); copy this component + if (d === 0x2e) { + comps.push(checkComponent(bytes.slice(last, i))); + last = i + 1; + } + } + // There was a stray separator at the end of the name + if (last >= bytes.length) { + throw new Error("invalid ENS name; empty component"); + } + comps.push(checkComponent(bytes.slice(last))); + return comps; +} +function ensNormalize(name) { + return ensNameSplit(name).map((comp) => (0, index_js_1.toUtf8String)(comp)).join("."); +} +exports.ensNormalize = ensNormalize; +function isValidName(name) { + try { + return (ensNameSplit(name).length !== 0); + } + catch (error) { } + return false; +} +exports.isValidName = isValidName; +function namehash(name) { + /* istanbul ignore if */ + if (typeof (name) !== "string") { + index_js_1.logger.throwArgumentError("invalid ENS name; not a string", "name", name); + } + let result = Zeros; + const comps = ensNameSplit(name); + while (comps.length) { + result = (0, keccak_js_1.keccak256)((0, index_js_1.concat)([result, (0, keccak_js_1.keccak256)((comps.pop()))])); + } + return (0, index_js_1.hexlify)(result); +} +exports.namehash = namehash; +function dnsEncode(name) { + return (0, index_js_1.hexlify)((0, index_js_1.concat)(ensNameSplit(name).map((comp) => { + // DNS does not allow components over 63 bytes in length + if (comp.length > 63) { + throw new Error("invalid DNS encoded entry; length exceeds 63 bytes"); + } + const bytes = new Uint8Array(comp.length + 1); + bytes.set(comp, 1); + bytes[0] = bytes.length - 1; + return bytes; + }))) + "00"; +} +exports.dnsEncode = dnsEncode; +//# sourceMappingURL=namehash.js.map \ No newline at end of file diff --git a/lib.commonjs/hash/namehash.js.map b/lib.commonjs/hash/namehash.js.map new file mode 100644 index 000000000..e8bc45801 --- /dev/null +++ b/lib.commonjs/hash/namehash.js.map @@ -0,0 +1 @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EAAE,EAAE;QAClD,wDAAwD;QACxD,IAAI,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACzE;QAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC9C,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QACnB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5B,OAAO,KAAK,CAAC;IAEjB,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAChB,CAAC;AAbD,8BAaC"} \ No newline at end of file diff --git a/lib.commonjs/hash/solidity.js b/lib.commonjs/hash/solidity.js new file mode 100644 index 000000000..6c1bffe8f --- /dev/null +++ b/lib.commonjs/hash/solidity.js @@ -0,0 +1,111 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.solidityPackedSha256 = exports.test = exports.solidityPackedKeccak256 = exports.solidityPacked = void 0; +const index_js_1 = require("../utils/index.js"); +const keccak_js_1 = require("../crypto/keccak.js"); +const sha2_js_1 = require("../crypto/sha2.js"); +const regexBytes = new RegExp("^bytes([0-9]+)$"); +const regexNumber = new RegExp("^(u?int)([0-9]*)$"); +const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); +function _pack(type, value, isArray) { + switch (type) { + case "address": + if (isArray) { + return index_js_1.logger.getBytes((0, index_js_1.zeroPadValue)(value, 32)); + } + return index_js_1.logger.getBytes(value); + case "string": + return (0, index_js_1.toUtf8Bytes)(value); + case "bytes": + return index_js_1.logger.getBytes(value); + case "bool": + value = (!!value ? "0x01" : "0x00"); + if (isArray) { + return index_js_1.logger.getBytes((0, index_js_1.zeroPadValue)(value, 32)); + } + return index_js_1.logger.getBytes(value); + } + let match = type.match(regexNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) { + return index_js_1.logger.throwArgumentError("invalid number type", "type", type); + } + if (isArray) { + size = 256; + } + value = (0, index_js_1.toTwos)(value, size); + return index_js_1.logger.getBytes((0, index_js_1.zeroPadValue)((0, index_js_1.toArray)(value), size / 8)); + } + match = type.match(regexBytes); + if (match) { + const size = parseInt(match[1]); + if (String(size) !== match[1] || size === 0 || size > 32) { + return index_js_1.logger.throwArgumentError("invalid bytes type", "type", type); + } + if ((0, index_js_1.dataLength)(value) !== size) { + return index_js_1.logger.throwArgumentError(`invalid value for ${type}`, "value", value); + } + if (isArray) { + return index_js_1.logger.getBytes((0, index_js_1.zeroPadBytes)(value, 32)); + } + return value; + } + match = type.match(regexArray); + if (match && Array.isArray(value)) { + const baseType = match[1]; + const count = parseInt(match[2] || String(value.length)); + if (count != value.length) { + index_js_1.logger.throwArgumentError(`invalid array length for ${type}`, "value", value); + } + const result = []; + value.forEach(function (value) { + result.push(_pack(baseType, value, true)); + }); + return index_js_1.logger.getBytes((0, index_js_1.concat)(result)); + } + return index_js_1.logger.throwArgumentError("invalid type", "type", type); +} +// @TODO: Array Enum +function solidityPacked(types, values) { + if (types.length != values.length) { + index_js_1.logger.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values); + } + const tight = []; + types.forEach(function (type, index) { + tight.push(_pack(type, values[index])); + }); + return (0, index_js_1.hexlify)((0, index_js_1.concat)(tight)); +} +exports.solidityPacked = solidityPacked; +/** + * Computes the non-standard packed (tightly packed) keccak256 hash of + * the values given the types. + * + * @param {Array} types - The Solidity types to interpret each value as [default: bar] + * @param {Array} values - The values to pack + * + * @returns: {HexString} the hexstring of the hash + * @example: + * solidityPackedKeccak256([ "address", "uint" ], [ "0x1234", 45 ]); + * //_result: + * + * @see https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode + */ +function solidityPackedKeccak256(types, values) { + return (0, keccak_js_1.keccak256)(solidityPacked(types, values)); +} +exports.solidityPackedKeccak256 = solidityPackedKeccak256; +/** + * Test Function, for fun + * + * @param foo - something fun + */ +function test(foo) { +} +exports.test = test; +function solidityPackedSha256(types, values) { + return (0, sha2_js_1.sha256)(solidityPacked(types, values)); +} +exports.solidityPackedSha256 = solidityPackedSha256; +//# sourceMappingURL=solidity.js.map \ No newline at end of file diff --git a/lib.commonjs/hash/solidity.js.map b/lib.commonjs/hash/solidity.js.map new file mode 100644 index 000000000..fb14a1ff5 --- /dev/null +++ b/lib.commonjs/hash/solidity.js.map @@ -0,0 +1 @@ +{"version":3,"file":"solidity.js","sourceRoot":"","sources":["../../src.ts/hash/solidity.ts"],"names":[],"mappings":";;;AAAA,gDAE2B;AAC3B,mDAA8D;AAC9D,+CAAsD;AAGtD,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACjD,MAAM,WAAW,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACpD,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAGtD,SAAS,KAAK,CAAC,IAAY,EAAE,KAAU,EAAE,OAAiB;IACtD,QAAO,IAAI,EAAE;QACT,KAAK,SAAS;YACV,IAAI,OAAO,EAAE;gBAAE,OAAO,iBAAM,CAAC,QAAQ,CAAC,IAAA,uBAAY,EAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC;aAAE;YACjE,OAAO,iBAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClC,KAAK,QAAQ;YACT,OAAO,IAAA,sBAAW,EAAC,KAAK,CAAC,CAAC;QAC9B,KAAK,OAAO;YACR,OAAO,iBAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClC,KAAK,MAAM;YACP,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAA,CAAC,CAAC,MAAM,CAAC,CAAC;YACnC,IAAI,OAAO,EAAE;gBAAE,OAAO,iBAAM,CAAC,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C,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;QAC/B,iBAAM,CAAC,kBAAkB,CAAC,oDAAoD,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;KACpG;IACD,MAAM,KAAK,GAAsB,EAAE,CAAC;IACpC,KAAK,CAAC,OAAO,CAAC,UAAS,IAAI,EAAE,KAAK;QAC9B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;IACH,OAAO,IAAA,kBAAO,EAAC,IAAA,iBAAM,EAAC,KAAK,CAAC,CAAC,CAAC;AAClC,CAAC;AATD,wCASC;AAED;;;;;;;;;;;;;GAaG;AACH,SAAgB,uBAAuB,CAAC,KAA4B,EAAE,MAA0B;IAC5F,OAAO,IAAA,qBAAU,EAAC,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AACrD,CAAC;AAFD,0DAEC;AAED;;;;GAIG;AACH,SAAgB,IAAI,CAAC,GAAoB;AACzC,CAAC;AADD,oBACC;AAED,SAAgB,oBAAoB,CAAC,KAA4B,EAAE,MAA0B;IACzF,OAAO,IAAA,gBAAO,EAAC,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AAClD,CAAC;AAFD,oDAEC"} \ No newline at end of file diff --git a/lib.commonjs/hash/typed-data.js b/lib.commonjs/hash/typed-data.js new file mode 100644 index 000000000..04a61b1d5 --- /dev/null +++ b/lib.commonjs/hash/typed-data.js @@ -0,0 +1,433 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TypedDataEncoder = void 0; +//import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer"; +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 id_js_1 = require("./id.js"); +const logger_js_1 = require("../utils/logger.js"); +const padding = new Uint8Array(32); +padding.fill(0); +const BN__1 = BigInt(-1); +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +; +; +function hexPadRight(value) { + const bytes = logger_js_1.logger.getBytes(value); + const padOffset = bytes.length % 32; + if (padOffset) { + return (0, index_js_3.concat)([bytes, padding.slice(padOffset)]); + } + return (0, index_js_3.hexlify)(bytes); +} +const hexTrue = (0, index_js_3.toHex)(BN_1, 32); +const hexFalse = (0, index_js_3.toHex)(BN_0, 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" +}; +const domainFieldNames = [ + "name", "version", "chainId", "verifyingContract", "salt" +]; +function checkString(key) { + return function (value) { + if (typeof (value) !== "string") { + logger_js_1.logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + } + return value; + }; +} +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function (value) { + return logger_js_1.logger.getBigInt(value, "domain.chainId"); + }, + verifyingContract: function (value) { + try { + return (0, index_js_1.getAddress)(value).toLowerCase(); + } + catch (error) { } + return logger_js_1.logger.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function (value) { + const bytes = logger_js_1.logger.getBytes(value, "domain.salt"); + if (bytes.length !== 32) { + logger_js_1.logger.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); + } + return (0, index_js_3.hexlify)(bytes); + } +}; +function getBaseEncoder(type) { + // intXX and uintXX + { + const match = type.match(/^(u?)int(\d*)$/); + if (match) { + const signed = (match[1] === ""); + const width = parseInt(match[2] || "256"); + if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) { + logger_js_1.logger.throwArgumentError("invalid numeric width", "type", type); + } + const boundsUpper = (0, index_js_3.mask)(BN_MAX_UINT256, signed ? (width - 1) : width); + const boundsLower = signed ? ((boundsUpper + BN_1) * BN__1) : BN_0; + return function (_value) { + const value = logger_js_1.logger.getBigInt(_value, "value"); + if (value < boundsLower || value > boundsUpper) { + logger_js_1.logger.throwArgumentError(`value out-of-bounds for ${type}`, "value", value); + } + return (0, index_js_3.toHex)((0, index_js_3.toTwos)(value, 256), 32); + }; + } + } + // bytesXX + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + if (width === 0 || width > 32 || match[1] !== String(width)) { + logger_js_1.logger.throwArgumentError("invalid bytes width", "type", type); + } + return function (value) { + const bytes = logger_js_1.logger.getBytes(value); + if (bytes.length !== width) { + logger_js_1.logger.throwArgumentError(`invalid length for ${type}`, "value", value); + } + return hexPadRight(value); + }; + } + } + switch (type) { + case "address": return function (value) { + return (0, index_js_3.zeroPadValue)((0, index_js_1.getAddress)(value), 32); + }; + case "bool": return function (value) { + return ((!value) ? hexFalse : hexTrue); + }; + case "bytes": return function (value) { + return (0, index_js_2.keccak256)(value); + }; + case "string": return function (value) { + return (0, id_js_1.id)(value); + }; + } + return null; +} +function encodeType(name, fields) { + return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`; +} +class TypedDataEncoder { + primaryType; + #types; + get types() { + return JSON.parse(this.#types); + } + #fullTypes; + #encoderCache; + constructor(types) { + this.#types = JSON.stringify(types); + this.#fullTypes = new Map(); + this.#encoderCache = new Map(); + // Link struct types to their direct child structs + const links = new Map(); + // Link structs to structs which contain them as a child + const parents = new Map(); + // Link all subtypes within a given struct + const subtypes = new Map(); + Object.keys(types).forEach((type) => { + links.set(type, new Set()); + parents.set(type, []); + subtypes.set(type, new Set()); + }); + for (const name in types) { + const uniqueNames = new Set(); + for (const field of types[name]) { + // Check each field has a unique name + if (uniqueNames.has(field.name)) { + logger_js_1.logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types); + } + uniqueNames.add(field.name); + // Get the base type (drop any array specifiers) + const baseType = (field.type.match(/^([^\x5b]*)(\x5b|$)/))[1] || null; + if (baseType === name) { + logger_js_1.logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types); + } + // Is this a base encoding type? + const encoder = getBaseEncoder(baseType); + if (encoder) { + continue; + } + if (!parents.has(baseType)) { + logger_js_1.logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types); + } + // Add linkage + parents.get(baseType).push(name); + links.get(name).add(baseType); + } + } + // Deduce the primary type + const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0)); + if (primaryTypes.length === 0) { + logger_js_1.logger.throwArgumentError("missing primary type", "types", types); + } + else if (primaryTypes.length > 1) { + logger_js_1.logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", types); + } + (0, index_js_3.defineProperties)(this, { primaryType: primaryTypes[0] }); + // Check for circular type references + function checkCircular(type, found) { + if (found.has(type)) { + logger_js_1.logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types); + } + found.add(type); + for (const child of links.get(type)) { + if (!parents.has(child)) { + continue; + } + // Recursively check children + checkCircular(child, found); + // Mark all ancestors as having this decendant + for (const subtype of found) { + subtypes.get(subtype).add(child); + } + } + found.delete(type); + } + checkCircular(this.primaryType, new Set()); + // Compute each fully describe type + for (const [name, set] of subtypes) { + const st = Array.from(set); + st.sort(); + this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join("")); + } + } + getEncoder(type) { + let encoder = this.#encoderCache.get(type); + if (!encoder) { + encoder = this.#getEncoder(type); + this.#encoderCache.set(type, encoder); + } + return encoder; + } + #getEncoder(type) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return encoder; + } + } + // Array + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const subEncoder = this.getEncoder(subtype); + const length = parseInt(match[3]); + return (value) => { + if (length >= 0 && value.length !== length) { + logger_js_1.logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + let result = value.map(subEncoder); + if (this.#fullTypes.has(subtype)) { + result = result.map(index_js_2.keccak256); + } + return (0, index_js_2.keccak256)((0, index_js_3.concat)(result)); + }; + } + // Struct + const fields = this.types[type]; + if (fields) { + const encodedType = (0, id_js_1.id)(this.#fullTypes.get(type)); + return (value) => { + const values = fields.map(({ name, type }) => { + const result = this.getEncoder(type)(value[name]); + if (this.#fullTypes.has(type)) { + return (0, index_js_2.keccak256)(result); + } + return result; + }); + values.unshift(encodedType); + return (0, index_js_3.concat)(values); + }; + } + return logger_js_1.logger.throwArgumentError(`unknown type: ${type}`, "type", type); + } + encodeType(name) { + const result = this.#fullTypes.get(name); + if (!result) { + return logger_js_1.logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name); + } + return result; + } + encodeData(type, value) { + return this.getEncoder(type)(value); + } + hashStruct(name, value) { + return (0, index_js_2.keccak256)(this.encodeData(name, value)); + } + encode(value) { + return this.encodeData(this.primaryType, value); + } + hash(value) { + return this.hashStruct(this.primaryType, value); + } + _visit(type, value, callback) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return callback(type, value); + } + } + // Array + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const length = parseInt(match[3]); + if (length >= 0 && value.length !== length) { + logger_js_1.logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + return value.map((v) => this._visit(subtype, v, callback)); + } + // Struct + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name, type }) => { + accum[name] = this._visit(type, value[name], callback); + return accum; + }, {}); + } + return logger_js_1.logger.throwArgumentError(`unknown type: ${type}`, "type", type); + } + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + static from(types) { + return new TypedDataEncoder(types); + } + static getPrimaryType(types) { + return TypedDataEncoder.from(types).primaryType; + } + static hashStruct(name, types, value) { + return TypedDataEncoder.from(types).hashStruct(name, value); + } + static hashDomain(domain) { + const domainFields = []; + for (const name in domain) { + const type = domainFieldTypes[name]; + if (!type) { + logger_js_1.logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); + } + domainFields.push({ name, type }); + } + domainFields.sort((a, b) => { + return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); + }); + return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain); + } + static encode(domain, types, value) { + return (0, index_js_3.concat)([ + "0x1901", + TypedDataEncoder.hashDomain(domain), + TypedDataEncoder.from(types).hash(value) + ]); + } + static hash(domain, types, value) { + return (0, index_js_2.keccak256)(TypedDataEncoder.encode(domain, types, value)); + } + // Replaces all address types with ENS names with their looked up address + static async resolveNames(domain, types, value, resolveName) { + // Make a copy to isolate it from the object passed in + domain = Object.assign({}, domain); + // Look up all ENS names + const ensCache = {}; + // Do we need to look up the domain's verifyingContract? + if (domain.verifyingContract && !(0, index_js_3.isHexString)(domain.verifyingContract, 20)) { + ensCache[domain.verifyingContract] = "0x"; + } + // We are going to use the encoder to visit all the base values + const encoder = TypedDataEncoder.from(types); + // Get a list of all the addresses + encoder.visit(value, (type, value) => { + if (type === "address" && !(0, index_js_3.isHexString)(value, 20)) { + ensCache[value] = "0x"; + } + return value; + }); + // Lookup each name + for (const name in ensCache) { + ensCache[name] = await resolveName(name); + } + // Replace the domain verifyingContract if needed + if (domain.verifyingContract && ensCache[domain.verifyingContract]) { + domain.verifyingContract = ensCache[domain.verifyingContract]; + } + // Replace all ENS names with their address + value = encoder.visit(value, (type, value) => { + if (type === "address" && ensCache[value]) { + return ensCache[value]; + } + return value; + }); + return { domain, value }; + } + static getPayload(domain, types, value) { + // Validate the domain fields + TypedDataEncoder.hashDomain(domain); + // Derive the EIP712Domain Struct reference type + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name) => { + const value = domain[name]; + if (value == null) { + return; + } + domainValues[name] = domainChecks[name](value); + domainTypes.push({ name, type: domainFieldTypes[name] }); + }); + const encoder = TypedDataEncoder.from(types); + const typesWithDomain = Object.assign({}, types); + if (typesWithDomain.EIP712Domain) { + logger_js_1.logger.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types); + } + else { + typesWithDomain.EIP712Domain = domainTypes; + } + // Validate the data structures and types + encoder.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder.primaryType, + message: encoder.visit(value, (type, value) => { + // bytes + if (type.match(/^bytes(\d*)/)) { + return (0, index_js_3.hexlify)(logger_js_1.logger.getBytes(value)); + } + // uint or int + if (type.match(/^u?int/)) { + return logger_js_1.logger.getBigInt(value).toString(); + } + switch (type) { + case "address": + return value.toLowerCase(); + case "bool": + return !!value; + case "string": + if (typeof (value) !== "string") { + logger_js_1.logger.throwArgumentError(`invalid string`, "value", value); + } + return value; + } + return logger_js_1.logger.throwArgumentError("unsupported type", "type", type); + }) + }; + } +} +exports.TypedDataEncoder = TypedDataEncoder; +//# sourceMappingURL=typed-data.js.map \ No newline at end of file diff --git a/lib.commonjs/hash/typed-data.js.map b/lib.commonjs/hash/typed-data.js.map new file mode 100644 index 000000000..874b6d922 --- /dev/null +++ b/lib.commonjs/hash/typed-data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typed-data.js","sourceRoot":"","sources":["../../src.ts/hash/typed-data.ts"],"names":[],"mappings":";;;AAAA,2FAA2F;AAC3F,kDAAiD;AACjD,iDAA+C;AAC/C,gDAE2B;AAE3B,mCAA6B;AAC7B,kDAA4C;AAK5C,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAEhB,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AACzB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,cA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AC;QAEtB,OAAO;YACH,KAAK,EAAE,eAAe;YACtB,MAAM,EAAE,YAAY;YACpB,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,IAAY,EAAE,KAAU,EAAE,EAAE;gBAEvD,QAAQ;gBACR,IAAI,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,EAAE;oBAC3B,OAAO,IAAA,kBAAO,EAAC,kBAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;iBAC1C;gBAED,cAAc;gBACd,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE;oBACtB,OAAO,kBAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAC;iBAC7C;gBAED,QAAQ,IAAI,EAAE;oBACV,KAAK,SAAS;wBACV,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;oBAC/B,KAAK,MAAM;wBACP,OAAO,CAAC,CAAC,KAAK,CAAC;oBACnB,KAAK,QAAQ;wBACT,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;4BAC5B,kBAAM,CAAC,kBAAkB,CAAC,gBAAgB,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;yBAC/D;wBACD,OAAO,KAAK,CAAC;iBACpB;gBAED,OAAO,kBAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;YACvE,CAAC,CAAC;SACL,CAAC;IACN,CAAC;CACJ;AA1WD,4CA0WC"} \ No newline at end of file diff --git a/lib.commonjs/index.js b/lib.commonjs/index.js new file mode 100644 index 000000000..fa7c347a5 --- /dev/null +++ b/lib.commonjs/index.js @@ -0,0 +1,33 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ethers = void 0; +const ethers = __importStar(require("./ethers.js")); +exports.ethers = ethers; +__exportStar(require("./ethers.js"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/index.js.map b/lib.commonjs/index.js.map new file mode 100644 index 000000000..318d29afc --- /dev/null +++ b/lib.commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src.ts/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,oDAAsC;AAE7B,wBAAM;AAEf,8CAA4B"} \ No newline at end of file diff --git a/lib.commonjs/package.json b/lib.commonjs/package.json new file mode 100644 index 000000000..5bbefffba --- /dev/null +++ b/lib.commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/lib.commonjs/providers/abstract-provider.js b/lib.commonjs/providers/abstract-provider.js new file mode 100644 index 000000000..3ad526f07 --- /dev/null +++ b/lib.commonjs/providers/abstract-provider.js @@ -0,0 +1,1094 @@ +"use strict"; +// @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. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractProvider = exports.copyRequest = exports.UnmanagedSubscriber = void 0; +const index_js_1 = require("../address/index.js"); +const data_js_1 = require("../utils/data.js"); +const errors_js_1 = require("../utils/errors.js"); +const fetch_js_1 = require("../utils/fetch.js"); +const maths_js_1 = require("../utils/maths.js"); +const index_js_2 = require("../utils/index.js"); +const index_js_3 = require("../utils/index.js"); +; +const logger_js_1 = require("../utils/logger.js"); +const ens_resolver_js_1 = require("./ens-resolver.js"); +const network_js_1 = require("./network.js"); +const provider_js_1 = require("./provider.js"); +const subscriber_polling_js_1 = require("./subscriber-polling.js"); +// Constants +const BN_2 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v) => { + 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; + }); +} +class UnmanagedSubscriber { + name; + constructor(name) { (0, index_js_2.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; +} +// Normalize a ProviderEvent into a Subscription +// @TODO: Make events sync if possible; like block +//function getSyncSubscription(_event: ProviderEvent): Subscription { +//} +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 "pending": + case "debug": + case "network": { + return { type: _event, tag: _event }; + } + } + } + if ((0, data_js_1.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, data_js_1.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" }; + } + return logger_js_1.logger.throwArgumentError("unknown ProviderEvent", "event", _event); +} +function getTime() { return (new Date()).getTime(); } +function copyRequest(tx) { + // @TODO: copy the copy from contracts and use it from this + return tx; +} +exports.copyRequest = copyRequest; +class AbstractProvider { + #subs; + #plugins; + // null=unpaused, true=paused+dropWhilePaused, false=paused + #pausedState; + #networkPromise; + #anyNetwork; + #performCache; + #nextTimer; + #timers; + #disableCcipRead; + // @TODO: This should be a () => Promise so network can be + // done when needed; or rely entirely on _detectNetwork? + constructor(_network) { + 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.#performCache = new Map(); + this.#subs = new Map(); + this.#plugins = new Map(); + this.#pausedState = null; + this.#nextTimer = 0; + this.#timers = new Map(); + this.#disableCcipRead = false; + } + get provider() { return this; } + get plugins() { + return Array.from(this.#plugins.values()); + } + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.validate(this)); + return this; + } + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + set disableCcipRead(value) { this.#disableCcipRead = !!value; } + get disableCcipRead() { return this.#disableCcipRead; } + // Shares multiple identical requests made during the same 250ms + async #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); + } + }, 250); + } + return await perform; + } + 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 fetch_js_1.FetchRequest(href); + if (url.indexOf("{data}") === -1) { + request.body = { data, sender }; + } + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + } + catch (error) { } + // 4xx indicates the result is not present; stop + if (resp.statusCode >= 400 && resp.statusCode < 500) { + return logger_js_1.logger.throwError(`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); + } + return logger_js_1.logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, info: { urls, errorMessages } + }); + } + _wrapTransaction(tx, hash, blockNumber) { + return tx; + } + _detectNetwork() { + return logger_js_1.logger.throwError("sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); + } + // Sub-classes should override this and handle PerformActionRequest requests, calling + // the super for any unhandled actions. + async _perform(req) { + return logger_js_1.logger.throwError(`unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + // State + async getBlockNumber() { + return logger_js_1.logger.getNumber(await this.#perform({ method: "getBlockNumber" }), "%response"); + } + // @TODO: Make this string | Promsie so no await needed if sync is possible + _getAddress(address) { + return (0, index_js_1.resolveAddress)(address, this); + /* + if (typeof(address) === "string") { + if (address.match(/^0x[0-9a-f]+$/i)) { return address; } + const resolved = await this.resolveName(address); + if (resolved == null) { throw new Error("not confiugred @TODO"); } + return resolved; + } + return address.getAddress(); + */ + } + _getBlockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return blockTag; + } + if ((0, data_js_1.isHexString)(blockTag)) { + if ((0, data_js_1.dataLength)(blockTag) === 32) { + return blockTag; + } + return (0, maths_js_1.toQuantity)(blockTag); + } + if (typeof (blockTag) === "number") { + if (blockTag >= 0) { + return (0, maths_js_1.toQuantity)(blockTag); + } + return this.getBlockNumber().then((b) => (0, maths_js_1.toQuantity)(b + blockTag)); + } + return logger_js_1.logger.throwArgumentError("invalid blockTag", "blockTag", blockTag); + } + async getNetwork() { + // 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 = this._detectNetwork().then((network) => { + this.emit("network", network, null); + return network; + }, (error) => { + // Reset the networkPromise on failure, so we will try again + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + }); + this.#networkPromise = detectNetwork; + return await detectNetwork; + } + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork() // 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 + logger_js_1.logger.throwError(`network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone().freeze(); + } + async getFeeData() { + const { block, gasPrice } = await (0, index_js_2.resolveProperties)({ + block: this.getBlock("latest"), + gasPrice: ((async () => { + try { + const gasPrice = await this.#perform({ method: "getGasPrice" }); + return logger_js_1.logger.getBigInt(gasPrice, "%response"); + } + catch (error) { } + return null; + })()) + }); + let maxFeePerGas = null, maxPriorityFeePerGas = null; + if (block && block.baseFeePerGas) { + // We may want to compute this more accurately in the future, + // using the formula "check if the base fee is correct". + // See: https://eips.ethereum.org/EIPS/eip-1559 + maxPriorityFeePerGas = BigInt("1500000000"); + // Allow a network to override their maximum priority fee per gas + //const priorityFeePlugin = (await this.getNetwork()).getPlugin("org.ethers.plugins.max-priority-fee"); + //if (priorityFeePlugin) { + // maxPriorityFeePerGas = await priorityFeePlugin.getPriorityFee(this); + //} + maxFeePerGas = (block.baseFeePerGas * BN_2) + maxPriorityFeePerGas; + } + return new provider_js_1.FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + } + async _getTransaction(_request) { + const network = await this.getNetwork(); + // Fill in any addresses + const request = Object.assign({}, _request, await (0, index_js_2.resolveProperties)({ + to: (_request.to ? (0, index_js_1.resolveAddress)(_request.to, this) : undefined), + from: (_request.from ? (0, index_js_1.resolveAddress)(_request.from, this) : undefined), + })); + return network.formatter.transactionRequest(request); + } + async estimateGas(_tx) { + const transaction = await this._getTransaction(_tx); + return logger_js_1.logger.getBigInt(await this.#perform({ + method: "estimateGas", transaction + }), "%response"); + } + async #call(tx, blockTag, attempt) { + if (attempt >= MAX_CCIP_REDIRECTS) { + logger_js_1.logger.throwError("CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + } + const transaction = copyRequest(tx); + try { + return (0, data_js_1.hexlify)(await this._perform({ method: "call", transaction, blockTag })); + } + catch (error) { + // CCIP Read OffchainLookup + if (!this.disableCcipRead && (0, errors_js_1.isCallException)(error) && attempt >= 0 && blockTag === "latest" && transaction.to != null && (0, data_js_1.dataSlice)(error.data, 0, 4) === "0x556f1830") { + const data = error.data; + const txSender = await (0, index_js_1.resolveAddress)(transaction.to, this); + // Parse the CCIP Read Arguments + let ccipArgs; + try { + ccipArgs = parseOffchainLookup((0, data_js_1.dataSlice)(error.data, 4)); + } + catch (error) { + return logger_js_1.logger.throwError(error.message, "OFFCHAIN_FAULT", { + reason: "BAD_DATA", + transaction, info: { data } + }); + } + // Check the sender of the OffchainLookup matches the transaction + if (ccipArgs.sender.toLowerCase() !== txSender.toLowerCase()) { + return logger_js_1.logger.throwError("CCIP Read sender mismatch", "CALL_EXCEPTION", { + data, transaction, + errorSignature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + errorName: "OffchainLookup", + errorArgs: ccipArgs.errorArgs + }); + } + const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + if (ccipResult == null) { + return logger_js_1.logger.throwError("CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + reason: "FETCH_FAILED", + transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } + }); + } + return this.#call({ + to: txSender, + data: (0, data_js_1.concat)([ + ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData]) + ]), + }, blockTag, attempt + 1); + } + throw error; + } + } + async call(_tx) { + const [tx, blockTag] = await Promise.all([ + this._getTransaction(_tx), this._getBlockTag(_tx.blockTag) + ]); + return this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1); + } + // Account + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + let blockTag = this._getBlockTag(_blockTag); + if (typeof (address) !== "string" || typeof (blockTag) !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await this.#perform(Object.assign(request, { address, blockTag })); + } + async getBalance(address, blockTag) { + return logger_js_1.logger.getBigInt(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return logger_js_1.logger.getNumber(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return (0, data_js_1.hexlify)(await this.#getAccountValue({ method: "getCode" }, address, blockTag)); + } + async getStorageAt(address, _position, blockTag) { + const position = logger_js_1.logger.getBigInt(_position, "position"); + return (0, data_js_1.hexlify)(await this.#getAccountValue({ method: "getStorageAt", position }, address, blockTag)); + } + // Write + async broadcastTransaction(signedTx) { + throw new Error(); + return {}; + } + async #getBlock(block, includeTransactions) { + if ((0, data_js_1.isHexString)(block, 32)) { + return await this.#perform({ + method: "getBlock", blockHash: block, includeTransactions + }); + } + let blockTag = this._getBlockTag(block); + if (typeof (blockTag) !== "string") { + blockTag = await blockTag; + } + return await this.#perform({ + method: "getBlock", blockTag, includeTransactions + }); + } + // Queries + async getBlock(block) { + const [network, params] = await Promise.all([ + this.getNetwork(), this.#getBlock(block, false) + ]); + if (params == null) { + return null; + } + return network.formatter.block(params, this); + } + async getBlockWithTransactions(block) { + const format = (await this.getNetwork()).formatter; + const params = this.#getBlock(block, true); + if (params == null) { + return null; + } + return format.blockWithTransactions(params, this); + } + async getTransaction(hash) { + const format = (await this.getNetwork()).formatter; + const params = await this.#perform({ method: "getTransaction", hash }); + return format.transactionResponse(params, this); + } + async getTransactionReceipt(hash) { + const format = (await this.getNetwork()).formatter; + const receipt = await this.#perform({ method: "getTransactionReceipt", hash }); + if (receipt == null) { + return null; + } + // Some backends did not backfill the effectiveGasPrice into old transactions + // in the receipt, so we look it up manually and inject it. + if (receipt.gasPrice == null && receipt.effectiveGasPrice == null) { + const tx = await this.#perform({ method: "getTransaction", hash }); + receipt.effectiveGasPrice = tx.gasPrice; + } + return format.receipt(receipt, this); + } + async getTransactionResult(hash) { + const result = await this.#perform({ method: "getTransactionResult", hash }); + if (result == null) { + return null; + } + return (0, data_js_1.hexlify)(result); + } + _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) => { + 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; + } + 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.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.toBlock); + } + 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 resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock); + } + // Bloom-filter Queries + async getLogs(_filter) { + const { network, filter } = await (0, index_js_2.resolveProperties)({ + network: this.getNetwork(), + filter: this._getFilter(_filter) + }); + return (await this.#perform({ method: "getLogs", filter })).map((l) => { + return network.formatter.log(l, this); + }); + } + // ENS + _getProvider(chainId) { + return logger_js_1.logger.throwError("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) { + //if (typeof(name) === "string") { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + /* + } else { + const address = await name.getAddress(); + if (address == null) { + return logger.throwArgumentError("Addressable returned no address", "name", name); + } + return address; + } + */ + return null; + } + async lookupAddress(address) { + throw new Error(); + //return "TODO"; + } + async waitForTransaction(hash, confirms = 1, timeout) { + 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(logger_js_1.logger.makeError("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); + } + listener(await this.getBlockNumber()); + }); + } + async waitForBlock(blockTag) { + throw new Error(); + //return new Block({ }, this); + } + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); + } + _setTimeout(_func, 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; + } + _forEachSubscriber(func) { + for (const sub of this.#subs.values()) { + func(sub.subscriber); + } + } + // Event API; sub-classes should override this; any supported + // event filter will have been munged into an EventFilter + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "network": + return new UnmanagedSubscriber(sub.type); + case "block": + return new subscriber_polling_js_1.PollingBlockSubscriber(this); + case "event": + return new subscriber_polling_js_1.PollingEventSubscriber(this, sub.filter); + case "transaction": + return new subscriber_polling_js_1.PollingTransactionSubscriber(this, sub.hash); + case "orphan": + return new subscriber_polling_js_1.PollingOrphanSubscriber(this, sub.filter); + } + throw new Error(`unsupported event: ${sub.type}`); + } + _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 (!sub) { + return false; + } + ; + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const payload = new index_js_2.EventPayload(this, (once ? null : listener), event); + try { + listener.call(this, ...args, payload); + } + catch (error) { } + return !once; + }); + 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); + } + // Sub-classes should override this to shutdown any sockets, etc. + // but MUST call this super.shutdown. + async shutdown() { + // Stop all listeners + this.removeAllListeners(); + // Shut down all tiemrs + for (const timerId of this.#timers.keys()) { + this._clearTimeout(timerId); + } + } + get paused() { return (this.#pausedState != null); } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } + else { + this.pause(false); + } + } + pause(dropWhilePaused) { + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; + } + return logger_js_1.logger.throwError("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() { + 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, start) { + try { + const bytes = _parseBytes(result, start); + if (bytes) { + return (0, index_js_3.toUtf8String)(bytes); + } + } + catch (error) { } + return null; +} +function _parseBytes(result, start) { + if (result === "0x") { + return null; + } + try { + const offset = logger_js_1.logger.getNumber((0, data_js_1.dataSlice)(result, start, start + 32)); + const length = logger_js_1.logger.getNumber((0, data_js_1.dataSlice)(result, offset, offset + 32)); + return (0, data_js_1.dataSlice)(result, offset + 32, offset + 32 + length); + } + catch (error) { } + return null; +} +function numPad(value) { + const result = (0, maths_js_1.toArray)(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) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +const empty = new Uint8Array([]); +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes(datas) { + const result = []; + 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 = logger_js_1.logger.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 (0, data_js_1.concat)(result); +} +const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000"; +function parseOffchainLookup(data) { + const result = { + sender: "", urls: [], calldata: "", selector: "", extraData: "", errorArgs: [] + }; + if ((0, data_js_1.dataLength)(data) < 5 * 32) { + throw new Error("insufficient OffchainLookup data"); + } + const sender = (0, data_js_1.dataSlice)(data, 0, 32); + if ((0, data_js_1.dataSlice)(sender, 0, 12) !== (0, data_js_1.dataSlice)(zeros, 0, 12)) { + throw new Error("corrupt OffchainLookup sender"); + } + result.sender = (0, data_js_1.dataSlice)(sender, 12); + // Read the URLs from the response + try { + const urls = []; + const urlsOffset = logger_js_1.logger.getNumber((0, data_js_1.dataSlice)(data, 32, 64)); + const urlsLength = logger_js_1.logger.getNumber((0, data_js_1.dataSlice)(data, urlsOffset, urlsOffset + 32)); + const urlsData = (0, data_js_1.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) { + throw new Error("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) { + throw new Error("corrupt OffchainLookup calldata"); + } + // Get the callbackSelector (bytes4) + if ((0, data_js_1.dataSlice)(data, 100, 128) !== (0, data_js_1.dataSlice)(zeros, 0, 28)) { + throw new Error("corrupt OffchainLookup callbaackSelector"); + } + result.selector = (0, data_js_1.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) { + throw new Error("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 000000000..bf73807eb --- /dev/null +++ b/lib.commonjs/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,QAAQ;AACR,oBAAoB;AACpB,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,2EAA2E;;;AAE3E,kDAAqD;AACrD,8CAAuF;AACvF,kDAAqD;AACrD,gDAAiD;AACjD,gDAAwD;AACxD,gDAAsF;AACtF,gDAAiD;AAAA,CAAC;AAElD,kDAA4C;AAE5C,uDAAgD;AAChD,6CAAuC;AACvC,+CAA6F;AAC7F,mEAEiC;AAejC,YAAY;AACZ,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvB,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAG9B,SAAS,MAAM,CAAC,MAAc,EAAE,KAAU;IACtC,OAAO,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACjD,IAAI,OAAM,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;YAAE,OAAO,UAAW,CAAC,CAAC,QAAQ,EAAG,EAAE,CAAA;SAAC;QAChE,IAAI,OAAM,CAAC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,mCAAmC;IACnC,IAAI;QACA,MAAM,QAAQ,GAAG,WAAW,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACvC,IAAI,QAAQ,IAAI,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;SAAE;QACnD,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;KAC9B;IAAC,OAAO,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;KAAE;IAEvE,oCAAoC;IACpC,IAAI,IAAA,mBAAS,EAAC,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,KAAK,IAAA,mBAAS,EAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE;QACvD,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;KAC/D;IACD,MAAM,CAAC,QAAQ,GAAG,IAAA,mBAAS,EAAC,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC;IAE3C,6DAA6D;IAC7D,IAAI;QACA,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QACzC,IAAI,SAAS,IAAI,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;SAAE;QACpD,MAAM,CAAC,SAAS,GAAG,SAAS,CAAC;KAChC;IAAC,OAAO,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;KAAE;IAExE,MAAM,CAAC,SAAS,GAAG,yCAAyC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAO,MAAO,CAAC,CAAC,CAAC,CAAC,CAAA;IAGpG,OAAO,MAAM,CAAC;AAClB,CAAC"} \ 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 000000000..bdb606a91 --- /dev/null +++ b/lib.commonjs/providers/abstract-signer.js @@ -0,0 +1,149 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WrappedSigner = exports.VoidSigner = exports.AbstractSigner = void 0; +const logger_js_1 = require("../utils/logger.js"); +const index_js_1 = require("../transaction/index.js"); +const index_js_2 = require("../utils/index.js"); +class AbstractSigner { + provider; + constructor(provider) { + (0, index_js_2.defineProperties)(this, { provider: (provider || null) }); + } + #checkProvider(operation) { + if (this.provider) { + return this.provider; + } + return logger_js_1.logger.throwError("missing provider", "UNSUPPORTED_OPERATION", { operation }); + } + async getNonce(blockTag) { + return this.#checkProvider("getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async #populate(op, tx) { + const provider = this.#checkProvider(op); + //let pop: Deferrable = Object.assign({ }, tx); + let pop = Object.assign({}, tx); + if (pop.to != null) { + pop.to = provider.resolveName(pop.to).then((to) => { + if (to == null) { + return logger_js_1.logger.throwArgumentError("transaction to ENS name not configured", "tx.to", pop.to); + } + return to; + }); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + this.getAddress(), + this.resolveName(from) + ]).then(([address, from]) => { + if (!from || address.toLowerCase() !== from.toLowerCase()) { + return logger_js_1.logger.throwArgumentError("transaction from mismatch", "tx.from", from); + } + return address; + }); + } + return pop; + } + async populateCall(tx) { + const pop = await this.#populate("populateCall", tx); + return pop; + } + async populateTransaction(tx) { + const pop = await this.#populate("populateTransaction", tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.gasLimit == null) { + pop.gasLimit = await this.estimateGas(pop); + } + //@TODO: Copy type logic from AbstractSigner in v5 + return await (0, index_js_2.resolveProperties)(pop); + } + async estimateGas(tx) { + return this.#checkProvider("estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return this.#checkProvider("call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = this.#checkProvider("resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = this.#checkProvider("sendTransaction"); + const txObj = index_js_1.Transaction.from(await this.populateTransaction(tx)); + return await provider.broadcastTransaction(await this.signTransaction(txObj)); + } +} +exports.AbstractSigner = AbstractSigner; +class VoidSigner extends AbstractSigner { + address; + constructor(address, provider) { + super(provider); + (0, index_js_2.defineProperties)(this, { address }); + } + async getAddress() { return this.address; } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + return logger_js_1.logger.throwError(`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; +class WrappedSigner extends AbstractSigner { + #signer; + constructor(signer) { + super(signer.provider); + this.#signer = signer; + } + async getAddress() { + return await this.#signer.getAddress(); + } + connect(provider) { + return new WrappedSigner(this.#signer.connect(provider)); + } + async getNonce(blockTag) { + return await this.#signer.getNonce(blockTag); + } + async populateCall(tx) { + return await this.#signer.populateCall(tx); + } + async populateTransaction(tx) { + return await this.#signer.populateTransaction(tx); + } + async estimateGas(tx) { + return await this.#signer.estimateGas(tx); + } + async call(tx) { + return await this.#signer.call(tx); + } + async resolveName(name) { + return this.#signer.resolveName(name); + } + async signTransaction(tx) { + return await this.#signer.signTransaction(tx); + } + async sendTransaction(tx) { + return await this.#signer.sendTransaction(tx); + } + async signMessage(message) { + return await this.#signer.signMessage(message); + } + async signTypedData(domain, types, value) { + return await this.#signer.signTypedData(domain, types, value); + } +} +exports.WrappedSigner = WrappedSigner; +//# 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 000000000..d17fea3fb --- /dev/null +++ b/lib.commonjs/providers/abstract-signer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-signer.js","s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EAAsB;QAC5C,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,EAAe;QAC7B,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,EAAe;QACtB,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,IAAY;QAC1B,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IAC1C,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,EAAsB;QACxC,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;IAClD,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,EAAsB;QACxC,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;IAClD,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA4B;QAC1C,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAuB,EAAE,KAA4C,EAAE,KAA0B;QACjH,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;CACJ;AAvDD,sCAuDC"} \ No newline at end of file diff --git a/lib.commonjs/providers/common-networks.js b/lib.commonjs/providers/common-networks.js new file mode 100644 index 000000000..b49fb6894 --- /dev/null +++ b/lib.commonjs/providers/common-networks.js @@ -0,0 +1,81 @@ +"use strict"; +/** + * Exports the same Network as "./network.js" except with common + * networks injected registered. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Network = exports.injectCommonNetworks = void 0; +const plugins_network_js_1 = require("./plugins-network.js"); +const provider_etherscan_js_1 = require("./provider-etherscan.js"); +const network_js_1 = require("./network.js"); +Object.defineProperty(exports, "Network", { enumerable: true, get: function () { return network_js_1.Network; } }); +// See: https://chainlist.org +function injectCommonNetworks() { + /// Register popular Ethereum networks + function registerEth(name, chainId, options) { + const func = function () { + const network = new network_js_1.Network(name, chainId); + // We use 0 to disable ENS + if (options.ensNetwork != null) { + network.attachPlugin(new plugins_network_js_1.EnsPlugin(null, options.ensNetwork)); + } + if (options.priorityFee) { + // network.attachPlugin(new MaxPriorityFeePlugin(options.priorityFee)); + } + if (options.etherscan) { + const { url, apiKey } = options.etherscan; + network.attachPlugin(new provider_etherscan_js_1.EtherscanPlugin(url, apiKey)); + } + network.attachPlugin(new plugins_network_js_1.GasCostPlugin()); + return network; + }; + // Register the network by name and chain ID + network_js_1.Network.register(name, func); + network_js_1.Network.register(chainId, func); + if (options.altNames) { + options.altNames.forEach((name) => { + network_js_1.Network.register(name, func); + }); + } + } + registerEth("homestead", 1, { ensNetwork: 1, altNames: ["mainnet"] }); + registerEth("ropsten", 3, { ensNetwork: 3 }); + registerEth("rinkeby", 4, { ensNetwork: 4 }); + registerEth("goerli", 5, { ensNetwork: 5 }); + registerEth("kovan", 42, { ensNetwork: 42 }); + registerEth("classic", 61, {}); + registerEth("classicKotti", 6, {}); + registerEth("xdai", 100, { ensNetwork: 1 }); + // Polygon has a 35 gwei maxPriorityFee requirement + registerEth("matic", 137, { + ensNetwork: 1, + // priorityFee: 35000000000, + etherscan: { + apiKey: "W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7", + url: "https:/\/api.polygonscan.com/" + } + }); + registerEth("maticMumbai", 80001, { + // priorityFee: 35000000000, + etherscan: { + apiKey: "W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7", + url: "https:/\/api-testnet.polygonscan.com/" + } + }); + registerEth("bnb", 56, { + ensNetwork: 1, + etherscan: { + apiKey: "EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9", + url: "http:/\/api.bscscan.com" + } + }); + registerEth("bnbt", 97, { + etherscan: { + apiKey: "EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9", + url: "http:/\/api-testnet.bscscan.com" + } + }); +} +exports.injectCommonNetworks = injectCommonNetworks; +injectCommonNetworks(); +//# sourceMappingURL=common-networks.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/common-networks.js.map b/lib.commonjs/providers/common-networks.js.map new file mode 100644 index 000000000..ec3e2223d --- /dev/null +++ b/lib.commonjs/providers/common-networks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common-networks.js","sourceRoot":"","sources":["../../src.ts/providers/common-networks.ts"],"names":[],"mappings":";AACA;;;GAGG;;;AAEH,6DAAgE;AAChE,mEAA0D;AAE1D,6CAAuC;AA4F9B,wFA5FA,oBAAO,OA4FA;AAnFhB,6BAA6B;AAC7B,SAAgB,oBAAoB;IAEhC,sCAAsC;IACtC,SAAS,WAAW,CAAC,IAAY,EAAE,OAAe,EAAE,OAAgB;QAChE,MAAM,IAAI,GAAG;YACT,MAAM,OAAO,GAAG,IAAI,oBAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAE3C,0BAA0B;YAC1B,IAAI,OAAO,CAAC,UAAU,IAAI,IAAI,EAAE;gBAC5B,OAAO,CAAC,YAAY,CAAC,IAAI,8BAAS,CAAC,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;aACjE;YAED,IAAI,OAAO,CAAC,WAAW,EAAE;gBACrC,sFAAsF;aACzE;YAED,IAAI,OAAO,CAAC,SAAS,EAAE;gBACnB,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,SAAS,CAAC;gBAC1C,OAAO,CAAC,YAAY,CAAC,IAAI,uCAAe,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;aAC1D;YAED,OAAO,CAAC,YAAY,CAAC,IAAI,kCA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C,GAAG,EAAE,+BAA+B;SACvC;KACJ,CAAC,CAAC;IACH,WAAW,CAAC,aAAa,EAAE,KAAK,EAAE;QACtC,mCAAmC;QAC3B,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,uCAAuC;SAC/C;KACJ,CAAC,CAAC;IAEH,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE;QACnB,UAAU,EAAE,CAAC;QACb,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,yBAAyB;SACjC;KACJ,CAAC,CAAC;IACH,WAAW,CAAC,MAAM,EAAE,EAAE,EAAE;QACpB,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,iCAAiC;SACzC;KACJ,CAAC,CAAC;AACP,CAAC;AA9ED,oDA8EC;AAED,oBAAoB,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/providers/community.js b/lib.commonjs/providers/community.js new file mode 100644 index 000000000..b109b5f20 --- /dev/null +++ b/lib.commonjs/providers/community.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.showThrottleMessage = void 0; +// Show the throttle message only once +const shown = new Set(); +function showThrottleMessage(service) { + if (shown.has(service)) { + return; + } + shown.add(service); + console.log("========= NOTICE ========="); + console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`); + console.log(""); + console.log("The default API keys for each service are provided as a highly-throttled,"); + console.log("community resource for low-traffic projects and early prototyping."); + console.log(""); + console.log("While your application will continue to function, we highly recommended"); + console.log("signing up for your own API keys to improve performance, increase your"); + console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); + console.log(""); + console.log("For more details: https:/\/docs.ethers.io/api-keys/"); + console.log("=========================="); +} +exports.showThrottleMessage = showThrottleMessage; +//# sourceMappingURL=community.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/community.js.map b/lib.commonjs/providers/community.js.map new file mode 100644 index 000000000..b7726b725 --- /dev/null +++ b/lib.commonjs/providers/community.js.map @@ -0,0 +1 @@ +{"version":3,"file":"community.js","sourceRoot":"","sources":["../../src.ts/providers/community.ts"],"names":[],"mappings":";;;AAKA,sCAAsC;AACtC,MAAM,KAAK,GAAgB,IAAI,GAAG,EAAE,CAAC;AACrC,SAAgB,mBAAmB,CAAC,OAAe;IAC/C,IAAI,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;QAAE,OAAO;KAAE;IACnC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAEnB,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;IACzC,OAAO,CAAC,GAAG,CAAC,6BAA8B,OAAQ,sCAAsC,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;IACzF,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,wEAAwE,CAAC,CAAC;IACtF,OAAO,CAAC,GAAG,CAAC,+EAA+E,CAAC,CAAC;IAC7F,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAAC;IACnE,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAC9C,CAAC;AAhBD,kDAgBC"} \ No newline at end of file diff --git a/lib.commonjs/providers/contracts.js b/lib.commonjs/providers/contracts.js new file mode 100644 index 000000000..705cd38a9 --- /dev/null +++ b/lib.commonjs/providers/contracts.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=contracts.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/contracts.js.map b/lib.commonjs/providers/contracts.js.map new file mode 100644 index 000000000..42ac4de89 --- /dev/null +++ b/lib.commonjs/providers/contracts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../src.ts/providers/contracts.ts"],"names":[],"mappings":""} \ 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 000000000..9c22e4e7c --- /dev/null +++ b/lib.commonjs/providers/default-provider.js @@ -0,0 +1,98 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDefaultProvider = void 0; +const provider_ankr_js_1 = require("./provider-ankr.js"); +const provider_alchemy_js_1 = require("./provider-alchemy.js"); +const provider_cloudflare_js_1 = require("./provider-cloudflare.js"); +const provider_etherscan_js_1 = require("./provider-etherscan.js"); +const provider_infura_js_1 = require("./provider-infura.js"); +//import { PocketProvider } from "./provider-pocket.js"; +const provider_fallback_js_1 = require("./provider-fallback.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +const provider_websocket_js_1 = require("./provider-websocket.js"); +function isWebSocketLike(value) { + return (value && typeof (value.send) === "function" && + typeof (value.close) === "function"); +} +function getDefaultProvider(network, options) { + if (options == null) { + options = {}; + } + if (typeof (network) === "string" && network.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); + } + const providers = []; + if (options.alchemy !== "-") { + try { + providers.push(new provider_alchemy_js_1.AlchemyProvider(network, options.alchemy)); + } + catch (error) { + console.log(error); + } + } + if (options.ankr !== "-") { + try { + providers.push(new provider_ankr_js_1.AnkrProvider(network, options.ankr)); + } + catch (error) { + console.log(error); + } + } + if (options.cloudflare !== "-") { + try { + providers.push(new provider_cloudflare_js_1.CloudflareProvider(network)); + } + catch (error) { + console.log(error); + } + } + if (options.etherscan !== "-") { + try { + providers.push(new provider_etherscan_js_1.EtherscanProvider(network, options.etherscan)); + } + catch (error) { + console.log(error); + } + } + if (options.infura !== "-") { + try { + let projectId = options.infura; + let projectSecret = undefined; + if (typeof (projectId) === "object") { + projectSecret = projectId.projectSecret; + projectId = projectId.projectId; + } + providers.push(new provider_infura_js_1.InfuraProvider(network, projectId, projectSecret)); + } + catch (error) { + console.log(error); + } + } + /* + 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); } + } + */ + if (providers.length === 0) { + throw new Error("TODO"); + } + if (providers.length === 1) { + return providers[0]; + } + return new provider_fallback_js_1.FallbackProvider(providers); +} +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 000000000..abafc8241 --- /dev/null +++ b/lib.commonjs/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,yDAAkD;AAClD,+DAAwD;AACxD,qEAA8D;AAC9D,mEAA4D;AAC5D,6DAAsD;AACtD,wDAAwD;AAExD,iEAA0D;AAC1D,+DAAwD;AACxD,mEAA4D;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,SAAgB,kBAAkB,CAAC,OAA4C,EAAE,OAAa;IAC1F,IAAI,OAAO,IAAI,IAAI,EAAE;QAAE,OAAO,GAAG,EAA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,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;SACrE;QAAC,OAAO,KAAK,EAAE;YAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAAE;KAC1C;IAED,IAAI,OAAO,CAAC,MAAM,KAAK,GAAG,EAAE;QACxB,IAAI;YACA,IAAI,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC;YAC/B,IAAI,aAAa,GAAuB,SAAS,CAAC;YAClD,IAAI,OAAM,CAAC,SAAS,CAAC,KAAK,QAAQ,EAAE;gBAChC,aAAa,GAAG,SAAS,CAAC,aAAa,CAAC;gBACxC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;aACnC;YACD,SAAS,CAAC,IAAI,CAAC,IAAI,mCAAc,CAAC,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC,CAAC;SACzE;QAAC,OAAO,KAAK,EAAE;YAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAAE;KAC1C;IACL;;;;;;;;;;;;;;MAcE;IACE,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC;KAAE;IACxD,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAAE,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC;KAAE;IAEpD,OAAO,IAAI,uCAAgB,CAAC,SAAS,CAAC,CAAC;AAC3C,CAAC;AAnED,gDAmEC"} \ No newline at end of file diff --git a/lib.commonjs/providers/ens-resolver.js b/lib.commonjs/providers/ens-resolver.js new file mode 100644 index 000000000..e167daa4f --- /dev/null +++ b/lib.commonjs/providers/ens-resolver.js @@ -0,0 +1,471 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EnsResolver = exports.BasicMulticoinProviderPlugin = exports.MulticoinProviderPlugin = void 0; +const hashes_js_1 = require("../constants/hashes.js"); +const index_js_1 = require("../hash/index.js"); +const index_js_2 = require("../utils/index.js"); +const data_js_1 = require("../utils/data.js"); +const fetch_js_1 = require("../utils/fetch.js"); +const logger_js_1 = require("../utils/logger.js"); +const BN_1 = BigInt(1); +const Empty = new Uint8Array([]); +function parseBytes(result, start) { + if (result === "0x") { + return null; + } + const offset = (0, index_js_2.toNumber)((0, data_js_1.dataSlice)(result, start, start + 32)); + const length = (0, index_js_2.toNumber)((0, data_js_1.dataSlice)(result, offset, offset + 32)); + return (0, data_js_1.dataSlice)(result, offset + 32, offset + 32 + length); +} +function parseString(result, start) { + try { + const bytes = parseBytes(result, start); + if (bytes != null) { + return (0, index_js_2.toUtf8String)(bytes); + } + } + catch (error) { } + return null; +} +function numPad(value) { + const result = (0, index_js_2.toArray)(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) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes(datas) { + const result = []; + 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 = logger_js_1.logger.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 (0, data_js_1.concat)(result); +} +// @TODO: This should use the fetch-data:ipfs gateway +// Trim off the ipfs:// prefix and return the default gateway URL +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } + else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } + else { + logger_js_1.logger.throwArgumentError("unsupported IPFS format", "link", link); + } + return `https:/\/gateway.ipfs.io/ipfs/${link}`; +} +; +; +class MulticoinProviderPlugin { + name; + constructor(name) { + (0, index_js_2.defineProperties)(this, { name }); + } + validate(proivder) { + return this; + } + supportsCoinType(coinType) { + return false; + } + async encodeAddress(coinType, address) { + throw new Error("unsupported coin"); + } + async decodeAddress(coinType, data) { + throw new Error("unsupported coin"); + } +} +exports.MulticoinProviderPlugin = MulticoinProviderPlugin; +const BasicMulticoinPluginId = "org.ethers.provider-prugins.basicmulticoin"; +class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin { + constructor() { + super(BasicMulticoinPluginId); + } +} +exports.BasicMulticoinProviderPlugin = BasicMulticoinProviderPlugin; +const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i"); +const matchers = [ + new RegExp("^(https):/\/(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"), +]; +class EnsResolver { + provider; + address; + name; + // For EIP-2544 names, the ancestor that provided the resolver + #supports2544; + constructor(provider, address, name) { + (0, index_js_2.defineProperties)(this, { provider, address, name }); + this.#supports2544 = null; + } + async supportsWildcard() { + if (!this.#supports2544) { + // supportsInterface(bytes4 = selector("resolve(bytes,bytes)")) + this.#supports2544 = this.provider.call({ + to: this.address, + data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000" + }).then((result) => { + return (logger_js_1.logger.getBigInt(result) === BN_1); + }).catch((error) => { + if (error.code === "CALL_EXCEPTION") { + return false; + } + // Rethrow the error: link is down, etc. Let future attempts retry. + this.#supports2544 = null; + throw error; + }); + } + return await this.#supports2544; + } + async _fetch(selector, parameters = "0x") { + // e.g. keccak256("addr(bytes32,uint256)") + const addrData = (0, data_js_1.concat)([selector, (0, index_js_1.namehash)(this.name), parameters]); + const tx = { + to: this.address, + enableCcipRead: true, + data: addrData + }; + // Wildcard support; use EIP-2544 to resolve the request + let wrapped = false; + if (await this.supportsWildcard()) { + wrapped = true; + // selector("resolve(bytes,bytes)") + tx.data = (0, data_js_1.concat)(["0x9061b923", encodeBytes([(0, index_js_1.dnsEncode)(this.name), addrData])]); + } + try { + let data = await this.provider.call(tx); + if ((logger_js_1.logger.getBytes(data).length % 32) === 4) { + return logger_js_1.logger.throwError("resolver threw error", "CALL_EXCEPTION", { + transaction: tx, data + }); + } + if (wrapped) { + return parseBytes(data, 0); + } + return data; + } + catch (error) { + if (error.code !== "CALL_EXCEPTION") { + throw error; + } + } + return null; + } + async getAddress(coinType = 60) { + if (coinType === 60) { + try { + // keccak256("addr(bytes32)") + const result = await this._fetch("0x3b3b57de"); + // No address + if (result === "0x" || result === hashes_js_1.ZeroHash) { + return null; + } + const network = await this.provider.getNetwork(); + return network.formatter.callAddress(result); + } + catch (error) { + if (error.code === "CALL_EXCEPTION") { + return null; + } + throw error; + } + } + let coinPlugin = null; + for (const plugin of this.provider.plugins) { + if (!(plugin instanceof MulticoinProviderPlugin)) { + continue; + } + if (plugin.supportsCoinType(coinType)) { + coinPlugin = plugin; + break; + } + } + if (coinPlugin == null) { + return null; + } + // keccak256("addr(bytes32,uint256") + const data = parseBytes((await this._fetch("0xf1cb7e06", numPad(coinType))) || "0x", 0); + // No address + if (data == null || data === "0x") { + return null; + } + // Compute the address + const address = await coinPlugin.encodeAddress(coinType, data); + if (address != null) { + return address; + } + return logger_js_1.logger.throwError(`invalid coin data`, "UNSUPPORTED_OPERATION", { + operation: `getAddress(${coinType})`, + info: { coinType, data } + }); + } + async getText(key) { + // The key encoded as parameter to fetchBytes + let keyBytes = (0, index_js_2.toUtf8Bytes)(key); + // The nodehash consumes the first slot, so the string pointer targets + // offset 64, with the length at offset 64 and data starting at offset 96 + const calldata = logger_js_1.logger.getBytes((0, data_js_1.concat)([numPad(64), numPad(keyBytes.length), keyBytes])); + const hexBytes = parseBytes((await this._fetch("0x59d1d43c", bytesPad(calldata))) || "0x", 0); + if (hexBytes == null || hexBytes === "0x") { + return null; + } + return (0, index_js_2.toUtf8String)(hexBytes); + } + async getContentHash() { + // keccak256("contenthash()") + const hexBytes = parseBytes((await this._fetch("0xbc1c58d1")) || "0x", 0); + // No contenthash + if (hexBytes == null || hexBytes === "0x") { + return null; + } + // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key) + const ipfs = hexBytes.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const scheme = (ipfs[1] === "e3010170") ? "ipfs" : "ipns"; + const length = parseInt(ipfs[4], 16); + if (ipfs[5].length === length * 2) { + return `${scheme}:/\/${(0, index_js_2.encodeBase58)("0x" + ipfs[2])}`; + } + } + // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32) + const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm && swarm[1].length === 64) { + return `bzz:/\/${swarm[1]}`; + } + return logger_js_1.logger.throwError(`invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { + operation: "getContentHash()", + info: { data: hexBytes } + }); + } + async getAvatar() { + return (await this._getAvatar()).url; + } + async _getAvatar() { + const linkage = [{ type: "name", value: this.name }]; + try { + // test data for ricmoo.eth + //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233"; + const avatar = await this.getText("avatar"); + if (avatar == null) { + linkage.push({ type: "!avatar", value: "" }); + throw new Error("!avatar"); + } + linkage.push({ type: "avatar", value: avatar }); + for (let i = 0; i < matchers.length; i++) { + const match = avatar.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch (scheme) { + case "https": + case "data": + linkage.push({ type: "url", value: avatar }); + return { linkage, url: avatar }; + case "ipfs": { + const url = getIpfsLink(avatar); + linkage.push({ type: "ipfs", value: avatar }); + linkage.push({ type: "url", value: url }); + return { linkage, url }; + } + case "erc721": + case "erc1155": { + // Depending on the ERC type, use tokenURI(uint256) or url(uint256) + const selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c"; + linkage.push({ type: scheme, value: avatar }); + // The owner of this name + const owner = await this.getAddress(); + if (owner == null) { + linkage.push({ type: "!owner", value: "" }); + throw new Error("!owner"); + } + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + linkage.push({ type: `!${scheme}caip`, value: (match[2] || "") }); + throw new Error("!caip"); + } + const formatter = (await this.provider.getNetwork()).formatter; + const addr = formatter.address(comps[0]); + const tokenId = numPad(comps[1]); + // Check that this account owns the token + if (scheme === "erc721") { + // ownerOf(uint256 tokenId) + const tokenOwner = formatter.callAddress(await this.provider.call({ + to: addr, data: (0, data_js_1.concat)(["0x6352211e", tokenId]) + })); + if (owner !== tokenOwner) { + linkage.push({ type: "!owner", value: tokenOwner }); + throw new Error("!owner"); + } + linkage.push({ type: "owner", value: tokenOwner }); + } + else if (scheme === "erc1155") { + // balanceOf(address owner, uint256 tokenId) + const balance = logger_js_1.logger.getBigInt(await this.provider.call({ + to: addr, data: (0, data_js_1.concat)(["0x00fdd58e", (0, data_js_1.zeroPadValue)(owner, 32), tokenId]) + })); + if (!balance) { + linkage.push({ type: "!balance", value: "0" }); + throw new Error("!balance"); + } + linkage.push({ type: "balance", value: balance.toString() }); + } + // Call the token contract for the metadata URL + const tx = { + to: comps[0], + data: (0, data_js_1.concat)([selector, tokenId]) + }; + let metadataUrl = parseString(await this.provider.call(tx), 0); + if (metadataUrl == null) { + linkage.push({ type: "!metadata-url", value: "" }); + throw new Error("!metadata-url"); + } + linkage.push({ type: "metadata-url-base", value: metadataUrl }); + // ERC-1155 allows a generic {id} in the URL + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", (0, data_js_1.hexlify)(tokenId).substring(2)); + linkage.push({ type: "metadata-url-expanded", value: metadataUrl }); + } + // Transform IPFS metadata links + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ type: "metadata-url", value: metadataUrl }); + // Get the token metadata + let metadata = {}; + const response = await (new fetch_js_1.FetchRequest(metadataUrl)).send(); + response.assertOk(); + try { + metadata = response.bodyJson; + } + catch (error) { + try { + linkage.push({ type: "!metadata", value: response.bodyText }); + } + catch (error) { + const bytes = response.body; + if (bytes) { + linkage.push({ type: "!metadata", value: (0, data_js_1.hexlify)(bytes) }); + } + throw error; + } + throw error; + } + if (!metadata) { + linkage.push({ type: "!metadata", value: "" }); + throw new Error("!metadata"); + } + linkage.push({ type: "metadata", value: JSON.stringify(metadata) }); + // Pull the image URL out + let imageUrl = metadata.image; + if (typeof (imageUrl) !== "string") { + linkage.push({ type: "!imageUrl", value: "" }); + throw new Error("!imageUrl"); + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) { + // Allow + } + else { + // Transform IPFS link to gateway + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + linkage.push({ type: "!imageUrl-ipfs", value: imageUrl }); + throw new Error("!imageUrl-ipfs"); + } + linkage.push({ type: "imageUrl-ipfs", value: imageUrl }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ type: "url", value: imageUrl }); + return { linkage, url: imageUrl }; + } + } + } + } + catch (error) { + console.log("EE", error); + } + return { linkage, url: null }; + } + static async #getResolver(provider, name) { + const network = await provider.getNetwork(); + const ensPlugin = network.getPlugin("org.ethers.network-plugins.ens"); + // No ENS... + if (!ensPlugin) { + return logger_js_1.logger.throwError("network does not support ENS", "UNSUPPORTED_OPERATION", { + operation: "getResolver", info: { network: network.name } + }); + } + try { + // keccak256("resolver(bytes32)") + const addrData = await provider.call({ + to: ensPlugin.address, + data: (0, data_js_1.concat)(["0x0178b8bf", (0, index_js_1.namehash)(name)]), + enableCcipRead: true + }); + const addr = network.formatter.callAddress(addrData); + if (addr === (0, data_js_1.dataSlice)(hashes_js_1.ZeroHash, 0, 20)) { + return null; + } + return addr; + } + catch (error) { + // ENS registry cannot throw errors on resolver(bytes32), + // so probably a link error + throw error; + } + return null; + } + static async fromName(provider, name) { + let currentName = name; + while (true) { + if (currentName === "" || currentName === ".") { + return null; + } + // Optimization since the eth node cannot change and does + // not have a wildcar resolver + if (name !== "eth" && currentName === "eth") { + return null; + } + // Check the current node for a resolver + const addr = await EnsResolver.#getResolver(provider, currentName); + // Found a resolver! + if (addr != null) { + const resolver = new EnsResolver(provider, addr, name); + // Legacy resolver found, using EIP-2544 so it isn't safe to use + if (currentName !== name && !(await resolver.supportsWildcard())) { + return null; + } + return resolver; + } + // Get the parent node + currentName = currentName.split(".").slice(1).join("."); + } + } +} +exports.EnsResolver = EnsResolver; +//# sourceMappingURL=ens-resolver.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/ens-resolver.js.map b/lib.commonjs/providers/ens-resolver.js.map new file mode 100644 index 000000000..2e66b2627 --- /dev/null +++ b/lib.commonjs/providers/ens-resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ens-resolver.js","sourceRoot":"","sources":["../../src.ts/providers/ens-resolver.ts"],"names":[],"mappings":";;;AAAA,sDAAkD;AAClD,+CAAuD;AACvD,gDAE2B;AAC3B,8CAA4E;AAC5E,gDAAiD;AACjD,kDAA4C;AAQ5C,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvB,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,EAAG,CAAC,CAAC;AAElC,SAAS,UAAU,CAAC,MAAc,EAAE,KAAa;IAC7C,IAAI,MAAM,KAAK,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IAErC,MAAM,MAAM,GAAG,IAAA,mBAAQ,EAAC,IAAA,mBAAS,EAAC,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,EAAE,CAAC,CAAC,CAAC;IAC9D,MAAM,MAAM,GAAG,IAAA,mBAAQ,EAAC,IAAA,mBAAS,EAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC;IAEhE,OAAO,IAAA,mBAAS,EAAC,MAAM,EAAE,MAAM,GAAG,EAAE,EAAE,MAAM,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,WAAW,CAAC,MAAc,EAAE,KAAa;IAC9C,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;YACT,IAAI,WAAW,KAAK,EAAE,IAAI,WAAW,KAAK,GAAG,EAAE;gBAAE,OAAO,IAAI,CAAC;aAAE;YAE/D,yDAAyD;YACzD,8BAA8B;YAC9B,IAAI,IAAI,KAAK,KAAK,IAAI,WAAW,KAAK,KAAK,EAAE;gBAAE,OAAO,IAAI,CAAC;aAAE;YAE7D,wCAAwC;YACxC,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,YAAY,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;YAEnE,oBAAoB;YACpB,IAAI,IAAI,IAAI,IAAI,EAAE;gBACd,MAAM,QAAQ,GAAG,IAAI,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;gBAEvD,gEAAgE;gBAChE,IAAI,WAAW,KAAK,IAAI,IAAI,CAAC,CAAC,MAAM,QAAQ,CAAC,gBAAgB,EAAE,CAAC,EAAE;oBAAE,OAAO,IAAI,CAAC;iBAAE;gBAElF,OAAO,QAAQ,CAAC;aACnB;YAED,sBAAsB;YACtB,WAAW,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAC3D;IACL,CAAC;CACJ;AA/XD,kCA+XC"} \ No newline at end of file diff --git a/lib.commonjs/providers/formatter.js b/lib.commonjs/providers/formatter.js new file mode 100644 index 000000000..35a1f377b --- /dev/null +++ b/lib.commonjs/providers/formatter.js @@ -0,0 +1,389 @@ +"use strict"; +// Belongs to Networks; requires abstract-provider +// provider requires abstract-provider and network +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Formatter = void 0; +/** + * Formatter + * + * This is responsibile for converting much of the various + * loose network values into a concrete ethers-ready value. + * + * For example, converting addresses to checksum addresses, + * validating a hash is 32 bytes, and so on. + * + * By sub-classing this class and providing it in a custom + * Network object this allows exotic (non-Ethereum) networks + * to be fairly simple to adapt to ethers. + */ +const index_js_1 = require("../address/index.js"); +const data_js_1 = require("../utils/data.js"); +const maths_js_1 = require("../utils/maths.js"); +const logger_js_1 = require("../utils/logger.js"); +const signature_js_1 = require("../crypto/signature.js"); +const index_js_2 = require("../transaction/index.js"); +const provider_js_1 = require("./provider.js"); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +//export type AccessListSet = { address: string, storageKeys: Array }; +//export type AccessList = Array; +//export type AccessListish = AccessList | +// Array<[ string, Array ]> | +// Record>; +function stringify(value) { + if (typeof (value) !== "string") { + throw new Error("invalid string"); + } + return value; +} +class Formatter { + #format; + #baseBlock; + constructor() { + const address = this.address.bind(this); + const bigNumber = this.bigNumber.bind(this); + const blockTag = this.blockTag.bind(this); + const data = this.data.bind(this); + const hash = this.hash.bind(this); + const number = this.number.bind(this); + const uint256 = this.uint256.bind(this); + const topics = this.arrayOf(hash); + this.#format = { + address, + bigNumber, + blockTag, + data, + hash, + number, + uint256, + topics, + filter: this.object({ + fromBlock: this.allowNull(blockTag, undefined), + toBlock: this.allowNull(blockTag, undefined), + blockHash: this.allowNull(hash, undefined), + address: this.allowNull(address, undefined), + topics: this.allowNull(topics, undefined) + }), + transactionRequest: this.object({ + from: this.allowNull(address), + type: this.allowNull(number), + to: this.allowNull(address), + nonce: this.allowNull(number), + gasLimit: this.allowNull(uint256), + gasPrice: this.allowNull(uint256), + maxFeePerGas: this.allowNull(uint256), + maxPriorityFeePerGas: this.allowNull(uint256), + data: this.allowNull(data), + value: this.allowNull(uint256), + }), + transactionResponse: this.object({ + hash: hash, + index: number, + type: this.allowNull(number, 0), + // These can be null for pending blocks + blockHash: this.allowNull(hash), + blockNumber: this.allowNull(number), + // For Legacy transactions, this comes from the v + chainId: this.allowNull(number), + from: address, + to: this.address, + gasLimit: bigNumber, + gasPrice: this.allowNull(bigNumber), + maxFeePerGas: this.allowNull(bigNumber), + maxPriorityFeePerGas: this.allowNull(bigNumber), + value: bigNumber, + data: data, + nonce: number, + r: hash, + s: hash, + v: number, + accessList: this.allowNull(this.accessList) + }, { + index: ["transactionIndex"] + }), + }; + this.#baseBlock = this.object({ + number: number, + hash: this.allowNull(hash, null), + timestamp: number, + parentHash: hash, + nonce: this.allowNull(stringify, "0x0000000000000000"), + difficulty: bigNumber, + gasLimit: bigNumber, + gasUsed: bigNumber, + miner: this.allowNull(address, "0x0000000000000000000000000000000000000000"), + extraData: stringify, + baseFeePerGas: this.allowNull(bigNumber), + }); + } + // An address + address(value) { + return (0, index_js_1.getAddress)(value); + } + // An address from a call result; may be zero-padded + callAddress(value) { + if ((0, data_js_1.dataLength)(value) !== 32 || (0, data_js_1.dataSlice)(value, 0, 12) !== "0x000000000000000000000000") { + logger_js_1.logger.throwArgumentError("invalid call address", "value", value); + } + return this.address((0, data_js_1.dataSlice)(value, 12)); + } + // An address from a transaction (e.g. { from: string, nonce: number }) + contractAddress(value) { + return (0, index_js_1.getCreateAddress)({ + from: this.address(value.from), + nonce: logger_js_1.logger.getNumber(value.nonce, "value.nonce") + }); + } + // Block Tag + blockTag(value) { + if (value == null) { + return "latest"; + } + switch (value) { + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return value; + } + if (typeof (value) === "number" || ((0, data_js_1.isHexString)(value) && (0, data_js_1.dataLength)(value) < 32)) { + return (0, maths_js_1.toQuantity)(value); + } + return logger_js_1.logger.throwArgumentError("invalid blockTag", "value", value); + } + // Block objects + block(value, provider) { + const params = this.#baseBlock(value); + params.transactions = value.transactions.map((t) => this.hash(t)); + return new provider_js_1.Block(params, provider); + } + blockWithTransactions(value, provider) { + throw new Error(); + } + // Transactions + transactionRequest(value, provider) { + return this.#format.transactionRequest(value); + } + transactionResponse(value, provider) { + value = Object.assign({}, value); + // @TODO: Use the remap feature + if (value.data == null && value.input != null) { + value.data = value.input; + } + if (value.gasLimit == null && value.gas) { + value.gasLimit = value.gas; + } + value = this.#format.transactionResponse(value); + const sig = signature_js_1.Signature.from({ r: value.r, s: value.s, v: value.v }); + value.signature = sig; + if (value.chainId == null) { + value.chainId = sig.legacyChainId; + } + return new provider_js_1.TransactionResponse(value, provider); + } + // Receipts + log(value, provider) { + const log = this.object({ + address: this.address, + blockHash: this.hash, + blockNumber: this.number, + data: this.data, + index: this.number, + removed: this.boolean, + topics: this.topics, + transactionHash: this.hash, + transactionIndex: this.number, + }, { + index: ["logIndex"] + })(value); + return new provider_js_1.Log(log, provider); + } + receipt(value, provider) { + const receipt = this.object({ + blockHash: this.hash, + blockNumber: this.number, + contractAddress: this.allowNull(this.address), + cumulativeGasUsed: this.bigNumber, + from: this.address, + gasUsed: this.bigNumber, + logs: this.arrayOf((v) => (this.log(v, provider))), + logsBloom: this.data, + root: this.allowNull(this.data), + status: this.allowNull(this.number), + to: this.address, + gasPrice: this.allowNull(this.bigNumber), + hash: this.hash, + index: this.number, + type: this.allowNull(this.number, 0), + }, { + hash: ["transactionHash"], + gasPrice: ["effectiveGasPrice"], + index: ["transactionIndex"] + })(value); + // RSK incorrectly implemented EIP-658, so we munge things a bit here for it + if (receipt.root != null) { + if (receipt.root.length <= 4) { + // Could be 0x00, 0x0, 0x01 or 0x1 + const value = parseInt(receipt.root); + if (value === 0 || value === 1) { + // Make sure if both are specified, they match + if (receipt.status != null && receipt.status !== value) { + return logger_js_1.logger.throwError("alt-root-status/status mismatch", "BAD_DATA", { + value: { root: receipt.root, status: receipt.status } + }); + } + receipt.status = value; + delete receipt.root; + } + else { + return logger_js_1.logger.throwError("invalid alt-root-status", "BAD_DATA", { + value: receipt.root + }); + } + } + else if (!(0, data_js_1.isHexString)(receipt.root, 32)) { + // Must be a valid bytes32 + return logger_js_1.logger.throwError("invalid receipt root hash", "BAD_DATA", { + value: receipt.root + }); + } + } + //receipt.byzantium = (receipt.root == null); + return new provider_js_1.TransactionReceipt(receipt, provider); + } + // Fitlers + topics(value) { + return this.#format.topics(value); + } + filter(value) { + return this.#format.filter(value); + } + filterLog(value) { + console.log("ME", value); + return null; + } + // Converts a serialized transaction to a TransactionResponse + transaction(value) { + throw new Error(); + } + // Useful utility formatters functions, which if need be use the + // methods within the formatter to ensure internal compatibility + // Access List; converts an AccessListish to an AccessList + accessList(value) { + return (0, index_js_2.accessListify)(value); + } + // Converts falsish values to a specific value, otherwise use the formatter. Calls preserve `this`. + allowFalsish(format, ifFalse) { + return ((value) => { + if (!value) { + return ifFalse; + } + return format.call(this, value); + }); + } + // Allows null, optionally replacing it with a default value. Calls preserve `this`. + allowNull(format, ifNull) { + return ((value) => { + if (value == null) { + return ifNull; + } + return format.call(this, value); + }); + } + // Requires an Array satisfying the formatter. Calls preserves `this`. + arrayOf(format) { + return ((array) => { + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + return array.map((i) => format.call(this, i)); + }); + } + // Requires a value which is a value BigNumber + bigNumber(value) { + return logger_js_1.logger.getBigInt(value, "value"); + } + uint256(value) { + const result = this.bigNumber(value); + if (result < 0 || result > BN_MAX_UINT256) { + logger_js_1.logger.throwArgumentError("invalid uint256", "value", value); + } + return result; + } + // Requires a value which is a value boolean or string equivalent + boolean(value) { + switch (value) { + case true: + case "true": + return true; + case false: + case "false": + return false; + } + return logger_js_1.logger.throwArgumentError(`invalid boolean; ${JSON.stringify(value)}`, "value", value); + } + // Requires a value which is a valid hexstring. If dataOrLength is true, + // the length must be even (i.e. a datahexstring) or if it is a number, + // specifies teh number of bytes value must represent + _hexstring(dataOrLength) { + if (dataOrLength == null) { + dataOrLength = false; + } + return (function (value) { + if ((0, data_js_1.isHexString)(value, dataOrLength)) { + return value.toLowerCase(); + } + throw new Error("bad hexstring"); + }); + } + data(value) { + if ((0, data_js_1.dataLength)(value) == null) { + logger_js_1.logger.throwArgumentError("", "value", value); + } + return value; + } + // Requires a network-native hash + hash(value) { + if ((0, data_js_1.dataLength)(value) !== 32) { + logger_js_1.logger.throwArgumentError("", "value", value); + } + return this.#format.data(value); + } + // Requires a valid number, within the IEEE 754 safe range + number(value) { + return logger_js_1.logger.getNumber(value); + } + // Requires an object which matches a fleet of other formatters + // Any FormatFunc may return `undefined` to have the value omitted + // from the result object. Calls preserve `this`. + object(format, altNames) { + return ((value) => { + const result = {}; + for (const key in format) { + let srcKey = key; + if (altNames && key in altNames && !(srcKey in value)) { + for (const altKey of altNames[key]) { + if (altKey in value) { + srcKey = altKey; + break; + } + } + } + try { + const nv = format[key].call(this, value[srcKey]); + if (nv !== undefined) { + result[key] = nv; + } + } + catch (error) { + const message = (error instanceof Error) ? error.message : "not-an-error"; + logger_js_1.logger.throwError(`invalid value for value.${key} (${message})`, "BAD_DATA", { value }); + } + } + return result; + }); + } +} +exports.Formatter = Formatter; +//# sourceMappingURL=formatter.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/formatter.js.map b/lib.commonjs/providers/formatter.js.map new file mode 100644 index 000000000..51c1dc3f7 --- /dev/null +++ b/lib.commonjs/providers/formatter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatter.js","sourceRoot":"","sources":["../../src.ts/providers/formatter.ts"],"names":[],"mappings":";AAAA,kDAAkD;AAClD,kDAAkD;;;AAElD;;;;;;;;;;;;GAYG;AAEH,kDAAmE;AACnE,8CAAsE;AACtE,gDAA+C;AAC/C,kDAA4C;AAC5C,yDAAmD;AACnD,sDAAwD;AAExD,+CAAoF;AAQpF,MAAM,cAAc,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAIpG,8EAA8E;AAC9E,gDAAgD;AAEhD,0CAA0C;AAC1C,gEAAgE;AAChE,4DAA4D;AAE5D,SAAS,SAAS,CAAC,KAAU;IACzB,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;KAAE;IACtE,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,MAAa,SAAS;IAClB,OAAO,CAYL;IAEF,UAAU,CAAa;IAEvB;QACI,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACxC,MAAM,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,SAAS,EAAE;wBAAE,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;qBAAE;iBAC9C;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,OAAO,GAAG,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAA,CAAC,CAAC,cAAc,CAAC;oBACzE,kBAAM,CAAC,UAAU,CAAC,2BAA4B,GAAI,KAAM,OAAQ,GAAG,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;iBAC9F;aACJ;YACD,OAAO,MAAM,CAAC;QAClB,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAzYD,8BAyYC"} \ No newline at end of file diff --git a/lib.commonjs/providers/index.js b/lib.commonjs/providers/index.js new file mode 100644 index 000000000..b8ca36a28 --- /dev/null +++ b/lib.commonjs/providers/index.js @@ -0,0 +1,61 @@ +"use strict"; +/* +export { + AbstractProvider, UnmanagedSubscriber +} from "./abstract-provider.js"; +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketProvider = exports.SocketProvider = exports.IpcSocketProvider = exports.InfuraProvider = exports.EtherscanProvider = exports.CloudflareProvider = exports.AnkrProvider = exports.AlchemyProvider = exports.JsonRpcSigner = exports.JsonRpcProvider = exports.JsonRpcApiProvider = exports.FallbackProvider = exports.copyRequest = exports.dummyProvider = exports.TransactionResponse = exports.TransactionReceipt = exports.Log = exports.FeeData = exports.Block = exports.EnsPlugin = exports.GasCostPlugin = exports.NetworkPlugin = exports.Network = exports.Formatter = exports.WrappedSigner = exports.VoidSigner = exports.AbstractSigner = void 0; +var abstract_signer_js_1 = require("./abstract-signer.js"); +Object.defineProperty(exports, "AbstractSigner", { enumerable: true, get: function () { return abstract_signer_js_1.AbstractSigner; } }); +Object.defineProperty(exports, "VoidSigner", { enumerable: true, get: function () { return abstract_signer_js_1.VoidSigner; } }); +Object.defineProperty(exports, "WrappedSigner", { enumerable: true, get: function () { return abstract_signer_js_1.WrappedSigner; } }); +/* +export { + showThrottleMessage +} from "./community.js"; + +export { getDefaultProvider } from "./default-provider.js"; + +export { EnsResolver } from "./ens-resolver.js"; +*/ +var formatter_js_1 = require("./formatter.js"); +Object.defineProperty(exports, "Formatter", { enumerable: true, get: function () { return formatter_js_1.Formatter; } }); +var common_networks_js_1 = require("./common-networks.js"); +Object.defineProperty(exports, "Network", { enumerable: true, get: function () { return common_networks_js_1.Network; } }); +var plugins_network_js_1 = require("./plugins-network.js"); +Object.defineProperty(exports, "NetworkPlugin", { enumerable: true, get: function () { return plugins_network_js_1.NetworkPlugin; } }); +Object.defineProperty(exports, "GasCostPlugin", { enumerable: true, get: function () { return plugins_network_js_1.GasCostPlugin; } }); +Object.defineProperty(exports, "EnsPlugin", { enumerable: true, get: function () { return plugins_network_js_1.EnsPlugin; } }); +var provider_js_1 = require("./provider.js"); +Object.defineProperty(exports, "Block", { enumerable: true, get: function () { return provider_js_1.Block; } }); +Object.defineProperty(exports, "FeeData", { enumerable: true, get: function () { return provider_js_1.FeeData; } }); +Object.defineProperty(exports, "Log", { enumerable: true, get: function () { return provider_js_1.Log; } }); +Object.defineProperty(exports, "TransactionReceipt", { enumerable: true, get: function () { return provider_js_1.TransactionReceipt; } }); +Object.defineProperty(exports, "TransactionResponse", { enumerable: true, get: function () { return provider_js_1.TransactionResponse; } }); +Object.defineProperty(exports, "dummyProvider", { enumerable: true, get: function () { return provider_js_1.dummyProvider; } }); +Object.defineProperty(exports, "copyRequest", { enumerable: true, get: function () { return provider_js_1.copyRequest; } }); +var provider_fallback_js_1 = require("./provider-fallback.js"); +Object.defineProperty(exports, "FallbackProvider", { enumerable: true, get: function () { return provider_fallback_js_1.FallbackProvider; } }); +var provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +Object.defineProperty(exports, "JsonRpcApiProvider", { enumerable: true, get: function () { return provider_jsonrpc_js_1.JsonRpcApiProvider; } }); +Object.defineProperty(exports, "JsonRpcProvider", { enumerable: true, get: function () { return provider_jsonrpc_js_1.JsonRpcProvider; } }); +Object.defineProperty(exports, "JsonRpcSigner", { enumerable: true, get: function () { return provider_jsonrpc_js_1.JsonRpcSigner; } }); +var provider_alchemy_js_1 = require("./provider-alchemy.js"); +Object.defineProperty(exports, "AlchemyProvider", { enumerable: true, get: function () { return provider_alchemy_js_1.AlchemyProvider; } }); +var provider_ankr_js_1 = require("./provider-ankr.js"); +Object.defineProperty(exports, "AnkrProvider", { enumerable: true, get: function () { return provider_ankr_js_1.AnkrProvider; } }); +var provider_cloudflare_js_1 = require("./provider-cloudflare.js"); +Object.defineProperty(exports, "CloudflareProvider", { enumerable: true, get: function () { return provider_cloudflare_js_1.CloudflareProvider; } }); +var provider_etherscan_js_1 = require("./provider-etherscan.js"); +Object.defineProperty(exports, "EtherscanProvider", { enumerable: true, get: function () { return provider_etherscan_js_1.EtherscanProvider; } }); +var provider_infura_js_1 = require("./provider-infura.js"); +Object.defineProperty(exports, "InfuraProvider", { enumerable: true, get: function () { return provider_infura_js_1.InfuraProvider; } }); +//export { PocketProvider } from "./provider-pocket.js"; +const provider_ipcsocket_js_1 = require("./provider-ipcsocket.js"); /*-browser*/ +Object.defineProperty(exports, "IpcSocketProvider", { enumerable: true, get: function () { return provider_ipcsocket_js_1.IpcSocketProvider; } }); +var provider_socket_js_1 = require("./provider-socket.js"); +Object.defineProperty(exports, "SocketProvider", { enumerable: true, get: function () { return provider_socket_js_1.SocketProvider; } }); +var provider_websocket_js_1 = require("./provider-websocket.js"); +Object.defineProperty(exports, "WebSocketProvider", { enumerable: true, get: function () { return provider_websocket_js_1.WebSocketProvider; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/index.js.map b/lib.commonjs/providers/index.js.map new file mode 100644 index 000000000..cf491cec0 --- /dev/null +++ b/lib.commonjs/providers/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/providers/index.ts"],"names":[],"mappings":";AAAA;;;;EAIE;;;AAEF,2DAI8B;AAH1B,oHAAA,cAAc,OAAA;AACd,gHAAA,UAAU,OAAA;AACV,mHAAA,aAAa,OAAA;AAEjB;;;;;;;;EAQE;AAEF,+CAA2C;AAAlC,yGAAA,SAAS,OAAA;AAElB,2DAA+C;AAAtC,6GAAA,OAAO,OAAA;AAEhB,2DAO8B;AAN1B,mHAAA,aAAa,OAAA;AACb,mHAAA,aAAa,OAAA;AACb,+GAAA,SAAS,OAAA;AAMb,6CAWuB;AAVnB,oGAAA,KAAK,OAAA;AACL,sGAAA,OAAO,OAAA;AACP,kGAAA,GAAG,OAAA;AACH,iHAAA,kBAAkB,OAAA;AAClB,kHAAA,mBAAmB,OAAA;AAEnB,4GAAA,aAAa,OAAA;AAEb,0GAAA,WAAW,OAAA;AAIf,+DAA0D;AAAjD,wHAAA,gBAAgB,OAAA;AACzB,6DAA0F;AAAjF,yHAAA,kBAAkB,OAAA;AAAE,sHAAA,eAAe,OAAA;AAAE,oHAAA,aAAa,OAAA;AAE3D,6DAAwD;AAA/C,sHAAA,eAAe,OAAA;AACxB,uDAAkD;AAAzC,gHAAA,YAAY,OAAA;AACrB,mEAA8D;AAArD,4HAAA,kBAAkB,OAAA;AAC3B,iEAA4D;AAAnD,0HAAA,iBAAiB,OAAA;AAC1B,2DAAsD;AAA7C,oHAAA,cAAc,OAAA;AACvB,wDAAwD;AAExD,mEAA4D,CAAC,YAAY;AAChE,kGADA,yCAAiB,OACA;AAC1B,2DAAsD;AAA7C,oHAAA,cAAc,OAAA;AACvB,iEAA4D;AAAnD,0HAAA,iBAAiB,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/providers/network.js b/lib.commonjs/providers/network.js new file mode 100644 index 000000000..5b77a2191 --- /dev/null +++ b/lib.commonjs/providers/network.js @@ -0,0 +1,191 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Network = void 0; +const logger_js_1 = require("../utils/logger.js"); +const storage_js_1 = require("../utils/storage.js"); +const formatter_js_1 = require("./formatter.js"); +const plugins_network_js_1 = require("./plugins-network.js"); +/* * * * +// Networks which operation against an L2 can use this plugin to +// specify how to access L1, for the purpose of resolving ENS, +// for example. +export class LayerOneConnectionPlugin extends NetworkPlugin { + readonly provider!: Provider; +// @TODO: Rename to ChainAccess and allow for connecting to any chain + constructor(provider: Provider) { + super("org.ethers.plugins.layer-one-connection"); + defineProperties(this, { provider }); + } + + clone(): LayerOneConnectionPlugin { + return new LayerOneConnectionPlugin(this.provider); + } +} +*/ +/* * * * +export class PriceOraclePlugin extends NetworkPlugin { + readonly address!: string; + + constructor(address: string) { + super("org.ethers.plugins.price-oracle"); + defineProperties(this, { address }); + } + + clone(): PriceOraclePlugin { + return new PriceOraclePlugin(this.address); + } +} +*/ +// Networks or clients with a higher need for security (such as clients +// that may automatically make CCIP requests without user interaction) +// can use this plugin to anonymize requests or intercept CCIP requests +// to notify and/or receive authorization from the user +/* * * * +export type FetchDataFunc = (req: Frozen) => Promise; +export class CcipPreflightPlugin extends NetworkPlugin { + readonly fetchData!: FetchDataFunc; + + constructor(fetchData: FetchDataFunc) { + super("org.ethers.plugins.ccip-preflight"); + defineProperties(this, { fetchData }); + } + + clone(): CcipPreflightPlugin { + return new CcipPreflightPlugin(this.fetchData); + } +} +*/ +const Networks = new Map(); +const defaultFormatter = new formatter_js_1.Formatter(); +class Network { + #props; + constructor(name, _chainId, formatter) { + const chainId = logger_js_1.logger.getBigInt(_chainId); + if (formatter == null) { + formatter = defaultFormatter; + } + const plugins = new Map(); + this.#props = { name, chainId, formatter, plugins }; + } + toJSON() { + return { name: this.name, chainId: this.chainId }; + } + get name() { return (0, storage_js_1.getStore)(this.#props, "name"); } + set name(value) { (0, storage_js_1.setStore)(this.#props, "name", value); } + get chainId() { return (0, storage_js_1.getStore)(this.#props, "chainId"); } + set chainId(value) { (0, storage_js_1.setStore)(this.#props, "chainId", logger_js_1.logger.getBigInt(value, "chainId")); } + get formatter() { return (0, storage_js_1.getStore)(this.#props, "formatter"); } + set formatter(value) { (0, storage_js_1.setStore)(this.#props, "formatter", value); } + get plugins() { + return Array.from(this.#props.plugins.values()); + } + attachPlugin(plugin) { + if (this.isFrozen()) { + throw new Error("frozen"); + } + if (this.#props.plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#props.plugins.set(plugin.name, plugin.validate(this)); + return this; + } + getPlugin(name) { + return (this.#props.plugins.get(name)) || null; + } + // Gets a list of Plugins which match basename, ignoring any fragment + getPlugins(basename) { + return (this.plugins.filter((p) => (p.name.split("#")[0] === basename))); + } + clone() { + const clone = new Network(this.name, this.chainId, this.formatter); + this.plugins.forEach((plugin) => { + clone.attachPlugin(plugin.clone()); + }); + return clone; + } + freeze() { + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + computeIntrinsicGas(tx) { + const costs = this.getPlugin("org.ethers.gas-cost") || (new plugins_network_js_1.GasCostPlugin()); + let gas = costs.txBase; + if (tx.to == null) { + gas += costs.txCreate; + } + if (tx.data) { + for (let i = 2; i < tx.data.length; i += 2) { + if (tx.data.substring(i, i + 2) === "00") { + gas += costs.txDataZero; + } + else { + gas += costs.txDataNonzero; + } + } + } + if (tx.accessList) { + const accessList = this.formatter.accessList(tx.accessList); + for (const addr in accessList) { + gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; + } + } + return gas; + } + static from(network) { + // Default network + if (network == null) { + return Network.from("homestead"); + } + // Canonical name or chain ID + if (typeof (network) === "number") { + network = BigInt(network); + } + if (typeof (network) === "string" || typeof (network) === "bigint") { + const networkFunc = Networks.get(network); + if (networkFunc) { + return networkFunc(); + } + if (typeof (network) === "bigint") { + return new Network("unknown", network); + } + logger_js_1.logger.throwArgumentError("unknown network", "network", network); + } + // Clonable with network-like abilities + if (typeof (network.clone) === "function") { + const clone = network.clone(); + //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") { + //} + return clone; + } + // Networkish + if (typeof (network) === "object") { + if (typeof (network.name) !== "string" || typeof (network.chainId) !== "number") { + logger_js_1.logger.throwArgumentError("invalid network object name or chainId", "network", network); + } + const custom = new Network((network.name), (network.chainId)); + if (network.ensAddress || network.ensNetwork != null) { + custom.attachPlugin(new plugins_network_js_1.EnsPlugin(network.ensAddress, network.ensNetwork)); + } + //if ((network).layerOneConnection) { + // custom.attachPlugin(new LayerOneConnectionPlugin((network).layerOneConnection)); + //} + return custom; + } + return logger_js_1.logger.throwArgumentError("invalid network", "network", network); + } + static register(nameOrChainId, networkFunc) { + if (typeof (nameOrChainId) === "number") { + nameOrChainId = BigInt(nameOrChainId); + } + const existing = Networks.get(nameOrChainId); + if (existing) { + logger_js_1.logger.throwArgumentError(`conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); + } + Networks.set(nameOrChainId, networkFunc); + } +} +exports.Network = Network; +//# sourceMappingURL=network.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/network.js.map b/lib.commonjs/providers/network.js.map new file mode 100644 index 000000000..74806903c --- /dev/null +++ b/lib.commonjs/providers/network.js.map @@ -0,0 +1 @@ +{"version":3,"file":"network.js","sourceRoot":"","sources":["../../src.ts/providers/network.ts"],"names":[],"mappings":";;;AAAA,kDAA4C;AAC5C,oDAAyD;AAEzD,iDAA2C;AAC3C,6DAAgE;AA0BhE;;;;;;;;;;;;;;;;EAgBE;AAEF;;;;;;;;;;;;;EAaE;AAEF,uEAAuE;AACvE,sEAAsE;AACtE,uEAAuE;AACvE,uDAAuD;AACvD;;;;;;;;;;;;;;EAcE;AAEF,MAAM,QAAQ,GAAwC,IAAI,GAAG,EAAE,CAAC;AAEhE,MAAM,gBAAgB,GAAG,IAAI,wBAAS,EAAE,CAAC;AAEzC,MAAa,OAAO;IAChB,MAAM,CAOJ;IAEF,YAAY,IAAY,EAAE,QAAsB,EAAE,SAAqB;QACnE,MAAM,OAAO,GAAG,kBAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC3C,IAAI,SAAS,I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MAAM,CAAC,YAAY,CAAC,IAAI,8BAAS,CAAO,OAAQ,CAAC,UAAU,EAAQ,OAAQ,CAAC,UAAU,CAAC,CAAC,CAAC;aAC5F;YAED,0CAA0C;YAC1C,2FAA2F;YAC3F,GAAG;YAEH,OAAO,MAAM,CAAC;SACjB;QAED,OAAO,kBAAM,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,aAAuC,EAAE,WAA0B;QAC/E,IAAI,OAAM,CAAC,aAAa,CAAC,KAAK,QAAQ,EAAE;YAAE,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;SAAE;QAClF,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC7C,IAAI,QAAQ,EAAE;YACV,kBAAM,CAAC,kBAAkB,CAAC,2BAA4B,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAE,EAAE,EAAE,eAAe,EAAE,aAAa,CAAC,CAAC;SAC3H;QACD,QAAQ,CAAC,GAAG,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;IAC7C,CAAC;CACJ;AApJD,0BAoJC"} \ No newline at end of file diff --git a/lib.commonjs/providers/pagination.js b/lib.commonjs/providers/pagination.js new file mode 100644 index 000000000..7696f1a42 --- /dev/null +++ b/lib.commonjs/providers/pagination.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=pagination.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/pagination.js.map b/lib.commonjs/providers/pagination.js.map new file mode 100644 index 000000000..d08e925cb --- /dev/null +++ b/lib.commonjs/providers/pagination.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pagination.js","sourceRoot":"","sources":["../../src.ts/providers/pagination.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib.commonjs/providers/plugins-network.js b/lib.commonjs/providers/plugins-network.js new file mode 100644 index 000000000..ee01ca85c --- /dev/null +++ b/lib.commonjs/providers/plugins-network.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FeeDataNetworkPlugin = exports.EnsPlugin = exports.GasCostPlugin = exports.NetworkPlugin = void 0; +const properties_js_1 = require("../utils/properties.js"); +const logger_js_1 = require("../utils/logger.js"); +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +class NetworkPlugin { + name; + constructor(name) { + (0, properties_js_1.defineProperties)(this, { name }); + } + clone() { + return new NetworkPlugin(this.name); + } + validate(network) { + return this; + } +} +exports.NetworkPlugin = NetworkPlugin; +class GasCostPlugin extends NetworkPlugin { + effectiveBlock; + txBase; + txCreate; + txDataZero; + txDataNonzero; + txAccessListStorageKey; + txAccessListAddress; + constructor(effectiveBlock = 0, costs) { + super(`org.ethers.network-plugins.gas-cost#${(effectiveBlock || 0)}`); + const props = { effectiveBlock }; + function set(name, nullish) { + let value = (costs || {})[name]; + if (value == null) { + value = nullish; + } + if (typeof (value) !== "number") { + logger_js_1.logger.throwArgumentError(`invalud value for ${name}`, "costs", costs); + } + props[name] = value; + } + set("txBase", 21000); + set("txCreate", 32000); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + (0, properties_js_1.defineProperties)(this, props); + } + clone() { + return new GasCostPlugin(this.effectiveBlock, this); + } +} +exports.GasCostPlugin = GasCostPlugin; +// Networks shoudl use this plugin to specify the contract address +// and network necessary to resolve ENS names. +class EnsPlugin extends NetworkPlugin { + // The ENS contract address + address; + // The network ID that the ENS contract lives on + targetNetwork; + constructor(address, targetNetwork) { + super("org.ethers.network-plugins.ens"); + (0, properties_js_1.defineProperties)(this, { + address: (address || EnsAddress), + targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork) + }); + } + clone() { + return new EnsPlugin(this.address, this.targetNetwork); + } + validate(network) { + network.formatter.address(this.address); + return this; + } +} +exports.EnsPlugin = EnsPlugin; +/* +export class MaxPriorityFeePlugin extends NetworkPlugin { + readonly priorityFee!: bigint; + + constructor(priorityFee: BigNumberish) { + super("org.ethers.plugins.max-priority-fee"); + defineProperties(this, { + priorityFee: logger.getBigInt(priorityFee) + }); + } + + async getPriorityFee(provider: Provider): Promise { + return this.priorityFee; + } + + clone(): MaxPriorityFeePlugin { + return new MaxPriorityFeePlugin(this.priorityFee); + } +} +*/ +class FeeDataNetworkPlugin extends NetworkPlugin { + #feeDataFunc; + get feeDataFunc() { return this.#feeDataFunc; } + constructor(feeDataFunc) { + super("org.ethers.network-plugins.fee-data"); + this.#feeDataFunc = feeDataFunc; + } + async getFeeData(provider) { + return await this.#feeDataFunc(provider); + } + clone() { + return new FeeDataNetworkPlugin(this.#feeDataFunc); + } +} +exports.FeeDataNetworkPlugin = FeeDataNetworkPlugin; +//# sourceMappingURL=plugins-network.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/plugins-network.js.map b/lib.commonjs/providers/plugins-network.js.map new file mode 100644 index 000000000..8b46308ee --- /dev/null +++ b/lib.commonjs/providers/plugins-network.js.map @@ -0,0 +1 @@ +{"version":3,"file":"plugins-network.js","sourceRoot":"","sources":["../../src.ts/providers/plugins-network.ts"],"names":[],"mappings":";;;AAAA,0DAA0D;AAE1D,kDAA4C;AAQ5C,MAAM,UAAU,GAAG,4CAA4C,CAAC;AAEhE,MAAa,aAAa;IACb,IAAI,CAAU;IAEvB,YAAY,IAAY;QACpB,IAAA,gCAAgB,EAAgB,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,CAAC;IAED,KAAK;QACD,OAAO,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;IAED,QAAQ,CAAC,OAAgB;QACrB,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AAdD,sCAcC;AAcD,MAAa,aAAc,SAAQ,aAAa;IACnC,cAAc,CAAU;I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,2BAA2B;IAClB,OAAO,CAAU;IAE1B,gDAAgD;IACvC,aAAa,CAAU;IAEhC,YAAY,OAAuB,EAAE,aAA6B;QAC9D,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACxC,IAAA,gCAAgB,EAAY,IAAI,EAAE;YAC9B,OAAO,EAAE,CAAC,OAAO,IAAI,UAAU,CAAC;YAChC,aAAa,EAAE,CAAC,CAAC,aAAa,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,CAAC,CAAC,aAAa,CAAC;SAC9D,CAAC,CAAC;IACP,CAAC;IAED,KAAK;QACD,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IAC3D,CAAC;IAED,QAAQ,CAAC,OAAgB;QACrB,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACxC,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AAxBD,8BAwBC;AACD;;;;;;;;;;;;;;;;;;;EAmBE;AACF,MAAa,oBAAqB,SAAQ,aAAa;IAC1C,YAAY,CAA2C;IAEhE,IAAI,WAAW,KAA+C,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;IAEzF,YAAY,WAAqD;QAC7D,KAAK,CAAC,qCAAqC,CAAC,CAAC;QAC7C,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IACpC,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAkB;QAC/B,OAAO,MAAM,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK;QACD,OAAO,IAAI,oBAAoB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvD,CAAC;CACJ;AAjBD,oDAiBC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-alchemy.js b/lib.commonjs/providers/provider-alchemy.js new file mode 100644 index 000000000..dfdb9f190 --- /dev/null +++ b/lib.commonjs/providers/provider-alchemy.js @@ -0,0 +1,101 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AlchemyProvider = void 0; +const properties_js_1 = require("../utils/properties.js"); +const fetch_js_1 = require("../utils/fetch.js"); +const community_js_1 = require("./community.js"); +const logger_js_1 = require("../utils/logger.js"); +const network_js_1 = require("./network.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; +function getHost(name) { + switch (name) { + case "homestead": + return "eth-mainnet.alchemyapi.io"; + case "ropsten": + return "eth-ropsten.alchemyapi.io"; + case "rinkeby": + return "eth-rinkeby.alchemyapi.io"; + case "goerli": + return "eth-goerli.alchemyapi.io"; + case "kovan": + return "eth-kovan.alchemyapi.io"; + case "matic": + return "polygon-mainnet.g.alchemy.com"; + case "maticmum": + return "polygon-mumbai.g.alchemy.com"; + case "arbitrum": + return "arb-mainnet.g.alchemy.com"; + case "arbitrum-rinkeby": + return "arb-rinkeby.g.alchemy.com"; + case "optimism": + return "opt-mainnet.g.alchemy.com"; + case "optimism-kovan": + return "opt-kovan.g.alchemy.com"; + } + return logger_js_1.logger.throwArgumentError("unsupported network", "network", name); +} +class AlchemyProvider extends provider_jsonrpc_js_1.JsonRpcProvider { + apiKey; + constructor(_network = "homestead", apiKey) { + const network = network_js_1.Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = AlchemyProvider.getRequest(network, apiKey); + super(request, network, { staticNetwork: network }); + (0, properties_js_1.defineProperties)(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AlchemyProvider(chainId, this.apiKey); + } + catch (error) { } + return super._getProvider(chainId); + } + async _perform(req) { + // https://docs.alchemy.com/reference/trace-transaction + if (req.method === "getTransactionResult") { + const trace = await this.send("trace_transaction", [req.hash]); + if (trace == null) { + return null; + } + let data; + let error = false; + try { + data = trace[0].result.output; + error = (trace[0].error === "Reverted"); + } + catch (error) { } + if (data) { + if (error) { + logger_js_1.logger.throwError("an error occurred during transaction executions", "CALL_EXCEPTION", { + data + }); + } + return data; + } + return logger_js_1.logger.throwError("could not parse trace result", "BAD_DATA", { value: trace }); + } + return await super._perform(req); + } + isCommunityResource() { + return (this.apiKey === defaultApiKey); + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = new fetch_js_1.FetchRequest(`https:/\/${getHost(network.name)}/v2/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request, response, attempt) => { + (0, community_js_1.showThrottleMessage)("alchemy"); + return true; + }; + } + return request; + } +} +exports.AlchemyProvider = AlchemyProvider; +//# sourceMappingURL=provider-alchemy.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-alchemy.js.map b/lib.commonjs/providers/provider-alchemy.js.map new file mode 100644 index 000000000..52ddc4037 --- /dev/null +++ b/lib.commonjs/providers/provider-alchemy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-alchemy.js","sourceRoot":"","sources":["../../src.ts/providers/provider-alchemy.ts"],"names":[],"mappings":";;;AACA,0DAA0D;AAC1D,gDAAiD;AAEjD,iDAAqD;AACrD,kDAA4C;AAC5C,6CAAuC;AACvC,+DAAwD;AAOxD,MAAM,aAAa,GAAG,kCAAkC,CAAA;AAExD,SAAS,OAAO,CAAC,IAAY;IACzB,QAAO,IAAI,EAAE;QACT,KAAK,WAAW;YACZ,OAAO,2BAA2B,CAAC;QACvC,KAAK,SAAS;YACV,OAAO,2BAA2B,CAAC;QACvC,KAAK,SAAS;YACV,OAAO,2BAA2B,CAAC;QACvC,KAAK,QAAQ;YACT,OAAO,0BAA0B,CAAC;QACtC,KAAK,OAAO;YACR,OAAO,yBAAyB,CAAC;QACrC,KAAK,OAAO;YACR,OAAO,+BAA+B,CAAC;QAC3C,KAAK,UAAU;YACX,OAAO,8BAA8B,CAAC;QAC1C,KAAK,UAAU;YACX,OAAO,2BAA2B,CAAC;QACvC,KAAK,kBAA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} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-ankr.js b/lib.commonjs/providers/provider-ankr.js new file mode 100644 index 000000000..4700a914a --- /dev/null +++ b/lib.commonjs/providers/provider-ankr.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AnkrProvider = void 0; +const properties_js_1 = require("../utils/properties.js"); +const fetch_js_1 = require("../utils/fetch.js"); +const community_js_1 = require("./community.js"); +const logger_js_1 = require("../utils/logger.js"); +const network_js_1 = require("./network.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +const defaultApiKey = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; +function getHost(name) { + switch (name) { + case "homestead": + return "rpc.ankr.com/eth"; + case "ropsten": + return "rpc.ankr.com/eth_ropsten"; + case "rinkeby": + return "rpc.ankr.com/eth_rinkeby"; + case "goerli": + return "rpc.ankr.com/eth_goerli"; + case "matic": + return "rpc.ankr.com/polygon"; + case "arbitrum": + return "rpc.ankr.com/arbitrum"; + } + return logger_js_1.logger.throwArgumentError("unsupported network", "network", name); +} +class AnkrProvider extends provider_jsonrpc_js_1.JsonRpcProvider { + apiKey; + constructor(_network = "homestead", apiKey) { + const network = network_js_1.Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey; + } + // Ankr does not support filterId, so we force polling + const options = { polling: true, staticNetwork: network }; + const request = AnkrProvider.getRequest(network, apiKey); + super(request, network, options); + (0, properties_js_1.defineProperties)(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AnkrProvider(chainId, this.apiKey); + } + catch (error) { } + return super._getProvider(chainId); + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = new fetch_js_1.FetchRequest(`https:/\/${getHost(network.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request, response, attempt) => { + (0, community_js_1.showThrottleMessage)("AnkrProvider"); + return true; + }; + } + return request; + } + isCommunityResource() { + return (this.apiKey === defaultApiKey); + } +} +exports.AnkrProvider = AnkrProvider; +//# sourceMappingURL=provider-ankr.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-ankr.js.map b/lib.commonjs/providers/provider-ankr.js.map new file mode 100644 index 000000000..392d4c494 --- /dev/null +++ b/lib.commonjs/providers/provider-ankr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ankr.js","sourceRoot":"","sources":["../../src.ts/providers/provider-ankr.ts"],"names":[],"mappings":";;;AAAA,0DAA0D;AAC1D,gDAAiD;AAGjD,iDAAqD;AACrD,kDAA4C;AAC5C,6CAAuC;AACvC,+DAAwD;AAMxD,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEzF,SAAS,OAAO,CAAC,IAAY;IACzB,QAAQ,IAAI,EAAE;QACV,KAAK,WAAW;YACZ,OAAO,kBAAkB,CAAC;QAC9B,KAAK,SAAS;YACV,OAAO,0BAA0B,CAAC;QACtC,KAAK,SAAS;YACV,OAAO,0BAA0B,CAAC;QACtC,KAAK,QAAQ;YACT,OAAO,yBAAyB,CAAC;QACrC,KAAK,OAAO;YACR,OAAO,sBAAsB,CAAC;QAClC,KAAK,UAAU;YACX,OAAO,uBAAuB,CAAC;KACtC;IACD,OAAO,kBAAM,CAAC,kBAAkB,CAAC,qBAAqB,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAC7E,CAAC;AAGD,MAAa,YAAa,SAAQ,qCAAe;IACpC,MAAM,CAAU;IAEzB,YAAY,WAAuB,WAAW,EAAE,MAAsB;QAClE,MAAM,OAAO,GAAG,oBAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACvC,IAAI,MAAM,IAAI,IAAI,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC;SAAE;QAE/C,sDAAsD;QACtD,MAAM,OAAO,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;QAE1D,MAAM,OAAO,GAAG,YAAY,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACzD,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAA,gCAAgB,EAAe,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACrD,CAAC;IAED,YAAY,CAAC,OAAe;QACxB,IAAI;YACA,OAAO,IAAI,YAAY,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;SACjD;QAAC,OAAO,KAAK,EAAE,GAAG;QACnB,OAAO,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,OAAgB,EAAE,MAAsB;QACtD,IAAI,MAAM,IAAI,IAAI,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC;SAAE;QAE/C,MAAM,OAAO,GAAG,IAAI,uBAAY,CAAC,YAAa,OAAO,CAAC,OAAO,CAAC,IAAI,CAAE,IAAK,MAAO,EAAE,CAAC,CAAC;QACpF,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;QAEzB,IAAI,MAAM,KAAK,aAAa,EAAE;YAC1B,OAAO,CAAC,SAAS,GAAG,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;gBACrD,IAAA,kCAAmB,EAAC,cAAc,CAAC,CAAC;gBACpC,OAAO,IAAI,CAAC;YAChB,CAAC,CAAC;SACL;QAED,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,mBAAmB;QACf,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC,CAAC;IAC3C,CAAC;CACJ;AA1CD,oCA0CC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-cloudflare.js b/lib.commonjs/providers/provider-cloudflare.js new file mode 100644 index 000000000..d2eac542e --- /dev/null +++ b/lib.commonjs/providers/provider-cloudflare.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CloudflareProvider = void 0; +const logger_js_1 = require("../utils/logger.js"); +const network_js_1 = require("./network.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +class CloudflareProvider extends provider_jsonrpc_js_1.JsonRpcProvider { + constructor(_network = "homestead") { + const network = network_js_1.Network.from(_network); + if (network.name !== "homestead") { + return logger_js_1.logger.throwArgumentError("unsupported network", "network", _network); + } + super("https:/\/cloudflare-eth.com/", network, { staticNetwork: network }); + } +} +exports.CloudflareProvider = CloudflareProvider; +//# sourceMappingURL=provider-cloudflare.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-cloudflare.js.map b/lib.commonjs/providers/provider-cloudflare.js.map new file mode 100644 index 000000000..76e938041 --- /dev/null +++ b/lib.commonjs/providers/provider-cloudflare.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-cloudflare.js","sourceRoot":"","sources":["../../src.ts/providers/provider-cloudflare.ts"],"names":[],"mappings":";;;AACA,kDAA4C;AAC5C,6CAAuC;AACvC,+DAAwD;AAKxD,MAAa,kBAAmB,SAAQ,qCAAe;IACnD,YAAY,WAAuB,WAAW;QAC1C,MAAM,OAAO,GAAG,oBAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACvC,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE;YAC9B,OAAO,kBAAM,CAAC,kBAAkB,CAAC,qBAAqB,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;SAChF;QACD,KAAK,CAAC,8BAA8B,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ;AARD,gDAQC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-etherscan.js b/lib.commonjs/providers/provider-etherscan.js new file mode 100644 index 000000000..87549cb52 --- /dev/null +++ b/lib.commonjs/providers/provider-etherscan.js @@ -0,0 +1,468 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EtherscanProvider = exports.EtherscanPlugin = void 0; +const data_js_1 = require("../utils/data.js"); +const maths_js_1 = require("../utils/maths.js"); +const errors_js_1 = require("../utils/errors.js"); +const properties_js_1 = require("../utils/properties.js"); +const utf8_js_1 = require("../utils/utf8.js"); +const fetch_js_1 = require("../utils/fetch.js"); +if (false) { + console.log(data_js_1.isHexString, errors_js_1.isError); +} // @TODO +const abstract_provider_js_1 = require("./abstract-provider.js"); +const network_js_1 = require("./network.js"); +const plugins_network_js_1 = require("./plugins-network.js"); +const logger_js_1 = require("../utils/logger.js"); +const defaultApiKey = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB"; +const EtherscanPluginId = "org.ethers.plugins.etherscan"; +class EtherscanPlugin extends plugins_network_js_1.NetworkPlugin { + baseUrl; + communityApiKey; + constructor(baseUrl, communityApiKey) { + super(EtherscanPluginId); + //if (communityApiKey == null) { communityApiKey = null; } + (0, properties_js_1.defineProperties)(this, { baseUrl, communityApiKey }); + } + clone() { + return new EtherscanPlugin(this.baseUrl, this.communityApiKey); + } +} +exports.EtherscanPlugin = EtherscanPlugin; +class EtherscanProvider extends abstract_provider_js_1.AbstractProvider { + network; + apiKey; + constructor(_network, apiKey) { + super(); + const network = network_js_1.Network.from(_network); + if (apiKey == null) { + const plugin = network.getPlugin(EtherscanPluginId); + if (plugin) { + apiKey = plugin.communityApiKey; + } + else { + apiKey = defaultApiKey; + } + } + (0, properties_js_1.defineProperties)(this, { apiKey, network }); + // Test that the network is supported by Etherscan + this.getBaseUrl(); + } + getBaseUrl() { + const plugin = this.network.getPlugin(EtherscanPluginId); + if (plugin) { + return plugin.baseUrl; + } + switch (this.network.name) { + case "homestead": + return "https:/\/api.etherscan.io"; + case "ropsten": + return "https:/\/api-ropsten.etherscan.io"; + case "rinkeby": + return "https:/\/api-rinkeby.etherscan.io"; + case "kovan": + return "https:/\/api-kovan.etherscan.io"; + case "goerli": + return "https:/\/api-goerli.etherscan.io"; + default: + } + return logger_js_1.logger.throwArgumentError("unsupported network", "network", this.network); + } + getUrl(module, params) { + const query = Object.keys(params).reduce((accum, key) => { + const value = params[key]; + if (value != null) { + accum += `&${key}=${value}`; + } + return accum; + }, ""); + const apiKey = ((this.apiKey) ? `&apikey=${this.apiKey}` : ""); + return `${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`; + } + getPostUrl() { + return `${this.getBaseUrl()}/api`; + } + getPostData(module, params) { + params.module = module; + params.apikey = this.apiKey; + return params; + } + async detectNetwork() { + return this.network; + } + async fetch(module, params, post) { + const url = (post ? this.getPostUrl() : this.getUrl(module, params)); + const payload = (post ? this.getPostData(module, params) : null); + /* + this.emit("debug", { + action: "request", + request: url, + provider: this + }); + */ + const request = new fetch_js_1.FetchRequest(url); + request.processFunc = async (request, response) => { + const result = response.hasBody() ? JSON.parse((0, utf8_js_1.toUtf8String)(response.body)) : {}; + const throttle = ((typeof (result.result) === "string") ? result.result : "").toLowerCase().indexOf("rate limit") >= 0; + if (module === "proxy") { + // This JSON response indicates we are being throttled + if (result && result.status == 0 && result.message == "NOTOK" && throttle) { + response.throwThrottleError(result.result); + } + } + else { + if (throttle) { + response.throwThrottleError(result.result); + } + } + return response; + }; + // @TODO: + //throttleSlotInterval: 1000, + if (payload) { + request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); + request.body = Object.keys(payload).map((k) => `${k}=${payload[k]}`).join("&"); + } + const response = await request.send(); + response.assertOk(); + if (!response.hasBody()) { + throw new Error(); + } + /* + this.emit("debug", { + action: "response", + request: url, + response: deepCopy(result), + provider: this + }); + */ + const result = JSON.parse((0, utf8_js_1.toUtf8String)(response.body)); + if (module === "proxy") { + if (result.jsonrpc != "2.0") { + // @TODO: not any + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + throw error; + } + if (result.error) { + // @TODO: not any + const error = new Error(result.error.message || "unknown error"); + if (result.error.code) { + error.code = result.error.code; + } + if (result.error.data) { + error.data = result.error.data; + } + throw error; + } + return result.result; + } + else { + // getLogs, getHistory have weird success responses + if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { + return result.result; + } + if (result.status != 1 || result.message != "OK") { + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + // if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) { + // error.throttleRetry = true; + // } + throw error; + } + return result.result; + } + } + // The transaction has already been sanitized by the calls in Provider + _getTransactionPostData(transaction) { + const result = {}; + for (let key in transaction) { + if (transaction[key] == null) { + continue; + } + let value = transaction[key]; + if (key === "type" && value === 0) { + continue; + } + // Quantity-types require no leading zero, unless 0 + if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) { + value = (0, maths_js_1.toQuantity)((0, data_js_1.hexlify)(value)); + } + else if (key === "accessList") { + value = "[" + this.network.formatter.accessList(value).map((set) => { + return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; + }).join(",") + "]"; + } + else { + value = (0, data_js_1.hexlify)(value); + } + result[key] = value; + } + return result; + } + _checkError(req, error, transaction) { + /* + let body = ""; + if (isError(error, Logger.Errors.SERVER_ERROR) && error.response && error.response.hasBody()) { + body = toUtf8String(error.response.body); + } + console.log(body); + + // Undo the "convenience" some nodes are attempting to prevent backwards + // incompatibility; maybe for v6 consider forwarding reverts as errors + if (method === "call" && body) { + + // Etherscan keeps changing their string + if (body.match(/reverted/i) || body.match(/VM execution error/i)) { + + // Etherscan prefixes the data like "Reverted 0x1234" + let data = e.data; + if (data) { data = "0x" + data.replace(/^.*0x/i, ""); } + if (!isHexString(data)) { data = "0x"; } + + logger.throwError("call exception", Logger.Errors.CALL_EXCEPTION, { + error, data + }); + } + } + + // Get the message from any nested error structure + let message = error.message; + if (isError(error, Logger.Errors.SERVER_ERROR)) { + if (error.error && typeof(error.error.message) === "string") { + message = error.error.message; + } else if (typeof(error.body) === "string") { + message = error.body; + } else if (typeof(error.responseText) === "string") { + message = error.responseText; + } + } + message = (message || "").toLowerCase(); + + // "Insufficient funds. The account you tried to send transaction from + // does not have enough funds. Required 21464000000000 and got: 0" + if (message.match(/insufficient funds/)) { + logger.throwError("insufficient funds for intrinsic transaction cost", Logger.Errors.INSUFFICIENT_FUNDS, { + error, transaction, info: { method } + }); + } + + // "Transaction with the same hash was already imported." + if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { + logger.throwError("nonce has already been used", Logger.Errors.NONCE_EXPIRED, { + error, transaction, info: { method } + }); + } + + // "Transaction gas price is too low. There is another transaction with + // same nonce in the queue. Try increasing the gas price or incrementing the nonce." + if (message.match(/another transaction with same nonce/)) { + logger.throwError("replacement fee too low", Logger.Errors.REPLACEMENT_UNDERPRICED, { + error, transaction, info: { method } + }); + } + + if (message.match(/execution failed due to an exception|execution reverted/)) { + logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.Errors.UNPREDICTABLE_GAS_LIMIT, { + error, transaction, info: { method } + }); + } + */ + throw error; + } + async _detectNetwork() { + return this.network; + } + async _perform(req) { + switch (req.method) { + case "chainId": + return this.network.chainId; + case "getBlockNumber": + return this.fetch("proxy", { action: "eth_blockNumber" }); + case "getGasPrice": + return this.fetch("proxy", { action: "eth_gasPrice" }); + case "getBalance": + // Returns base-10 result + return this.fetch("account", { + action: "balance", + address: req.address, + tag: req.blockTag + }); + case "getTransactionCount": + return this.fetch("proxy", { + action: "eth_getTransactionCount", + address: req.address, + tag: req.blockTag + }); + case "getCode": + return this.fetch("proxy", { + action: "eth_getCode", + address: req.address, + tag: req.blockTag + }); + case "getStorageAt": + return this.fetch("proxy", { + action: "eth_getStorageAt", + address: req.address, + position: req.position, + tag: req.blockTag + }); + case "broadcastTransaction": + return this.fetch("proxy", { + action: "eth_sendRawTransaction", + hex: req.signedTransaction + }, true).catch((error) => { + return this._checkError(req, error, req.signedTransaction); + }); + case "getBlock": + if ("blockTag" in req) { + return this.fetch("proxy", { + action: "eth_getBlockByNumber", + tag: req.blockTag, + boolean: (req.includeTransactions ? "true" : "false") + }); + } + return logger_js_1.logger.throwError("getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", { + operation: "getBlock(blockHash)" + }); + case "getTransaction": + return this.fetch("proxy", { + action: "eth_getTransactionByHash", + txhash: req.hash + }); + case "getTransactionReceipt": + return this.fetch("proxy", { + action: "eth_getTransactionReceipt", + txhash: req.hash + }); + case "call": { + if (req.blockTag !== "latest") { + throw new Error("EtherscanProvider does not support blockTag for call"); + } + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_call"; + try { + return await this.fetch("proxy", postData, true); + } + catch (error) { + return this._checkError(req, error, req.transaction); + } + } + case "estimateGas": { + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_estimateGas"; + try { + return await this.fetch("proxy", postData, true); + } + catch (error) { + return this._checkError(req, error, req.transaction); + } + } + /* + case "getLogs": { + // Needs to complain if more than one address is passed in + const args: Record = { action: "getLogs" } + + if (params.filter.fromBlock) { + args.fromBlock = checkLogTag(params.filter.fromBlock); + } + + if (params.filter.toBlock) { + args.toBlock = checkLogTag(params.filter.toBlock); + } + + if (params.filter.address) { + args.address = params.filter.address; + } + + // @TODO: We can handle slightly more complicated logs using the logs API + if (params.filter.topics && params.filter.topics.length > 0) { + if (params.filter.topics.length > 1) { + logger.throwError("unsupported topic count", Logger.Errors.UNSUPPORTED_OPERATION, { topics: params.filter.topics }); + } + if (params.filter.topics.length === 1) { + const topic0 = params.filter.topics[0]; + if (typeof(topic0) !== "string" || topic0.length !== 66) { + logger.throwError("unsupported topic format", Logger.Errors.UNSUPPORTED_OPERATION, { topic0: topic0 }); + } + args.topic0 = topic0; + } + } + + const logs: Array = await this.fetch("logs", args); + + // Cache txHash => blockHash + let blocks: { [tag: string]: string } = {}; + + // Add any missing blockHash to the logs + for (let i = 0; i < logs.length; i++) { + const log = logs[i]; + if (log.blockHash != null) { continue; } + if (blocks[log.blockNumber] == null) { + const block = await this.getBlock(log.blockNumber); + if (block) { + blocks[log.blockNumber] = block.hash; + } + } + + log.blockHash = blocks[log.blockNumber]; + } + + return logs; + } + */ + default: + break; + } + return super._perform(req); + } + async getNetwork() { + return this.network; + } + async getEtherPrice() { + if (this.network.name !== "homestead") { + return 0.0; + } + return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd); + } + isCommunityResource() { + const plugin = this.network.getPlugin(EtherscanPluginId); + if (plugin) { + return (plugin.communityApiKey === this.apiKey); + } + return (defaultApiKey === this.apiKey); + } +} +exports.EtherscanProvider = EtherscanProvider; +/* +(async function() { + const provider = new EtherscanProvider(); + console.log(provider); + console.log(await provider.getBlockNumber()); + / * + provider.on("block", (b) => { + console.log("BB", b); + }); + console.log(await provider.getTransactionReceipt("0xa5ded92f548e9f362192f9ab7e5b3fbc9b5a919a868e29247f177d49ce38de6e")); + + provider.once("0xa5ded92f548e9f362192f9ab7e5b3fbc9b5a919a868e29247f177d49ce38de6e", (tx) => { + console.log("TT", tx); + }); + * / + try { + console.log(await provider.getBlock(100)); + } catch (error) { + console.log(error); + } + + try { + console.log(await provider.getBlock(13821768)); + } catch (error) { + console.log(error); + } + +})(); +*/ +//# sourceMappingURL=provider-etherscan.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-etherscan.js.map b/lib.commonjs/providers/provider-etherscan.js.map new file mode 100644 index 000000000..0cead5ee4 --- /dev/null +++ b/lib.commonjs/providers/provider-etherscan.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-etherscan.js","sourceRoot":"","sources":["../../src.ts/providers/provider-etherscan.ts"],"names":[],"mappings":";;;AAAA,8CAAwD;AACxD,gDAA+C;AAC/C,kDAA6C;AAC7C,0DAA0D;AAC1D,8CAAgD;AAChD,gDAAiD;AAEjD,IAAI,KAAK,EAAE;IAAE,OAAO,CAAC,GAAG,CAAC,qBAAW,EAAE,mBAAO,CAAC,CAAC;CAAE,CAAC,QAAQ;AAE1D,iEAA0D;AAC1D,6CAAuC;AACvC,6DAAqD;AAQrD,kDAA4C;AAG5C,MAAM,aAAa,GAAG,oCAA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AC3C,CAAC;CACJ;AAnbD,8CAmbC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4BE"} \ 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 000000000..d5655e068 --- /dev/null +++ b/lib.commonjs/providers/provider-fallback.js @@ -0,0 +1,417 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FallbackProvider = void 0; +const data_js_1 = require("../utils/data.js"); +const abstract_provider_js_1 = require("./abstract-provider.js"); +const logger_js_1 = require("../utils/logger.js"); +const network_js_1 = require("./network.js"); +//const BN_0 = BigInt("0"); +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(); } +; +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 +}; +async function waitForSync(config, blockNumber) { + while (config.blockNumber < 0 || config.blockNumber < blockNumber) { + if (!config._updateNumber) { + config._updateNumber = (async () => { + const blockNumber = await config.provider.getBlockNumber(); + if (blockNumber > config.blockNumber) { + config.blockNumber = blockNumber; + } + config._updateNumber = null; + })(); + } + await config._updateNumber; + config.outOfSync++; + } +} +// Normalizes a result to a string that can be used to compare against +// other results using normal string equality +function normalize(network, value, req) { + switch (req.method) { + case "chainId": + return logger_js_1.logger.getBigInt(value).toString(); + case "getBlockNumber": + return logger_js_1.logger.getNumber(value).toString(); + case "getGasPrice": + return logger_js_1.logger.getBigInt(value).toString(); + case "getBalance": + return logger_js_1.logger.getBigInt(value).toString(); + case "getTransactionCount": + return logger_js_1.logger.getNumber(value).toString(); + case "getCode": + return (0, data_js_1.hexlify)(value); + case "getStorageAt": + return (0, data_js_1.hexlify)(value); + case "getBlock": + if (req.includeTransactions) { + return JSON.stringify(network.formatter.blockWithTransactions(value)); + } + return JSON.stringify(network.formatter.block(value)); + case "getTransaction": + return JSON.stringify(network.formatter.transactionResponse(value)); + case "getTransactionReceipt": + return JSON.stringify(network.formatter.receipt(value)); + case "call": + return (0, data_js_1.hexlify)(value); + case "estimateGas": + return logger_js_1.logger.getBigInt(value).toString(); + case "getLogs": + return JSON.stringify(value.map((v) => network.formatter.log(v))); + } + return logger_js_1.logger.throwError("unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${JSON.stringify(req.method)})` + }); +} +// This strategy picks the highest wieght result, as long as the weight is +// equal to or greater than quorum +function checkQuorum(quorum, results) { + const tally = new Map(); + for (const { result, normal, weight } of results) { + const t = tally.get(normal) || { result, weight: 0 }; + t.weight += weight; + tally.set(normal, t); + } + let bestWeight = 0; + let bestResult = undefined; + for (const { weight, result } of tally.values()) { + if (weight >= quorum && weight > bestWeight) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +/* +function getMean(results: Array): bigint { + const total = results.reduce((a, r) => (a + BigInt(r.result)), BN_0); + return total / BigInt(results.length); +} +*/ +function getMedian(results) { + // Get the sorted values + const values = results.map((r) => BigInt(r.result)); + values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0)); + const mid = 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 getFuzzyMode(quorum, results) { + if (quorum === 1) { + return logger_js_1.logger.getNumber(getMedian(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, result } of results) { + const r = logger_js_1.logger.getNumber(result); + 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; +} +class FallbackProvider extends abstract_provider_js_1.AbstractProvider { + //readonly providerConfigs!: ReadonlyArray>>; + quorum; + eventQuorum; + eventWorkers; + #configs; + #height; + #initialSyncPromise; + constructor(providers, network) { + super(network); + 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; + this.quorum = 2; //Math.ceil(providers.length / 2); + this.eventQuorum = 1; + this.eventWorkers = 1; + if (this.quorum > this.#configs.reduce((a, c) => (a + c.weight), 0)) { + logger_js_1.logger.throwArgumentError("quorum exceed provider wieght", "quorum", this.quorum); + } + } + // @TOOD: Copy these and only return public values + get providerConfigs() { + return this.#configs.slice(); + } + async _detectNetwork() { + return network_js_1.Network.from(logger_js_1.logger.getBigInt(await this._perform({ method: "chainId" }))).freeze(); + } + // @TODO: Add support to select providers to be the event subscriber + //_getSubscriber(sub: Subscription): Subscriber { + // throw new Error("@TODO"); + //} + // Grab the next (random) config that is not already part of configs + #getNextConfig(configs) { + // Shuffle the states, sorted by priority + const allConfigs = this.#configs.slice(); + shuffle(allConfigs); + allConfigs.sort((a, b) => (b.priority - a.priority)); + for (const config of allConfigs) { + if (configs.indexOf(config) === -1) { + return config; + } + } + return null; + } + // Adds a new runner (if available) to running. + #addRunner(running, req) { + const config = this.#getNextConfig(Array.from(running).map((r) => r.config)); + if (config == null) { + return null; + } + const result = {}; + const runner = { + config, result, didBump: false, done: false, + perform: null, staller: null + }; + const now = getTime(); + runner.perform = (async () => { + try { + config.requests++; + result.result = await config.provider._perform(req); + } + catch (error) { + config.errorResponses++; + result.error = error; + } + if (runner.done) { + config.lateResponses++; + } + const dt = (getTime() - now); + config._totalTime += dt; + config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt; + runner.perform = null; + })(); + 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(waitForSync(config, 0)); + promises.push((async () => { + 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) { + const network = (config._network); + if (chainId == null) { + chainId = network.chainId; + } + else if (network.chainId !== chainId) { + logger_js_1.logger.throwError("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 ("result" in runner.result) { + const result = runner.result.result; + results.push({ + result, + normal: normalize((runner.config._network), result, req), + 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) { + const height = Math.ceil(logger_js_1.logger.getNumber(getMedian(this.#configs.map((c) => ({ + result: c.blockNumber, + normal: logger_js_1.logger.getNumber(c.blockNumber).toString(), + weight: c.weight + }))), "%internal")); + this.#height = height; + } + const mode = getFuzzyMode(this.quorum, results); + if (mode === undefined) { + return undefined; + } + if (mode > this.#height) { + this.#height = mode; + } + return this.#height; + } + case "getGasPrice": + case "estimateGas": + return getMedian(results); + case "getBlock": + // Pending blocks are mempool dependant and already + // quite untrustworthy + if ("blockTag" in req && req.blockTag === "pending") { + return results[0].result; + } + return checkQuorum(this.quorum, results); + case "chainId": + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorageAt": + case "getTransaction": + case "getTransactionReceipt": + case "getLogs": + return checkQuorum(this.quorum, results); + case "call": + // @TODO: Check errors + return checkQuorum(this.quorum, results); + case "broadcastTransaction": + throw new Error("TODO"); + } + return logger_js_1.logger.throwError("unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${JSON.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 = []; + //const results: Array = [ ]; + //const errors: Array = [ ]; + let newRunners = 0; + for (const runner of running) { + // @TODO: use runner.perfom != null + /* + if ("result" in runner.result) { + results.push(runner.result.result); + } else if ("error" in runner.result) { + errors.push(runner.result.error); + } +*/ + // 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 for quorum + /* + console.log({ results, errors } ); + if (results.length >= this.quorum) { + return results[0]; + } + + if (errors.length >= this.quorum) { + return errors[0]; + } + */ + 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); + } + if (interesting.length === 0) { + throw new Error("quorum not met"); + // return logger.throwError("failed to meet quorum", "", { + // }); + } + // Wait for someone to either complete its perform or trigger a stall + await Promise.race(interesting); + return await this.#waitForQuorum(running, req); + } + async _perform(req) { + await this.#initialSync(); + // Bootstrap enough to meet quorum + const running = new Set(); + for (let i = 0; i < this.quorum; i++) { + this.#addRunner(running, req); + } + const result = this.#waitForQuorum(running, req); + for (const runner of running) { + runner.done = true; + } + return result; + } +} +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 000000000..ab597c849 --- /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":";;;AACA,8CAA2C;AAE3C,iEAA0D;AAC1D,kDAA4C;AAC5C,6CAAsC;AAOtC,2BAA2B;AAC3B,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,CAAC,CAAC;AAgB5D,CAAC;AAEF,MAAM,aAAa,GAAG,E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KAAK,YAAY,KAAK,EAAE;gBAAE,MAAM,KAAK,CAAC;aAAE;YAC5C,OAAO,KAAK,CAAC;SAChB;QAED,+DAA+D;QAC/D,6BAA6B;QAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,EAAE;YACjC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;SAChC;QAED,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC1B,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;YAC9C,qEAAqE;YACrE,iBAAiB;SACR;QAED,qEAAqE;QACrE,MAAM,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAEhC,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,QAAQ,CAAU,GAAyB;QAC7C,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QAE1B,kCAAkC;QAClC,MAAM,OAAO,GAAsB,IAAI,GAAG,EAAE,CAAC;QAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAClC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;SACjC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QACjD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;YAAE,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;SAAE;QACrD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AA5SD,4CA4SC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-infura.js b/lib.commonjs/providers/provider-infura.js new file mode 100644 index 000000000..05378fc4c --- /dev/null +++ b/lib.commonjs/providers/provider-infura.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InfuraProvider = void 0; +const properties_js_1 = require("../utils/properties.js"); +const fetch_js_1 = require("../utils/fetch.js"); +const community_js_1 = require("./community.js"); +const logger_js_1 = require("../utils/logger.js"); +const network_js_1 = require("./network.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +const defaultProjectId = "84842078b09946638c03157f83405213"; +function getHost(name) { + switch (name) { + case "homestead": + return "mainnet.infura.io"; + case "ropsten": + return "ropsten.infura.io"; + case "rinkeby": + return "rinkeby.infura.io"; + case "kovan": + return "kovan.infura.io"; + case "goerli": + return "goerli.infura.io"; + case "matic": + return "polygon-mainnet.infura.io"; + case "maticmum": + return "polygon-mumbai.infura.io"; + case "optimism": + return "optimism-mainnet.infura.io"; + case "optimism-kovan": + return "optimism-kovan.infura.io"; + case "arbitrum": + return "arbitrum-mainnet.infura.io"; + case "arbitrum-rinkeby": + return "arbitrum-rinkeby.infura.io"; + } + return logger_js_1.logger.throwArgumentError("unsupported network", "network", name); +} +class InfuraProvider extends provider_jsonrpc_js_1.JsonRpcProvider { + projectId; + projectSecret; + constructor(_network = "homestead", projectId, projectSecret) { + const network = network_js_1.Network.from(_network); + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = InfuraProvider.getRequest(network, projectId, projectSecret); + super(request, network, { staticNetwork: network }); + (0, properties_js_1.defineProperties)(this, { projectId, projectSecret }); + } + _getProvider(chainId) { + try { + return new InfuraProvider(chainId, this.projectId, this.projectSecret); + } + catch (error) { } + return super._getProvider(chainId); + } + static getRequest(network, projectId, projectSecret) { + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = new fetch_js_1.FetchRequest(`https:/\/${getHost(network.name)}/v3/${projectId}`); + request.allowGzip = true; + if (projectSecret) { + request.setCredentials("", projectSecret); + } + if (projectId === defaultProjectId) { + request.retryFunc = async (request, response, attempt) => { + (0, community_js_1.showThrottleMessage)("InfuraProvider"); + return true; + }; + } + return request; + } + isCommunityResource() { + return (this.projectId === defaultProjectId); + } +} +exports.InfuraProvider = InfuraProvider; +//# sourceMappingURL=provider-infura.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-infura.js.map b/lib.commonjs/providers/provider-infura.js.map new file mode 100644 index 000000000..9053f6678 --- /dev/null +++ b/lib.commonjs/providers/provider-infura.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-infura.js","sourceRoot":"","sources":["../../src.ts/providers/provider-infura.ts"],"names":[],"mappings":";;;AAAA,0DAA0D;AAC1D,gDAAiD;AAEjD,iDAAqD;AACrD,kDAA4C;AAC5C,6CAAuC;AACvC,+DAAwD;AAOxD,MAAM,gBAAgB,GAAG,kCAAkC,CAAC;AAE5D,SAAS,OAAO,CAAC,IAAY;IACzB,QAAO,IAAI,EAAE;QACT,KAAK,WAAW;YACZ,OAAO,mBAAmB,CAAC;QAC/B,KAAK,SAAS;YACV,OAAO,mBAAmB,CAAC;QAC/B,KAAK,SAAS;YACV,OAAO,mBAAmB,CAAC;QAC/B,KAAK,OAAO;YACR,OAAO,iBAAiB,CAAC;QAC7B,KAAK,QAAQ;YACT,OAAO,kBAAkB,CAAC;QAC9B,KAAK,OAAO;YACR,OAAO,2BAA2B,CAAC;QACvC,KAAK,UAAU;YACX,OAAO,0BAA0B,CAAC;QACtC,KAAK,UAAU;YACX,OAAO,4BAA4B,CAAC;QACxC,KAAK,gBAAgB;YACjB,OAAO,0BAA0B,CAAC;QACtC,KAAK,UAAU;YACX,OAAO,4BAA4B,CAAC;QACxC,KAAK,kBAAkB;YACnB,OAAO,4BAA4B,CAAC;KAC3C;IAED,OAAO,kBAAM,CAAC,kBAAkB,CAAC,qBAAqB,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;AAC7E,CAAC;AAGD,MAAa,cAAe,SAAQ,qCAAe;IACtC,SAAS,CAAU;IACnB,aAAa,CAAiB;IAEvC,YAAY,WAAuB,WAAW,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,gBAAgB,EAAE;YAChC,OAAO,CAAC,SAAS,GAAG,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;gBACrD,IAAA,kCAAmB,EAAC,gBAAgB,CAAC,CAAC;gBACtC,OAAO,IAAI,CAAC;YAChB,CAAC,CAAC;SACL;QAED,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,mBAAmB;QACf,OAAO,CAAC,IAAI,CAAC,SAAS,KAAK,gBAAgB,CAAC,CAAC;IACjD,CAAC;CACJ;AA3CD,wCA2CC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-ipcsocket-browser.js b/lib.commonjs/providers/provider-ipcsocket-browser.js new file mode 100644 index 000000000..7a8728ff4 --- /dev/null +++ b/lib.commonjs/providers/provider-ipcsocket-browser.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IpcSocketProvider = void 0; +const IpcSocketProvider = undefined; +exports.IpcSocketProvider = IpcSocketProvider; +//# sourceMappingURL=provider-ipcsocket-browser.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-ipcsocket-browser.js.map b/lib.commonjs/providers/provider-ipcsocket-browser.js.map new file mode 100644 index 000000000..a4527c7ae --- /dev/null +++ b/lib.commonjs/providers/provider-ipcsocket-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ipcsocket-browser.js","sourceRoot":"","sources":["../../src.ts/providers/provider-ipcsocket-browser.ts"],"names":[],"mappings":";;;AAAA,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAE3B,8CAAiB"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-ipcsocket.js b/lib.commonjs/providers/provider-ipcsocket.js new file mode 100644 index 000000000..87e8a3f8f --- /dev/null +++ b/lib.commonjs/providers/provider-ipcsocket.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IpcSocketProvider = void 0; +const net_1 = require("net"); +const provider_socket_js_1 = require("./provider-socket.js"); +// @TODO: Is this sufficient? Is this robust? Will newlines occur between +// all payloads and only between payloads? +function splitBuffer(data) { + const messages = []; + let lastStart = 0; + while (true) { + const nl = data.indexOf(10, lastStart); + if (nl === -1) { + break; + } + messages.push(data.subarray(lastStart, nl).toString().trim()); + lastStart = nl + 1; + } + return { messages, remaining: data.subarray(lastStart) }; +} +class IpcSocketProvider extends provider_socket_js_1.SocketProvider { + #socket; + get socket() { return this.#socket; } + constructor(path, network) { + super(network); + this.#socket = (0, net_1.connect)(path); + this.socket.on("ready", () => { this._start(); }); + let response = Buffer.alloc(0); + this.socket.on("data", (data) => { + response = Buffer.concat([response, data]); + const { messages, remaining } = splitBuffer(response); + messages.forEach((message) => { + this._processMessage(message); + }); + response = remaining; + }); + this.socket.on("end", () => { + this.emit("close"); + this.socket.destroy(); + this.socket.end(); + }); + } + stop() { + this.socket.destroy(); + this.socket.end(); + } + async _write(message) { + console.log(">>>", message); + this.socket.write(message); + } +} +exports.IpcSocketProvider = IpcSocketProvider; +/* + +import { defineProperties } from "@ethersproject/properties"; + +import { SocketLike, SocketProvider } from "./provider-socket.js"; + +import type { Socket } from "net"; + +export class SocketWrapper implements SocketLike { + #socket: Socket; + + constructor(path: string) { + this.#socket = connect(path); + } + + send(data: string): void { + this.#socket.write(data, () => { }); + } + + addEventListener(event: string, listener: (data: string) => void): void { + //this.#socket.on(event, (value: ) => { + //}); + } + + close(): void { + } +} + +export class IpcProvider extends SocketProvider { + readonly path!: string; + + constructor(path: string) { + super(new SocketWrapper(path)); + defineProperties(this, { path }); + } +} +*/ +//# sourceMappingURL=provider-ipcsocket.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-ipcsocket.js.map b/lib.commonjs/providers/provider-ipcsocket.js.map new file mode 100644 index 000000000..cb6a583fc --- /dev/null +++ b/lib.commonjs/providers/provider-ipcsocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ipcsocket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-ipcs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,CAAE,CAAC,CAAC;YAC7C,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;YACtD,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBACzB,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;YAClC,CAAC,CAAC,CAAC;YACH,QAAQ,GAAG,SAAS,CAAC;QACzB,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACvB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACnB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACtB,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QACtB,CAAC,CAAC,CAAC;IACP,CAAC;IAED,IAAI;QACA,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;IACtB,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAAe;QACxB,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QAC5B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;CACJ;AApCD,8CAoCC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoCE"} \ 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 000000000..ffb24cf44 --- /dev/null +++ b/lib.commonjs/providers/provider-jsonrpc.js @@ -0,0 +1,693 @@ +"use strict"; +// @TODO: +// - Add the batching API +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonRpcProvider = exports.JsonRpcApiProvider = exports.JsonRpcSigner = void 0; +// 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("../address/index.js"); +const data_js_1 = require("../utils/data.js"); +const fetch_js_1 = require("../utils/fetch.js"); +const maths_js_1 = require("../utils/maths.js"); +const properties_js_1 = require("../utils/properties.js"); +const typed_data_js_1 = require("../hash/typed-data.js"); +const utf8_js_1 = require("../utils/utf8.js"); +const index_js_2 = require("../transaction/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 logger_js_1 = require("../utils/logger.js"); +//function copy(value: T): T { +// return JSON.parse(JSON.stringify(value)); +//} +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 getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +function isPollable(value) { + return (value && typeof (value.pollingInterval) === "number"); +} +const defaultOptions = { + polling: false, + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: (1 << 20), + batchMaxCount: 100 // 100 requests +}; +// @TODO: Unchecked Signers +class JsonRpcSigner extends abstract_signer_js_1.AbstractSigner { + address; + constructor(provider, address) { + super(provider); + (0, properties_js_1.defineProperties)(this, { address }); + } + connect(provider) { + return logger_js_1.logger.throwError("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); + } + //async getNetwork(): Promise> { + // return await this.provider.getNetwork(); + //} + //async estimateGas(tx: TransactionRequest): Promise { + // return await this.provider.estimateGas(tx); + //} + //async call(tx: TransactionRequest): Promise { + // return await this.provider.call(tx); + //} + //async resolveName(name: string | Addressable): Promise { + // return await this.provider.resolveName(name); + //} + //async getNonce(blockTag?: BlockTag): Promise { + // return await this.provider.getTransactionCountOf(this.address); + //} + // 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_1.resolveAddress)(_from, this.provider); + if (from == null || from.toLowerCase() !== this.address.toLowerCase()) { + logger_js_1.logger.throwArgumentError("from address mismatch", "transaction", _tx); + } + tx.from = from; + })()); + } + else { + tx.from = this.address; + } + // The JSON-RPC for eth_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_1.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("eth_sendTransaction", [hexTx]); + } + async sendTransaction(tx) { + // This cannot be mined any earlier than any recent block + const blockNumber = await this.provider.getBlockNumber(); + // 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]; + const checkTx = async () => { + // Try getting the transaction + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(this.provider._wrapTransaction(tx, hash, blockNumber)); + return; + } + // 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_1.resolveAddress)(tx.from, this.provider); + if (from == null || from.toLowerCase() !== this.address.toLowerCase()) { + return logger_js_1.logger.throwArgumentError("from address mismatch", "transaction", _tx); + } + tx.from = from; + } + else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("eth_sign_Transaction", [hexTx]); + } + async signMessage(_message) { + const message = ((typeof (_message) === "string") ? (0, utf8_js_1.toUtf8Bytes)(_message) : _message); + return await this.provider.send("personal_sign", [ + (0, data_js_1.hexlify)(message), this.address.toLowerCase() + ]); + } + async signTypedData(domain, types, _value) { + const value = deepCopy(_value); + // Populate any ENS names (in-place) + const populated = await typed_data_js_1.TypedDataEncoder.resolveNames(domain, types, value, async (value) => { + const address = await (0, index_js_1.resolveAddress)(value); + if (address == null) { + return logger_js_1.logger.throwArgumentError("TypedData does not support null address", "value", value); + } + return address; + }); + return await this.provider.send("eth_signTypedData_v4", [ + this.address.toLowerCase(), + JSON.stringify(typed_data_js_1.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#eth_sign + async _legacySignMessage(_message) { + const message = ((typeof (_message) === "string") ? (0, utf8_js_1.toUtf8Bytes)(_message) : _message); + return await this.provider.send("eth_sign", [ + this.address.toLowerCase(), (0, data_js_1.hexlify)(message) + ]); + } +} +exports.JsonRpcSigner = JsonRpcSigner; +class JsonRpcApiProvider extends abstract_provider_js_1.AbstractProvider { + #options; + #nextId; + #payloads; + #drainTimer; + constructor(network, options) { + super(network); + this.#nextId = 1; + this.#options = Object.assign({}, defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + // This could be relaxed in the future to just check equivalent networks + const staticNetwork = this._getOption("staticNetwork"); + if (staticNetwork && staticNetwork !== network) { + logger_js_1.logger.throwArgumentError("staticNetwork MUST match network object", "options", options); + } + } + _getOption(key) { + return this.#options[key]; + } + // @TODO: Merge this into send + //prepareRequest(method: string, params: Array): JsonRpcPayload { + // return { + // method, params, id: (this.#nextId++), jsonrpc: "2.0" + // }; + //} + /* + async send(method: string, params: Array): Promise { + // @TODO: This should construct and queue the payload + throw new Error("sub-class must implement this"); + } + */ + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + 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 payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload)); + this.emit("debug", { action: "sendRpcPayload", payload }); + 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) { + // 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) { + return reject(new Error("@TODO: no result")); + } + // The response is an error + if ("error" in resp) { + return reject(this.getRpcError(payload, resp)); + } + // 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); + } + } + })(); + } + }, this.#options.batchStallTime); + } + // Sub-classes should **NOT** override this + send(method, params) { + // @TODO: cache chainId?? purge on switch_networks + const id = this.#nextId++; + const promise = new Promise((resolve, reject) => { + this.#payloads.push({ + resolve, reject, + payload: { method, params, id, jsonrpc: "2.0" } + }); + }); + // If there is not a pending drainTimer, set one + this.#scheduleDrain(); + return promise; + } + // Sub-classes MUST override this + _send(payload) { + return logger_js_1.logger.throwError("sub-classes must override _send", "UNSUPPORTED_OPERATION", { + operation: "jsonRpcApiProvider._send" + }); + } + async getSigner(address = 0) { + const accountsPromise = this.send("eth_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 [network, accounts] = await Promise.all([this.getNetwork(), accountsPromise]); + // Account address + address = network.formatter.address(address); + for (const account of accounts) { + if (network.formatter.address(account) === account) { + return new JsonRpcSigner(this, account); + } + } + throw new Error("invalid account"); + } + // Sub-classes can override this; it detects the *actual* network we + // are connected to + async _detectNetwork() { + // We have a static network (like INFURA) + const network = this._getOption("staticNetwork"); + if (network) { + return network; + } + return network_js_1.Network.from(logger_js_1.logger.getBigInt(await this._perform({ method: "chainId" }))); + } + _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); + } + // Normalize a JSON-RPC transaction + 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, maths_js_1.toQuantity)(logger_js_1.logger.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, data_js_1.hexlify)(tx[key]); + }); + // Normalize the access list object + if (tx.accessList) { + result["accessList"] = (0, index_js_2.accessListify)(tx.accessList); + } + return result; + } + // Get the necessary paramters for making a JSON-RPC request + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "eth_chainId", args: [] }; + case "getBlockNumber": + return { method: "eth_blockNumber", args: [] }; + case "getGasPrice": + return { method: "eth_gasPrice", args: [] }; + case "getBalance": + return { + method: "eth_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "eth_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "eth_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorageAt": + return { + method: "eth_getStorageAt", + args: [ + getLowerCase(req.address), + ("0x" + req.position.toString(16)), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "eth_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "eth_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] + }; + } + else if ("blockHash" in req) { + return { + method: "eth_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] + }; + } + break; + case "getTransaction": + return { + method: "eth_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "eth_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "eth_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "eth_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + 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: "eth_getLogs", args: [req.filter] }; + } + return null; + } + getRpcError(payload, error) { + console.log("getRpcError", payload, error); + return new Error(`JSON-RPC badness; @TODO: ${error}`); + /* + if (payload.method === "eth_call") { + const result = spelunkData(error); + if (result) { + // @TODO: Extract errorSignature, errorName, errorArgs, reason if + // it is Error(string) or Panic(uint25) + return logger.makeError("execution reverted during JSON-RPC call", "CALL_EXCEPTION", { + data: result.data, + transaction: args[0] + }); + } + + return logger.makeError("missing revert data during JSON-RPC call", "CALL_EXCEPTION", { + data: "0x", transaction: args[0], info: { error } + }); + } + + if (method === "eth_estimateGas") { + // @TODO: Spelunk, and adapt the above to allow missing data. + // Then throw an UNPREDICTABLE_GAS exception + } + + const message = JSON.stringify(spelunkMessage(error)); + + if (message.match(/insufficient funds|base fee exceeds gas limit/)) { + return logger.makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: args[0] + }); + } + + if (message.match(/nonce/) && message.match(/too low/)) { + return logger.makeError("nonce has already been used", "NONCE_EXPIRED", { + transaction: args[0] + }); + } + + // "replacement transaction underpriced" + if (message.match(/replacement transaction/) && message.match(/underpriced/)) { + return logger.makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { + transaction: args[0] + }); + } + + if (message.match(/only replay-protected/)) { + return logger.makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, info: { transaction: args[0] } + }); + } + + if (method === "estimateGas" && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) { + return logger.makeError("cannot estimate gas; transaction may fail or may require manual gas limit", "UNPREDICTABLE_GAS_LIMIT", { + transaction: args[0] + }); + } + + return error; + */ + } + 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 + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && logger_js_1.logger.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(); + 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); + /* + @TODO: Add debug output to send + this.emit("debug", { type: "sendRequest", request }); + try { + const result = + //console.log("RR", result); + this.emit("debug", { type: "getResponse", result }); + return result; + } catch (error) { + this.emit("debug", { type: "getError", error }); + throw error; + //throw this.getRpcError(request.method, request.args, error); + } + */ + } + return super._perform(req); + } +} +exports.JsonRpcApiProvider = JsonRpcApiProvider; +class JsonRpcProvider extends JsonRpcApiProvider { + #connect; + #pollingInterval; + constructor(url, network, options) { + if (url == null) { + url = "http:/\/localhost:8545"; + } + super(network, options); + if (typeof (url) === "string") { + this.#connect = new fetch_js_1.FetchRequest(url); + } + else { + this.#connect = url.clone(); + } + this.#pollingInterval = 4000; + } + async _send(payload) { + // Configure a POST connection for the requested method + const request = this.#connect.clone(); + request.body = JSON.stringify(payload); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; + } + get pollingInterval() { return this.#pollingInterval; } + set pollingInterval(value) { + if (!Number.isInteger(value) || value < 0) { + throw new Error("invalid interval"); + } + this.#pollingInterval = value; + this._forEachSubscriber((sub) => { + if (isPollable(sub)) { + sub.pollingInterval = this.#pollingInterval; + } + }); + } +} +exports.JsonRpcProvider = JsonRpcProvider; +// This class should only be used when it is not possible for the +// underlying network to change, such as with INFURA. If you are +// using MetaMask or some other client which allows users to change +// their network DO NOT USE THIS. Bad things will happen. +/* +export class StaticJsonRpcProvider extends JsonRpcProvider { + readonly network!: Network; + + constructor(url: string | ConnectionInfo, network?: Network, options?: JsonRpcOptions) { + super(url, network, options); + defineProperties(this, { network }); + } + + async _detectNetwork(): Promise { + return this.network; + } +} +*/ +/* +function spelunkData(value: any): null | { message: string, data: string } { + if (value == null) { return null; } + + // These *are* the droids we're looking for. + if (typeof(value.message) === "string" && value.message.match("reverted") && 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: any, result: Array): void { + 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: any): Array { + const result: Array = [ ]; + _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 000000000..995f5e355 --- /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,SAAS;AACT,yBAAyB;;;AAEzB,yQAAyQ;AAEzQ,kDAAqD;AACrD,8CAA2C;AAC3C,gDAAiD;AACjD,gDAA+C;AAC/C,0DAA0D;AAC1D,yDAAyD;AACzD,8CAA+C;AAC/C,sDAAwD;AAExD,iEAA+E;AAC/E,6DAAsD;AACtD,6CAAuC;AACvC,qEAA8F;AAU9F,kDAA4C;AAG5C,uCAAuC;AACvC,+CAA+C;AAC/C,GAAG;AAEH,MAAM,SAAS,GAAG,8CAA8C,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC7E,gDAAgD;AAChD,SAAS,QAAQ,CAAU,KAAQ;IAC/B,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AChE,mEAAmE;AACnE,yDAAyD;AACzD;;;;;;;;;;;;;EAaE;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwDE"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-pocket.js b/lib.commonjs/providers/provider-pocket.js new file mode 100644 index 000000000..c2ffa7fa5 --- /dev/null +++ b/lib.commonjs/providers/provider-pocket.js @@ -0,0 +1,101 @@ +"use strict"; +/* +import { defineProperties } from "../utils/properties.js"; +import { FetchRequest } from "../web/index.js"; + +import { showThrottleMessage } from "./community.js"; +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; + +import type { ConnectionInfo, ThrottleRetryFunc } from "../web/index.js"; + +import type { CommunityResourcable } from "./community.js"; +import type { Networkish } from "./network.js"; + + + +// These are load-balancer-based application IDs +const defaultAppIds: Record = { + homestead: "6004bcd10040261633ade990", + ropsten: "6004bd4d0040261633ade991", + rinkeby: "6004bda20040261633ade994", + goerli: "6004bd860040261633ade992", +}; + +function getHost(name: string): string { + switch(name) { + case "homestead": + return "eth-mainnet.gateway.pokt.network"; + case "ropsten": + return "eth-ropsten.gateway.pokt.network"; + case "rinkeby": + return "eth-rinkeby.gateway.pokt.network"; + case "goerli": + return "eth-goerli.gateway.pokt.network"; + } + + return logger.throwArgumentError("unsupported network", "network", name); +} + +function normalizeApiKey(network: Network, _appId?: null | string, applicationSecretKey?: null | string, loadBalancer?: boolean): { applicationId: string, applicationSecretKey: null | string, loadBalancer: boolean, community: boolean } { + loadBalancer = !!loadBalancer; + + let community = false; + let applicationId = _appId; + if (applicationId == null) { + applicationId = defaultAppIds[network.name]; + if (applicationId == null) { + logger.throwArgumentError("network does not support default applicationId", "applicationId", _appId); + } + loadBalancer = true; + community = true; + } else if (applicationId === defaultAppIds[network.name]) { + loadBalancer = true; + community = true; + } + if (applicationSecretKey == null) { applicationSecretKey = null; } + + return { applicationId, applicationSecretKey, community, loadBalancer }; +} + +export class PocketProvider extends JsonRpcProvider implements CommunityResourcable { + readonly applicationId!: string; + readonly applicationSecretKey!: null | string; + readonly loadBalancer!: boolean; + + constructor(_network: Networkish = "homestead", _appId?: null | string, _secretKey?: null | string, _loadBalancer?: boolean) { + const network = Network.from(_network); + const { applicationId, applicationSecretKey, loadBalancer } = normalizeApiKey(network, _appId, _secretKey, _loadBalancer); + + const connection = PocketProvider.getConnection(network, applicationId, applicationSecretKey, loadBalancer); + super(connection, network, { staticNetwork: network }); + + defineProperties(this, { applicationId, applicationSecretKey, loadBalancer }); + } + + static getConnection(network: Network, _appId?: null | string, _secretKey?: null | string, _loadBalancer?: boolean): ConnectionInfo { + const { applicationId, applicationSecretKey, community, loadBalancer } = normalizeApiKey(network, _appId, _secretKey, _loadBalancer); + + let url = `https:/\/${ getHost(network.name) }/v1/`; + if (loadBalancer) { url += "lb/"; } + url += applicationId; + + const request = new FetchRequest(url); + request.allowGzip = true; + if (applicationSecretKey) { request.setCredentials("", applicationSecretKey); } + + const throttleRetry: ThrottleRetryFunc = async (request, response, attempt) => { + if (community) { showThrottleMessage("PocketProvider"); } + return true; + }; + + return { request, throttleRetry }; + } + + isCommunityResource(): boolean { + return (this.applicationId === defaultAppIds[this.network.name]); + } +} +*/ +//# sourceMappingURL=provider-pocket.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-pocket.js.map b/lib.commonjs/providers/provider-pocket.js.map new file mode 100644 index 000000000..48d33a040 --- /dev/null +++ b/lib.commonjs/providers/provider-pocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-pocket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-pocket.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkGE"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-socket.js b/lib.commonjs/providers/provider-socket.js new file mode 100644 index 000000000..92dcd102b --- /dev/null +++ b/lib.commonjs/providers/provider-socket.js @@ -0,0 +1,225 @@ +"use strict"; +/** + * SocketProvider + * + * Generic long-lived socket provider. + * + * Sub-classing notes + * - a sub-class MUST call the `_start()` method once connected + * - a sub-class MUST override the `_write(string)` method + * - a sub-class MUST call `_processMessage(string)` for each message + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SocketProvider = exports.SocketEventSubscriber = exports.SocketPendingSubscriber = exports.SocketBlockSubscriber = exports.SocketSubscriber = void 0; +const abstract_provider_js_1 = require("./abstract-provider.js"); +const logger_js_1 = require("../utils/logger.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +class SocketSubscriber { + #provider; + #filter; + get filter() { return JSON.parse(this.#filter); } + #filterId; + #paused; + #emitPromise; + constructor(provider, filter) { + this.#provider = provider; + this.#filter = JSON.stringify(filter); + this.#filterId = null; + this.#paused = null; + this.#emitPromise = null; + } + start() { + this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId) => { + ; + this.#provider._register(filterId, this); + return filterId; + }); + } + stop() { + (this.#filterId).then((filterId) => { + this.#provider.send("eth_unsubscribe", [filterId]); + }); + this.#filterId = null; + } + // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs + // and resume + pause(dropWhilePaused) { + if (!dropWhilePaused) { + logger_js_1.logger.throwError("preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { + operation: "pause(false)" + }); + } + this.#paused = !!dropWhilePaused; + } + resume() { + this.#paused = null; + } + _handleMessage(message) { + if (this.#filterId == null) { + return; + } + if (this.#paused === null) { + let emitPromise = this.#emitPromise; + if (emitPromise == null) { + emitPromise = this._emit(this.#provider, message); + } + else { + emitPromise = emitPromise.then(async () => { + await this._emit(this.#provider, message); + }); + } + this.#emitPromise = emitPromise.then(() => { + if (this.#emitPromise === emitPromise) { + this.#emitPromise = null; + } + }); + } + } + async _emit(provider, message) { + throw new Error("sub-classes must implemente this; _emit"); + } +} +exports.SocketSubscriber = SocketSubscriber; +class SocketBlockSubscriber extends SocketSubscriber { + constructor(provider) { + super(provider, ["newHeads"]); + } + async _emit(provider, message) { + provider.emit("block", parseInt(message.number)); + } +} +exports.SocketBlockSubscriber = SocketBlockSubscriber; +class SocketPendingSubscriber extends SocketSubscriber { + constructor(provider) { + super(provider, ["newPendingTransactions"]); + } + async _emit(provider, message) { + provider.emit("pending", message); + } +} +exports.SocketPendingSubscriber = SocketPendingSubscriber; +class SocketEventSubscriber extends SocketSubscriber { + #logFilter; + get logFilter() { return JSON.parse(this.#logFilter); } + #formatter; + constructor(provider, filter) { + super(provider, ["logs", filter]); + this.#logFilter = JSON.stringify(filter); + this.#formatter = provider.getNetwork().then((network) => network.formatter); + } + async _emit(provider, message) { + const formatter = await this.#formatter; + provider.emit(this.#logFilter, formatter.log(message, provider)); + } +} +exports.SocketEventSubscriber = SocketEventSubscriber; +class SocketProvider extends provider_jsonrpc_js_1.JsonRpcApiProvider { + #callbacks; + #ready; + // Maps each filterId to its subscriber + #subs; + // If any events come in before a subscriber has finished + // registering, queue them + #pending; + constructor(network) { + super(network, { batchMaxCount: 1 }); + this.#callbacks = new Map(); + this.#ready = false; + this.#subs = new Map(); + this.#pending = new Map(); + } + _getSubscriber(sub) { + switch (sub.type) { + case "close": + return new abstract_provider_js_1.UnmanagedSubscriber("close"); + case "block": + return new SocketBlockSubscriber(this); + case "pending": + return new SocketPendingSubscriber(this); + case "event": + return new SocketEventSubscriber(this, sub.filter); + case "orphan": + // Handled auto-matically within AbstractProvider + // when the log.removed = true + if (sub.filter.orphan === "drop-log") { + return new abstract_provider_js_1.UnmanagedSubscriber("drop-log"); + } + } + return super._getSubscriber(sub); + } + _register(filterId, subscriber) { + this.#subs.set(filterId, subscriber); + const pending = this.#pending.get(filterId); + if (pending) { + for (const message of pending) { + subscriber._handleMessage(message); + } + this.#pending.delete(filterId); + } + } + async _send(payload) { + // WebSocket provider doesn't accept batches + (0, logger_js_1.assertArgument)(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload); + // @TODO: stringify payloads here and store to prevent mutations + const promise = new Promise((resolve, reject) => { + this.#callbacks.set(payload.id, { payload, resolve, reject }); + }); + if (this.#ready) { + await this._write(JSON.stringify(payload)); + } + return [await promise]; + } + // Sub-classes must call this once they are connected + async _start() { + if (this.#ready) { + return; + } + this.#ready = true; + for (const { payload } of this.#callbacks.values()) { + await this._write(JSON.stringify(payload)); + } + } + // Sub-classes must call this for each message + async _processMessage(message) { + const result = (JSON.parse(message)); + if ("id" in result) { + const callback = this.#callbacks.get(result.id); + if (callback == null) { + console.log("Weird... Response for not a thing we sent"); + return; + } + this.#callbacks.delete(result.id); + if ("error" in result) { + const { message, code, data } = result.error; + const error = logger_js_1.logger.makeError(message || "unkonwn error", "SERVER_ERROR", { + request: `ws:${JSON.stringify(callback.payload)}`, + info: { code, data } + }); + callback.reject(error); + } + else { + callback.resolve(result.result); + } + } + else if (result.method === "eth_subscription") { + const filterId = result.params.subscription; + const subscriber = this.#subs.get(filterId); + if (subscriber) { + subscriber._handleMessage(result.params.result); + } + else { + let pending = this.#pending.get(filterId); + if (pending == null) { + pending = []; + this.#pending.set(filterId, pending); + } + pending.push(result.params.result); + } + } + } + async _write(message) { + throw new Error("sub-classes must override this"); + } +} +exports.SocketProvider = SocketProvider; +//# sourceMappingURL=provider-socket.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-socket.js.map b/lib.commonjs/providers/provider-socket.js.map new file mode 100644 index 000000000..682ad5665 --- /dev/null +++ b/lib.commonjs/providers/provider-socket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-socket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-socket.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAEH,iEAA6D;AAC7D,kDAA4D;AAC5D,+DAA2D;AAiB3D,MAAa,gBAAgB;IACzB,SAAS,CAAiB;IAE1B,OAAO,CAAS;IAChB,IAAI,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tC;SACJ;IACL,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAAe;QACxB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACtD,CAAC;CACJ;AAtHD,wCAsHC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-websocket.js b/lib.commonjs/providers/provider-websocket.js new file mode 100644 index 000000000..c941adfb8 --- /dev/null +++ b/lib.commonjs/providers/provider-websocket.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketProvider = void 0; +const ws_js_1 = require("./ws.js"); /*-browser*/ +const provider_socket_js_1 = require("./provider-socket.js"); +class WebSocketProvider extends provider_socket_js_1.SocketProvider { + url; + #websocket; + get websocket() { return this.#websocket; } + constructor(url, network) { + super(network); + if (typeof (url) === "string") { + this.#websocket = new ws_js_1.WebSocket(url); + } + else { + this.#websocket = url; + } + this.websocket.onopen = () => { + this._start(); + }; + this.websocket.onmessage = (message) => { + this._processMessage(message.data); + }; + } + async _write(message) { + this.websocket.send(message); + } +} +exports.WebSocketProvider = WebSocketProvider; +//# sourceMappingURL=provider-websocket.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-websocket.js.map b/lib.commonjs/providers/provider-websocket.js.map new file mode 100644 index 000000000..00ed06637 --- /dev/null +++ b/lib.commonjs/providers/provider-websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-websocket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-websocket.ts"],"names":[],"mappings":";;;AAEA,mCAAkD,CAAC,YAAY;AAE/D,6DAAsD;AAetD,MAAa,iBAAkB,SAAQ,mCAAc;IACjD,GAAG,CAAU;IAEb,UAAU,CAAgB;IAC1B,IAAI,SAAS,KAAoB,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAE1D,YAAY,GAA2B,EAAE,OAAoB;QACzD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,OAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE;YAC1B,IAAI,CAAC,UAAU,GAAG,IAAI,iBAAU,CAAC,GAAG,CAAC,CAAC;SACzC;aAAM;YACH,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC;SACzB;QAED,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,GAAG,EAAE;YACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QAClB,CAAC,CAAC;QAEF,IAAI,CAAC,SAAS,CAAC,SAAS,GAAG,CAAC,OAAyB,EAAE,EAAE;YACrD,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACvC,CAAC,CAAC;IACN,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAAe;QACxB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACJ;AA1BD,8CA0BC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider.js b/lib.commonjs/providers/provider.js new file mode 100644 index 000000000..9ae99430e --- /dev/null +++ b/lib.commonjs/providers/provider.js @@ -0,0 +1,560 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dummyProvider = exports.TransactionResponse = exports.TransactionReceipt = exports.Log = exports.Block = exports.copyRequest = exports.FeeData = void 0; +//import { resolveAddress } from "@ethersproject/address"; +const data_js_1 = require("../utils/data.js"); +const logger_js_1 = require("../utils/logger.js"); +const properties_js_1 = require("../utils/properties.js"); +const index_js_1 = require("../transaction/index.js"); +// ----------------------- +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +// @TODO? implements Required +class FeeData { + gasPrice; + maxFeePerGas; + maxPriorityFeePerGas; + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + (0, properties_js_1.defineProperties)(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), + }; + } +} +exports.FeeData = FeeData; +; +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, data_js_1.hexlify)(req.data); + } + const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerGas, maxPriorityFeePerGas,value".split(/,/); + for (const key in bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = logger_js_1.logger.getBigInt(req[key], `request.${key}`); + } + const numberKeys = "type,nonce".split(/,/); + for (const key in numberKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = logger_js_1.logger.getNumber(req[key], `request.${key}`); + } + if (req.accessList) { + result.accessList = (0, index_js_1.accessListify)(req.accessList); + } + if ("blockTag" in req) { + result.blockTag = req.blockTag; + } + if ("enableCcipRead" in req) { + result.enableCcipReadEnabled = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + return result; +} +exports.copyRequest = copyRequest; +; +class Block { + provider; + number; + hash; + timestamp; + parentHash; + nonce; + difficulty; + gasLimit; + gasUsed; + miner; + extraData; + baseFeePerGas; + #transactions; + constructor(block, provider) { + if (provider == null) { + provider = exports.dummyProvider; + } + this.#transactions = Object.freeze(block.transactions.map((tx) => { + if (typeof (tx) !== "string" && tx.provider !== provider) { + throw new Error("provider mismatch"); + } + return tx; + })); + ; + (0, properties_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) + }); + } + get transactions() { return this.#transactions; } + //connect(provider: Provider): Block { + // return new Block(this, provider); + //} + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, nonce, number, parentHash, timestamp, transactions } = this; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + hash, miner, nonce, number, parentHash, timestamp, + transactions, + }; + } + [Symbol.iterator]() { + let index = 0; + return { + next: () => { + if (index < this.length) { + return { + value: this.transactions[index++], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + get length() { return this.transactions.length; } + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1000); + } + async getTransaction(index) { + const tx = this.transactions[index]; + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + isMined() { return !!this.hash; } + isLondon() { return !!this.baseFeePerGas; } + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +exports.Block = Block; +class Log { + provider; + transactionHash; + blockHash; + blockNumber; + removed; + address; + data; + topics; + index; + transactionIndex; + constructor(log, provider) { + if (provider == null) { + provider = exports.dummyProvider; + } + this.provider = provider; + const topics = Object.freeze(log.topics.slice()); + (0, properties_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, + }); + } + //connect(provider: Provider): Log { + // return new Log(this, provider); + //} + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, blockHash, blockNumber, data, index, + removed, topics, transactionHash, transactionIndex + }; + } + async getBlock() { + return (await this.provider.getBlock(this.blockHash)); + } + async getTransaction() { + return (await this.provider.getTransaction(this.transactionHash)); + } + async getTransactionReceipt() { + return (await this.provider.getTransactionReceipt(this.transactionHash)); + } + removedEvent() { + return createRemovedLogFilter(this); + } +} +exports.Log = Log; +class TransactionReceipt { + provider; + to; + from; + contractAddress; + hash; + index; + blockHash; + blockNumber; + logsBloom; + gasUsed; + cumulativeGasUsed; + gasPrice; + byzantium; + status; + root; + #logs; + constructor(tx, provider) { + if (provider == null) { + provider = exports.dummyProvider; + } + this.#logs = Object.freeze(tx.logs.map((log) => { + if (provider !== log.provider) { + //return log.connect(provider); + throw new Error("provider mismatch"); + } + return log; + })); + (0, properties_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: (tx.effectiveGasPrice || tx.gasPrice), + byzantium: tx.byzantium, + status: tx.status, + root: tx.root + }); + } + get logs() { return this.#logs; } + //connect(provider: Provider): TransactionReceipt { + // return new TransactionReceipt(this, provider); + //} + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, byzantium, status, root } = 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, root, status, to + }; + } + 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 }; + } + }; + } + get fee() { + return this.gasUsed * this.gasPrice; + } + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + async confirmations() { + return (await this.provider.getBlockNumber()) - this.blockNumber + 1; + } + removedEvent() { + return createRemovedTransactionFilter(this); + } + reorderedEvent(other) { + if (other && !other.isMined()) { + return logger_js_1.logger.throwError("unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "reorderedEvent(other)" + }); + } + return createReorderedTransactionFilter(this, other); + } +} +exports.TransactionReceipt = TransactionReceipt; +; +class TransactionResponse { + provider; + blockNumber; + blockHash; + index; + hash; + type; + to; + from; + nonce; + gasLimit; + gasPrice; + maxPriorityFeePerGas; + maxFeePerGas; + data; + value; + chainId; + signature; + accessList; + constructor(tx, provider) { + if (provider == null) { + provider = exports.dummyProvider; + } + 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.gasPrice = tx.gasPrice; + 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; + } + //connect(provider: Provider): TransactionResponse { + // return new TransactionResponse(this, provider); + //} + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList } = this; + return { + _type: "TransactionReceipt", + accessList, blockNumber, blockHash, + chainId: toJson(this.chainId), + data, from, + gasLimit: toJson(this.gasLimit), + gasPrice: toJson(this.gasPrice), + hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + nonce, signature, to, index, type, + value: toJson(this.value), + }; + } + async getBlock() { + 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); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + async getTransaction() { + return this.provider.getTransaction(this.hash); + } + async wait(confirms) { + return this.provider.waitForTransaction(this.hash, confirms); + } + isMined() { + return (this.blockHash != null); + } + isLegacy() { + return (this.type === 0); + } + isBerlin() { + return (this.type === 1); + } + isLondon() { + return (this.type === 2); + } + removedEvent() { + if (!this.isMined()) { + return logger_js_1.logger.throwError("unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + return createRemovedTransactionFilter(this); + } + reorderedEvent(other) { + if (!this.isMined()) { + return logger_js_1.logger.throwError("unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + if (other && !other.isMined()) { + return logger_js_1.logger.throwError("unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + return createReorderedTransactionFilter(this, other); + } +} +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 + } }; +} +function fail() { + throw new Error("this provider should not be used"); +} +class DummyProvider { + get provider() { return this; } + async getNetwork() { return fail(); } + async getFeeData() { return fail(); } + async estimateGas(tx) { return fail(); } + async call(tx) { return fail(); } + async resolveName(name) { return fail(); } + // State + async getBlockNumber() { return fail(); } + // Account + async getBalance(address, blockTag) { + return fail(); + } + async getTransactionCount(address, blockTag) { + return fail(); + } + async getCode(address, blockTag) { + return fail(); + } + async getStorageAt(address, position, blockTag) { + return fail(); + } + // Write + async broadcastTransaction(signedTx) { return fail(); } + // Queries + async getBlock(blockHashOrBlockTag) { + return fail(); + } + async getBlockWithTransactions(blockHashOrBlockTag) { + return fail(); + } + async getTransaction(hash) { + return fail(); + } + async getTransactionReceipt(hash) { + return fail(); + } + // Bloom-filter Queries + async getLogs(filter) { + return fail(); + } + // ENS + async lookupAddress(address) { + return fail(); + } + async waitForTransaction(hash, confirms, timeout) { + return fail(); + } + async waitForBlock(blockTag) { + return fail(); + } + // EventEmitterable + async on(event, listener) { return fail(); } + async once(event, listener) { return fail(); } + async emit(event, ...args) { return fail(); } + async listenerCount(event) { return fail(); } + async listeners(event) { return fail(); } + async off(event, listener) { return fail(); } + async removeAllListeners(event) { return fail(); } + async addListener(event, listener) { return fail(); } + async removeListener(event, listener) { return fail(); } +} +/** + * A singleton [[Provider]] instance that can be used as a placeholder. This + * allows API that have a Provider added later to not require a null check. + * + * All operations performed on this [[Provider]] will throw. + */ +exports.dummyProvider = new DummyProvider(); +//# 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 000000000..4af9b73fa --- /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,0DAA0D;AAC1D,8CAA2C;AAC3C,kDAA4C;AAC5C,0DAA0D;AAC1D,sDAAwD;AAcxD,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;AAC1D,MAAa,O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,CAAC;IAEjF,KAAK,CAAC,WAAW,CAAC,KAAoB,EAAE,QAAkB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7F,KAAK,CAAC,cAAc,CAAC,KAAoB,EAAE,QAAkB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;CACnG;AAED;;;;;GAKG;AACU,QAAA,aAAa,GAAa,IAAI,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/providers/signer.js b/lib.commonjs/providers/signer.js new file mode 100644 index 000000000..c73406acc --- /dev/null +++ b/lib.commonjs/providers/signer.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=signer.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/signer.js.map b/lib.commonjs/providers/signer.js.map new file mode 100644 index 000000000..68d48a837 --- /dev/null +++ b/lib.commonjs/providers/signer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signer.js","sourceRoot":"","sources":["../../src.ts/providers/signer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-connection.js b/lib.commonjs/providers/subscriber-connection.js new file mode 100644 index 000000000..9dbb1f6dc --- /dev/null +++ b/lib.commonjs/providers/subscriber-connection.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BlockConnectionSubscriber = void 0; +const logger_js_1 = require("../utils/logger.js"); +class BlockConnectionSubscriber { + #provider; + #blockNumber; + #filterId; + constructor(provider) { + this.#provider = provider; + this.#blockNumber = -2; + this.#filterId = null; + } + start() { + this.#filterId = this.#provider._subscribe(["newHeads"], (result) => { + const blockNumber = logger_js_1.logger.getNumber(result.number); + const initial = (this.#blockNumber === -2) ? blockNumber : (this.#blockNumber + 1); + for (let b = initial; b <= blockNumber; b++) { + this.#provider.emit("block", b); + } + this.#blockNumber = blockNumber; + }); + } + stop() { + if (this.#filterId != null) { + this.#provider._unsubscribe(this.#filterId); + this.#filterId = null; + } + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#blockNumber = -2; + } + this.stop(); + } + resume() { + this.start(); + } +} +exports.BlockConnectionSubscriber = BlockConnectionSubscriber; +//# sourceMappingURL=subscriber-connection.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-connection.js.map b/lib.commonjs/providers/subscriber-connection.js.map new file mode 100644 index 000000000..236fd2212 --- /dev/null +++ b/lib.commonjs/providers/subscriber-connection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-connection.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-connection.ts"],"names":[],"mappings":";;;AAEA,kDAA4C;AAW5C,MAAa,yBAAyB;IAClC,SAAS,CAAwB;IACjC,YAAY,CAAS;IAErB,SAAS,CAAgB;IAEzB,YAAY,QAA+B;QACvC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;IAC1B,CAAC;IAED,KAAK;QACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAE,UAAU,CAAE,EAAE,CAAC,MAAW,EAAE,EAAE;YACvE,MAAM,WAAW,GAAG,kBAAM,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACpD,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAA,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAA;YACjF,KAAK,IAAI,CAAC,GAAG,OAAO,EAAE,CAAC,IAAI,WAAW,EAAE,CAAC,EAAE,EAAE;gBACzC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;aACnC;YACD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QACpC,CAAC,CAAC,CAAC;IACP,CAAC;IAED,IAAI;QACA,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;YACxB,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC5C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;SACzB;IACL,CAAC;IAED,KAAK,CAAC,eAAyB;QAC3B,IAAI,eAAe,EAAE;YAAE,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;SAAE;QAChD,IAAI,CAAC,IAAI,EAAE,CAAC;IAChB,CAAC;IAED,MAAM;QACF,IAAI,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;CACJ;AAtCD,8DAsCC"} \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-filterid.js b/lib.commonjs/providers/subscriber-filterid.js new file mode 100644 index 000000000..e8e1e7729 --- /dev/null +++ b/lib.commonjs/providers/subscriber-filterid.js @@ -0,0 +1,111 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FilterIdPendingSubscriber = exports.FilterIdEventSubscriber = exports.FilterIdSubscriber = void 0; +const subscriber_polling_js_1 = require("./subscriber-polling.js"); +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +class FilterIdSubscriber { + #provider; + #filterIdPromise; + #poller; + #network; + constructor(provider) { + this.#provider = provider; + this.#filterIdPromise = null; + this.#poller = this.#poll.bind(this); + this.#network = null; + } + _subscribe(provider) { + throw new Error("subclasses must override this"); + } + _emitResults(provider, result) { + throw new Error("subclasses must override this"); + } + _recover(provider) { + throw new Error("subclasses must override this"); + } + async #poll(blockNumber) { + try { + if (this.#filterIdPromise == null) { + this.#filterIdPromise = this._subscribe(this.#provider); + } + const filterId = await this.#filterIdPromise; + if (filterId == null) { + this.#provider._recoverSubscriber(this, this._recover(this.#provider)); + return; + } + const network = await this.#provider.getNetwork(); + if (!this.#network) { + this.#network = network; + } + if (this.#network.chainId !== network.chainId) { + throw new Error("chaid changed"); + } + const result = await this.#provider.send("eth_getFilterChanges", [filterId]); + await this._emitResults(this.#provider, result); + } + catch (error) { + console.log("@TODO", error); + } + this.#provider.once("block", this.#poller); + } + #teardown() { + const filterIdPromise = this.#filterIdPromise; + if (filterIdPromise) { + this.#filterIdPromise = null; + filterIdPromise.then((filterId) => { + this.#provider.send("eth_uninstallFilter", [filterId]); + }); + } + } + start() { this.#poll(-2); } + stop() { + this.#teardown(); + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#teardown(); + } + this.#provider.off("block", this.#poller); + } + resume() { this.start(); } +} +exports.FilterIdSubscriber = FilterIdSubscriber; +class FilterIdEventSubscriber extends FilterIdSubscriber { + #event; + constructor(provider, filter) { + super(provider); + this.#event = copy(filter); + } + _recover(provider) { + return new subscriber_polling_js_1.PollingEventSubscriber(provider, this.#event); + } + async _subscribe(provider) { + const filterId = await provider.send("eth_newFilter", [this.#event]); + console.log("____SUB", filterId); + return filterId; + } + async _emitResults(provider, results) { + const network = await provider.getNetwork(); + for (const result of results) { + const log = network.formatter.log(result, provider); + provider.emit(this.#event, log); + } + } +} +exports.FilterIdEventSubscriber = FilterIdEventSubscriber; +class FilterIdPendingSubscriber extends FilterIdSubscriber { + async _subscribe(provider) { + return await provider.send("eth_newPendingTransactionFilter", []); + } + async _emitResults(provider, results) { + const network = await provider.getNetwork(); + for (const result of results) { + provider.emit("pending", network.formatter.hash(result)); + } + } +} +exports.FilterIdPendingSubscriber = FilterIdPendingSubscriber; +//# sourceMappingURL=subscriber-filterid.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-filterid.js.map b/lib.commonjs/providers/subscriber-filterid.js.map new file mode 100644 index 000000000..af60936ee --- /dev/null +++ b/lib.commonjs/providers/subscriber-filterid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-filterid.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-filterid.ts"],"names":[],"mappings":";;;AAA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QAAQ,CAAC,IAAI,CAAC,iCAAiC,EAAE,EAAG,CAAC,CAAC;IACvE,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA4B,EAAE,OAAmB;QAChE,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,UAAU,EAAE,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;YAC1B,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;SAC5D;IACL,CAAC;CACJ;AAXD,8DAWC"} \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-hotswap.js b/lib.commonjs/providers/subscriber-hotswap.js new file mode 100644 index 000000000..a7f27e7ad --- /dev/null +++ b/lib.commonjs/providers/subscriber-hotswap.js @@ -0,0 +1,43 @@ +"use strict"; +/* +import { Subscriber } from "./abstract-provider.js"; + +export class HotSwapSubscriber implements Subscriber { + #target?: Subscriber; + + _switchSubscriber(subscriber: Subscriber): void { + this.#target = subscriber; + } + + start(): void { + if (this.#target) { return this.#target.start(); } + return super.start(); + } + + stop(): void { + if (this.#target) { return this.#target.stop(); } + return super.stop(); + } + + pause(dropWhilePaused?: boolean): void { + if (this.#target) { return this.#target.pause(dropWhilePaused); } + return super.pause(dropWhilePaused); + } + + resume(): void { + if (this.#target) { return this.#target.resume(); } + return super.resume(); + } + + set pollingInterval(value: number) { + if (this.#target) { return this.#target.pollingInterval = value; } + return super.pollingInterval = value; + } + + get pollingInterval(): number { + if (this.#target) { return this.#target.pollingInterval; } + return super.pollingInterval; + } +} +*/ +//# sourceMappingURL=subscriber-hotswap.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-hotswap.js.map b/lib.commonjs/providers/subscriber-hotswap.js.map new file mode 100644 index 000000000..c8457b9ba --- /dev/null +++ b/lib.commonjs/providers/subscriber-hotswap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-hotswap.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-hotswap.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwCE"} \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-polling.js b/lib.commonjs/providers/subscriber-polling.js new file mode 100644 index 000000000..6661d5a27 --- /dev/null +++ b/lib.commonjs/providers/subscriber-polling.js @@ -0,0 +1,183 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PollingEventSubscriber = exports.PollingTransactionSubscriber = exports.PollingOrphanSubscriber = exports.OnBlockSubscriber = exports.PollingBlockSubscriber = exports.getPollingSubscriber = void 0; +const data_js_1 = require("../utils/data.js"); +const logger_js_1 = require("../utils/logger.js"); +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +function getPollingSubscriber(provider, event) { + if (event === "block") { + return new PollingBlockSubscriber(provider); + } + if ((0, data_js_1.isHexString)(event, 32)) { + return new PollingTransactionSubscriber(provider, event); + } + return logger_js_1.logger.throwError("unsupported polling event", "UNSUPPORTED_OPERATION", { + operation: "getPollingSubscriber", info: { event } + }); +} +exports.getPollingSubscriber = getPollingSubscriber; +// @TODO: refactor this +class PollingBlockSubscriber { + #provider; + #poller; + #interval; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + constructor(provider) { + this.#provider = provider; + this.#poller = null; + this.#interval = 4000; + this.#blockNumber = -2; + } + get pollingInterval() { return this.#interval; } + set pollingInterval(value) { this.#interval = value; } + async #poll() { + const blockNumber = await this.#provider.getBlockNumber(); + if (this.#blockNumber === -2) { + this.#blockNumber = blockNumber; + return; + } + // @TODO: Put a cap on the maximum number of events per loop? + if (blockNumber !== this.#blockNumber) { + for (let b = this.#blockNumber + 1; b <= blockNumber; b++) { + this.#provider.emit("block", b); + } + this.#blockNumber = blockNumber; + } + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + start() { + if (this.#poller) { + throw new Error("subscriber already running"); + } + this.#poll(); + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + stop() { + if (!this.#poller) { + throw new Error("subscriber not running"); + } + this.#provider._clearTimeout(this.#poller); + this.#poller = null; + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +exports.PollingBlockSubscriber = PollingBlockSubscriber; +class OnBlockSubscriber { + #provider; + #poll; + constructor(provider) { + this.#provider = provider; + this.#poll = (blockNumber) => { + this._poll(blockNumber, this.#provider); + }; + } + async _poll(blockNumber, provider) { + throw new Error("sub-classes must override this"); + } + start() { + this.#poll(-2); + this.#provider.on("block", this.#poll); + } + stop() { + this.#provider.off("block", this.#poll); + } + pause(dropWhilePaused) { this.stop(); } + resume() { this.start(); } +} +exports.OnBlockSubscriber = OnBlockSubscriber; +class PollingOrphanSubscriber extends OnBlockSubscriber { + #filter; + constructor(provider, filter) { + super(provider); + this.#filter = copy(filter); + } + async _poll(blockNumber, provider) { + throw new Error("@TODO"); + console.log(this.#filter); + } +} +exports.PollingOrphanSubscriber = PollingOrphanSubscriber; +class PollingTransactionSubscriber extends OnBlockSubscriber { + #hash; + constructor(provider, hash) { + super(provider); + this.#hash = hash; + } + async _poll(blockNumber, provider) { + const tx = await provider.getTransactionReceipt(this.#hash); + if (tx) { + provider.emit(this.#hash, tx); + } + } +} +exports.PollingTransactionSubscriber = PollingTransactionSubscriber; +class PollingEventSubscriber { + #provider; + #filter; + #poller; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + constructor(provider, filter) { + this.#provider = provider; + this.#filter = copy(filter); + this.#poller = this.#poll.bind(this); + this.#blockNumber = -2; + } + async #poll(blockNumber) { + // The initial block hasn't been determined yet + if (this.#blockNumber === -2) { + return; + } + const filter = copy(this.#filter); + filter.fromBlock = this.#blockNumber + 1; + filter.toBlock = blockNumber; + const logs = await this.#provider.getLogs(filter); + // No logs could just mean the node has not indexed them yet, + // so we keep a sliding window of 60 blocks to keep scanning + if (logs.length === 0) { + if (this.#blockNumber < blockNumber - 60) { + this.#blockNumber = blockNumber - 60; + } + return; + } + this.#blockNumber = blockNumber; + for (const log of logs) { + this.#provider.emit(this.#filter, log); + } + } + start() { + if (this.#blockNumber === -2) { + this.#provider.getBlockNumber().then((blockNumber) => { + this.#blockNumber = blockNumber; + }); + } + this.#provider.on("block", this.#poller); + } + stop() { + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +exports.PollingEventSubscriber = PollingEventSubscriber; +//# sourceMappingURL=subscriber-polling.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber-polling.js.map b/lib.commonjs/providers/subscriber-polling.js.map new file mode 100644 index 000000000..6c18a9f98 --- /dev/null +++ b/lib.commonjs/providers/subscriber-polling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-polling.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-polling.ts"],"names":[],"mappings":";;;AAAA,8CAA+C;AAI/C,kDAA4C;AAE5C,SAAS,IAAI,CAAC,GAAQ;IAClB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,SAAgB,oBAAoB,CAAC,QAA0B,EAAE,KAAoB;IACjF,IAAI,KAAK,KAAK,OAAO,EAAE;QAAE,OAAO,IAAI,sBAAsB,CAAC,QAAQ,CAAC,CAAC;KAAE;IACvE,IAAI,IAAA,qBAAW,EAAC,KAAK,EAAE,EAAE,CAAC,EAAE;QAAE,OAAO,IAAI,4BAA4B,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;KAAE;IAEzF,OAAO,kBAAM,CAAC,UAAU,CAAC,2BAA2B,EAAE,uBAAuB,EAAE;QAC3E,SAAS,EAAE,sBAAsB,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE;KACrD,CA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,EAAE,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,EAAE;gBACjD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;YACpC,CAAC,CAAC,CAAC;SACN;QACD,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI;QACA,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,eAAyB;QAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,IAAI,eAAe,EAAE;YAAE,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;SAAE;IACpD,CAAC;IAED,MAAM;QACF,IAAI,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;CACJ;AA9DD,wDA8DC"} \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber.js b/lib.commonjs/providers/subscriber.js new file mode 100644 index 000000000..b5d01060f --- /dev/null +++ b/lib.commonjs/providers/subscriber.js @@ -0,0 +1,57 @@ +"use strict"; +/* +import { defineProperties } from "@ethersproject/properties"; +export type EventCommon = "block" | "debug" | "blockObject"; + +export type Event = EventCommon | string | { address?: string, topics: Array> } + +export type EventLike = Event | Array; + +export function getTag(eventName: Event): string { + if (typeof(eventName) === "string") { return eventName; } + + if (typeof(eventName) === "object") { + return (eventName.address || "*") + (eventName.topics || []).map((topic) => { + if (typeof(topic) === "string") { return topic; } + return topic.join("|"); + }).join("&"); + } + + throw new Error("FOO"); +} + +export function getEvent(tag: string): Event { +} + +let nextId = 1; + +export class Subscriber { + readonly id!: number; + readonly tag!: string; + + #paused: boolean; + #blockNumber: number; + + constructor(tag: string) { + this.#paused = false; + this.#blockNumber = -1; + defineProperties(this, { id: nextId++, tag }); + } + + get blockNumber(): number { + return this.#blockNumber; + } + _setBlockNumber(blockNumber: number): void { this.#blockNumber = blockNumber; } + + setup(): void { } + teardown(): void { } + + isPaused(): boolean { return this.#paused; } + pause(): void { this.#paused = true; } + resume(): void { this.#paused = false; } + + resubscribeInfo(): string { return this.tag; } + resubscribe(info: string): boolean { return true; } +} +*/ +//# sourceMappingURL=subscriber.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/subscriber.js.map b/lib.commonjs/providers/subscriber.js.map new file mode 100644 index 000000000..d30b7a493 --- /dev/null +++ b/lib.commonjs/providers/subscriber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsDE"} \ No newline at end of file diff --git a/lib.commonjs/providers/ws-browser.js b/lib.commonjs/providers/ws-browser.js new file mode 100644 index 000000000..44b43a07d --- /dev/null +++ b/lib.commonjs/providers/ws-browser.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocket = void 0; +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const _WebSocket = getGlobal().WebSocket; +exports.WebSocket = _WebSocket; +//# sourceMappingURL=ws-browser.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/ws-browser.js.map b/lib.commonjs/providers/ws-browser.js.map new file mode 100644 index 000000000..a6800e42e --- /dev/null +++ b/lib.commonjs/providers/ws-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws-browser.js","sourceRoot":"","sources":["../../src.ts/providers/ws-browser.ts"],"names":[],"mappings":";;;AACA,SAAS,SAAS;IAChB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IACjD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAAE,OAAO,MAAM,CAAC;KAAE;IACrD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAAE,OAAO,MAAM,CAAC;KAAE;IACrD,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,CAAC;AAAA,CAAC;AAEF,MAAM,UAAU,GAAG,SAAS,EAAE,CAAC,SAAS,CAAC;AAElB,+BAAS"} \ No newline at end of file diff --git a/lib.commonjs/providers/ws.js b/lib.commonjs/providers/ws.js new file mode 100644 index 000000000..c06b35808 --- /dev/null +++ b/lib.commonjs/providers/ws.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocket = void 0; +var ws_1 = require("ws"); +Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function () { return ws_1.WebSocket; } }); +//# sourceMappingURL=ws.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/ws.js.map b/lib.commonjs/providers/ws.js.map new file mode 100644 index 000000000..15568f152 --- /dev/null +++ b/lib.commonjs/providers/ws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../src.ts/providers/ws.ts"],"names":[],"mappings":";;;AAAA,yBAA+B;AAAtB,+FAAA,SAAS,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/transaction/accesslist.js b/lib.commonjs/transaction/accesslist.js new file mode 100644 index 000000000..170c51e52 --- /dev/null +++ b/lib.commonjs/transaction/accesslist.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.accessListify = void 0; +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../utils/index.js"); +function accessSetify(addr, storageKeys) { + return { + address: (0, index_js_1.getAddress)(addr), + storageKeys: (storageKeys || []).map((storageKey, index) => { + if ((0, index_js_2.dataLength)(storageKey) !== 32) { + //logger.throwArgumentError("invalid access list storageKey", `accessList[${ addr }> + throw new Error(""); + } + return storageKey.toLowerCase(); + }) + }; +} +function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index) => { + if (Array.isArray(set)) { + if (set.length > 2) { + //logger.throwArgumentError("access list expected to be [ address, storageKeys[> + throw new Error(""); + } + return accessSetify(set[0], set[1]); + } + return accessSetify(set.address, set.storageKeys); + }); + } + const result = Object.keys(value).map((addr) => { + const storageKeys = value[addr].reduce((accum, storageKey) => { + accum[storageKey] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); + }); + result.sort((a, b) => (a.address.localeCompare(b.address))); + return result; +} +exports.accessListify = accessListify; +//# sourceMappingURL=accesslist.js.map \ No newline at end of file diff --git a/lib.commonjs/transaction/accesslist.js.map b/lib.commonjs/transaction/accesslist.js.map new file mode 100644 index 000000000..2f5951ca4 --- /dev/null +++ b/lib.commonjs/transaction/accesslist.js.map @@ -0,0 +1 @@ +{"version":3,"file":"accesslist.js","sourceRoot":"","sources":["../../src.ts/transaction/accesslist.ts"],"names":[],"mappings":";;;AAAA,kDAAiD;AACjD,gDAA+C;AAK/C,SAAS,YAAY,CAAC,IAAY,EAAE,WAA0B;IAC1D,OAAO;QACH,OAAO,EAAE,IAAA,qBAAU,EAAC,IAAI,CAAC;QACzB,WAAW,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE;YACvD,IAAI,IAAA,qBAAU,EAAC,UAAU,CAAC,KAAK,EAAE,EAAE;gBAC/B,oFAAoF;gBACpF,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;aACvB;YACD,OAAO,UAAU,CAAC,WAAW,EAAE,CAAC;QACpC,CAAC,CAAC;KACL,CAAC;AACN,CAAC;AAED,SAAgB,aAAa,CAAC,KAAoB;IAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACtB,OAA0F,KAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YAChH,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;gBACpB,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE;oBAChB,gFAAgF;oBAChF,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;iBACvB;gBACD,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;aACtC;YACD,OAAO,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;KACN;IAED,MAAM,MAAM,GAA2D,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACnG,MAAM,WAAW,GAAyB,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE;YAC/E,KAAK,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;YACzB,OAAO,KAAK,CAAC;QACjB,CAAC,EAAwB,EAAG,CAAC,CAAC;QAC9B,OAAO,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;IAC9D,CAAC,CAAC,CAAC;IACH,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAClB,CAAC;AAvBD,sCAuBC"} \ No newline at end of file diff --git a/lib.commonjs/transaction/address.js b/lib.commonjs/transaction/address.js new file mode 100644 index 000000000..8c896894f --- /dev/null +++ b/lib.commonjs/transaction/address.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.recoverAddress = exports.computeAddress = void 0; +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../crypto/index.js"); +function computeAddress(key) { + const publicKey = index_js_2.SigningKey.computePublicKey(key, false); + return (0, index_js_1.getAddress)((0, index_js_2.keccak256)("0x" + publicKey.substring(4)).substring(26)); +} +exports.computeAddress = computeAddress; +function recoverAddress(digest, signature) { + return computeAddress(index_js_2.SigningKey.recoverPublicKey(digest, signature)); +} +exports.recoverAddress = recoverAddress; +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/lib.commonjs/transaction/address.js.map b/lib.commonjs/transaction/address.js.map new file mode 100644 index 000000000..7fea0b980 --- /dev/null +++ b/lib.commonjs/transaction/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../src.ts/transaction/address.ts"],"names":[],"mappings":";;;AAAA,kDAAiD;AACjD,iDAA2D;AAM3D,SAAgB,cAAc,CAAC,GAAW;IACtC,MAAM,SAAS,GAAG,qBAAU,CAAC,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAC1D,OAAO,IAAA,qBAAU,EAAC,IAAA,oBAAS,EAAC,IAAI,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;AAC9E,CAAC;AAHD,wCAGC;AAED,SAAgB,cAAc,CAAC,MAAiB,EAAE,SAAwB;IACtE,OAAO,cAAc,CAAC,qBAAU,CAAC,gBAAgB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAC1E,CAAC;AAFD,wCAEC"} \ No newline at end of file diff --git a/lib.commonjs/transaction/index.js b/lib.commonjs/transaction/index.js new file mode 100644 index 000000000..e8ba294a8 --- /dev/null +++ b/lib.commonjs/transaction/index.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transaction = exports.recoverAddress = exports.computeAddress = exports.accessListify = void 0; +var accesslist_js_1 = require("./accesslist.js"); +Object.defineProperty(exports, "accessListify", { enumerable: true, get: function () { return accesslist_js_1.accessListify; } }); +var address_js_1 = require("./address.js"); +Object.defineProperty(exports, "computeAddress", { enumerable: true, get: function () { return address_js_1.computeAddress; } }); +Object.defineProperty(exports, "recoverAddress", { enumerable: true, get: function () { return address_js_1.recoverAddress; } }); +var transaction_js_1 = require("./transaction.js"); +Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return transaction_js_1.Transaction; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/transaction/index.js.map b/lib.commonjs/transaction/index.js.map new file mode 100644 index 000000000..1193ec349 --- /dev/null +++ b/lib.commonjs/transaction/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/transaction/index.ts"],"names":[],"mappings":";;;AAUA,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AACtB,2CAA8D;AAArD,4GAAA,cAAc,OAAA;AAAE,4GAAA,cAAc,OAAA;AACvC,mDAA+C;AAAtC,6GAAA,WAAW,OAAA"} \ 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 000000000..7557be82e --- /dev/null +++ b/lib.commonjs/transaction/transaction.js @@ -0,0 +1,579 @@ +"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"); +const address_js_1 = require("./address.js"); +const BN_0 = BigInt(0); +const BN_2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +function handleAddress(value) { + if (value === "0x") { + return null; + } + return (0, index_js_1.getAddress)(value); +} +function handleData(value, param) { + try { + return (0, index_js_3.hexlify)(value); + } + catch (error) { + return index_js_3.logger.throwArgumentError("invalid data", param, value); + } +} +function handleAccessList(value, param) { + try { + return (0, accesslist_js_1.accessListify)(value); + } + catch (error) { + return index_js_3.logger.throwArgumentError("invalid accessList", param, value); + } +} +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; + } + return index_js_3.logger.getNumber(_value, param); +} +function handleUint(_value, param) { + if (_value === "0x") { + return BN_0; + } + const value = index_js_3.logger.getBigInt(_value, param); + if (value > BN_MAX_UINT) { + index_js_3.logger.throwArgumentError("value exceeds uint size", param, value); + } + return value; +} +function formatNumber(_value, name) { + const value = index_js_3.logger.getBigInt(_value, "value"); + const result = (0, index_js_3.toArray)(value); + if (result.length > 32) { + index_js_3.logger.throwArgumentError(`value too large`, `tx.${name}`, value); + } + return result; +} +function formatAccessList(value) { + return (0, accesslist_js_1.accessListify)(value).map((set) => [set.address, set.storageKeys]); +} +function _parseLegacy(data) { + const fields = (0, index_js_3.decodeRlp)(data); + if (!Array.isArray(fields) || (fields.length !== 9 && fields.length !== 6)) { + return index_js_3.logger.throwArgumentError("invalid field count for legacy transaction", "data", data); + } + const tx = { + type: 0, + nonce: handleNumber(fields[0], "nonce"), + gasPrice: handleUint(fields[1], "gasPrice"), + gasLimit: handleUint(fields[2], "gasLimit"), + to: handleAddress(fields[3]), + value: handleUint(fields[4], "value"), + data: handleData(fields[5], "dta"), + chainId: BN_0 + }; + // Legacy unsigned transaction + if (fields.length === 6) { + return tx; + } + const v = handleUint(fields[6], "v"); + const r = handleUint(fields[7], "r"); + const s = handleUint(fields[8], "s"); + if (r === BN_0 && s === BN_0) { + // EIP-155 unsigned transaction + tx.chainId = v; + } + else { + // Compute the EIP-155 chain ID (or 0 for legacy) + let chainId = (v - BN_35) / BN_2; + if (chainId < BN_0) { + chainId = BN_0; + } + tx.chainId = chainId; + // Signed Legacy Transaction + if (chainId === BN_0 && (v < BN_27 || v > BN_28)) { + index_js_3.logger.throwArgumentError("non-canonical legacy v", "v", fields[6]); + } + tx.signature = index_js_2.Signature.from({ + r: (0, index_js_3.zeroPadValue)(fields[7], 32), + s: (0, index_js_3.zeroPadValue)(fields[8], 32), + v + }); + tx.hash = (0, index_js_2.keccak256)(data); + } + return tx; +} +function _serializeLegacy(tx, sig) { + const fields = [ + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? (0, index_js_1.getAddress)(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + ]; + let chainId = BN_0; + if (tx.chainId != null) { + // A chainId was provided; if non-zero we'll use EIP-155 + chainId = index_js_3.logger.getBigInt(tx.chainId, "tx.chainId"); + // We have a chainId in the tx and an EIP-155 v in the signature, + // make sure they agree with each other + if (sig && sig.networkV != null && sig.legacyChainId !== chainId) { + index_js_3.logger.throwArgumentError("tx.chainId/sig.v mismatch", "sig", sig); + } + } + else if (sig) { + // No chainId provided, but the signature is signing with EIP-155; derive chainId + const legacy = sig.legacyChainId; + if (legacy != null) { + chainId = legacy; + } + } + // Requesting an unsigned transaction + if (!sig) { + // We have an EIP-155 transaction (chainId was specified and non-zero) + if (chainId !== BN_0) { + fields.push((0, index_js_3.toArray)(chainId)); + fields.push("0x"); + fields.push("0x"); + } + return (0, index_js_3.encodeRlp)(fields); + } + // We pushed a chainId and null r, s on for hashing only; remove those + let v = BigInt(27 + sig.yParity); + if (chainId !== BN_0) { + v = index_js_2.Signature.getChainIdV(chainId, sig.v); + } + else if (BigInt(sig.v) !== v) { + index_js_3.logger.throwArgumentError("tx.chainId/sig.v mismatch", "sig", sig); + } + fields.push((0, index_js_3.toArray)(v)); + fields.push((0, index_js_3.toArray)(sig.r)); + fields.push((0, index_js_3.toArray)(sig.s)); + return (0, index_js_3.encodeRlp)(fields); +} +function _parseEipSignature(tx, fields, serialize) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } + catch (error) { + return index_js_3.logger.throwArgumentError("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 _parseEip1559(data) { + const fields = (0, index_js_3.decodeRlp)(index_js_3.logger.getBytes(data).slice(1)); + if (!Array.isArray(fields) || (fields.length !== 9 && fields.length !== 12)) { + index_js_3.logger.throwArgumentError("invalid field count for transaction type: 2", "data", (0, index_js_3.hexlify)(data)); + } + const maxPriorityFeePerGas = handleUint(fields[2], "maxPriorityFeePerGas"); + const maxFeePerGas = handleUint(fields[3], "maxFeePerGas"); + const tx = { + type: 2, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: maxPriorityFeePerGas, + maxFeePerGas: maxFeePerGas, + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: handleData(fields[7], "data"), + accessList: handleAccessList(fields[8], "accessList"), + }; + // Unsigned EIP-1559 Transaction + if (fields.length === 9) { + return tx; + } + tx.hash = (0, index_js_2.keccak256)(data); + _parseEipSignature(tx, fields.slice(9), _serializeEip1559); + return tx; +} +function _serializeEip1559(tx, sig) { + const fields = [ + formatNumber(tx.chainId || 0, "chainId"), + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? (0, index_js_1.getAddress)(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + (formatAccessList(tx.accessList || [])) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push((0, index_js_3.toArray)(sig.r)); + fields.push((0, index_js_3.toArray)(sig.s)); + } + return (0, index_js_3.concat)(["0x02", (0, index_js_3.encodeRlp)(fields)]); +} +function _parseEip2930(data) { + const fields = (0, index_js_3.decodeRlp)(index_js_3.logger.getBytes(data).slice(1)); + if (!Array.isArray(fields) || (fields.length !== 8 && fields.length !== 11)) { + index_js_3.logger.throwArgumentError("invalid field count for transaction type: 1", "data", (0, index_js_3.hexlify)(data)); + } + const tx = { + type: 1, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + gasPrice: handleUint(fields[2], "gasPrice"), + gasLimit: handleUint(fields[3], "gasLimit"), + to: handleAddress(fields[4]), + value: handleUint(fields[5], "value"), + data: handleData(fields[6], "data"), + accessList: handleAccessList(fields[7], "accessList") + }; + // Unsigned EIP-2930 Transaction + if (fields.length === 8) { + return tx; + } + tx.hash = (0, index_js_2.keccak256)(data); + _parseEipSignature(tx, fields.slice(8), _serializeEip2930); + return tx; +} +function _serializeEip2930(tx, sig) { + const fields = [ + formatNumber(tx.chainId || 0, "chainId"), + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? (0, index_js_1.getAddress)(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + (formatAccessList(tx.accessList || [])) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "recoveryParam")); + fields.push((0, index_js_3.toArray)(sig.r)); + fields.push((0, index_js_3.toArray)(sig.s)); + } + return (0, index_js_3.concat)(["0x01", (0, index_js_3.encodeRlp)(fields)]); +} +class Transaction { + #props; + // A type of null indicates the type will be populated automatically + get type() { return (0, index_js_3.getStore)(this.#props, "type"); } + get typeName() { + switch (this.type) { + case 0: return "legacy"; + case 1: return "eip-2930"; + case 2: return "eip-1559"; + } + return null; + } + set type(value) { + switch (value) { + case null: + (0, index_js_3.setStore)(this.#props, "type", null); + break; + case 0: + case "legacy": + (0, index_js_3.setStore)(this.#props, "type", 0); + break; + case 1: + case "berlin": + case "eip-2930": + (0, index_js_3.setStore)(this.#props, "type", 1); + break; + case 2: + case "london": + case "eip-1559": + (0, index_js_3.setStore)(this.#props, "type", 2); + break; + default: + throw new Error(`unsupported transaction type`); + } + } + get to() { return (0, index_js_3.getStore)(this.#props, "to"); } + set to(value) { + (0, index_js_3.setStore)(this.#props, "to", (value == null) ? null : (0, index_js_1.getAddress)(value)); + } + get nonce() { return (0, index_js_3.getStore)(this.#props, "nonce"); } + set nonce(value) { (0, index_js_3.setStore)(this.#props, "nonce", index_js_3.logger.getNumber(value, "value")); } + get gasLimit() { return (0, index_js_3.getStore)(this.#props, "gasLimit"); } + set gasLimit(value) { (0, index_js_3.setStore)(this.#props, "gasLimit", index_js_3.logger.getBigInt(value)); } + get gasPrice() { + const value = (0, index_js_3.getStore)(this.#props, "gasPrice"); + if (value == null && (this.type === 0 || this.type === 1)) { + return BN_0; + } + return value; + } + set gasPrice(value) { + (0, index_js_3.setStore)(this.#props, "gasPrice", (value == null) ? null : index_js_3.logger.getBigInt(value, "gasPrice")); + } + get maxPriorityFeePerGas() { + const value = (0, index_js_3.getStore)(this.#props, "maxPriorityFeePerGas"); + if (value == null && this.type === 2) { + return BN_0; + } + return value; + } + set maxPriorityFeePerGas(value) { + (0, index_js_3.setStore)(this.#props, "maxPriorityFeePerGas", (value == null) ? null : index_js_3.logger.getBigInt(value, "maxPriorityFeePerGas")); + } + get maxFeePerGas() { + const value = (0, index_js_3.getStore)(this.#props, "maxFeePerGas"); + if (value == null && this.type === 2) { + return BN_0; + } + return value; + } + set maxFeePerGas(value) { + (0, index_js_3.setStore)(this.#props, "maxFeePerGas", (value == null) ? null : index_js_3.logger.getBigInt(value, "maxFeePerGas")); + } + get data() { return (0, index_js_3.getStore)(this.#props, "data"); } + set data(value) { (0, index_js_3.setStore)(this.#props, "data", (0, index_js_3.hexlify)(value)); } + get value() { return (0, index_js_3.getStore)(this.#props, "value"); } + set value(value) { + (0, index_js_3.setStore)(this.#props, "value", index_js_3.logger.getBigInt(value, "value")); + } + get chainId() { return (0, index_js_3.getStore)(this.#props, "chainId"); } + set chainId(value) { (0, index_js_3.setStore)(this.#props, "chainId", index_js_3.logger.getBigInt(value)); } + get signature() { return (0, index_js_3.getStore)(this.#props, "sig") || null; } + set signature(value) { + (0, index_js_3.setStore)(this.#props, "sig", (value == null) ? null : index_js_2.Signature.from(value)); + } + get accessList() { + const value = (0, index_js_3.getStore)(this.#props, "accessList") || null; + if (value == null && (this.type === 1 || this.type === 2)) { + return []; + } + return value; + } + set accessList(value) { + (0, index_js_3.setStore)(this.#props, "accessList", (value == null) ? null : (0, accesslist_js_1.accessListify)(value)); + } + constructor() { + this.#props = { + type: null, + to: null, + nonce: 0, + gasLimit: BigInt(0), + gasPrice: null, + maxPriorityFeePerGas: null, + maxFeePerGas: null, + data: "0x", + value: BigInt(0), + chainId: BigInt(0), + sig: null, + accessList: null + }; + } + get hash() { + if (this.signature == null) { + throw new Error("cannot hash unsigned transaction; maybe you meant .unsignedHash"); + } + return (0, index_js_2.keccak256)(this.serialized); + } + get unsignedHash() { + return (0, index_js_2.keccak256)(this.unsignedSerialized); + } + get from() { + if (this.signature == null) { + return null; + } + return (0, address_js_1.recoverAddress)(this.unsignedSerialized, this.signature); + } + get fromPublicKey() { + if (this.signature == null) { + return null; + } + // use ecrecover + return ""; + } + isSigned() { + return this.signature != null; + } + get serialized() { + if (this.signature == null) { + throw new Error("cannot serialize unsigned transaction; maybe you meant .unsignedSerialized"); + } + const types = this.inferTypes(); + if (types.length !== 1) { + throw new Error("cannot determine transaction type; specify type manually"); + } + switch (types[0]) { + case 0: + return _serializeLegacy(this, this.signature); + case 1: + return _serializeEip2930(this, this.signature); + case 2: + return _serializeEip1559(this, this.signature); + } + throw new Error("unsupported type"); + } + get unsignedSerialized() { + const types = this.inferTypes(); + if (types.length !== 1) { + throw new Error("cannot determine transaction type; specify type manually"); + } + switch (types[0]) { + case 0: + return _serializeLegacy(this); + case 1: + return _serializeEip2930(this); + case 2: + return _serializeEip1559(this); + } + throw new Error("unsupported type"); + } + // Validates properties and lists possible types this transaction adheres to + inferTypes() { + // Checks that there are no conflicting properties set + const hasGasPrice = this.gasPrice != null; + const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != 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) { + if (this.maxFeePerGas < this.maxPriorityFeePerGas) { + throw new Error("priorityFee cannot be more than maxFee"); + } + } + //if (this.type === 2 && hasGasPrice) { + // throw new Error("eip-1559 transaction cannot have gasPrice"); + //} + if ((this.type === 0 || this.type === 1) && hasFee) { + throw new Error("transaction type cannot have maxFeePerGas or maxPriorityFeePerGas"); + } + if (this.type === 0 && hasAccessList) { + throw new Error("legacy transaction cannot have accessList"); + } + const types = []; + // Explicit type + if (this.type != null) { + types.push(this.type); + } + else { + if (hasFee) { + types.push(2); + } + else if (hasGasPrice) { + types.push(1); + if (!hasAccessList) { + types.push(0); + } + } + else if (hasAccessList) { + types.push(1); + types.push(2); + } + else { + types.push(0); + types.push(1); + types.push(2); + } + } + types.sort(); + return types; + } + isLegacy() { return (this.type === 0); } + isBerlin() { return (this.type === 1); } + isLondon() { return (this.type === 2); } + clone() { + return Transaction.from(this); + } + freeze() { + if (this.#props.sig) { + this.#props.sig = (this.#props.sig.clone().freeze()); + } + if (this.#props.accessList) { + this.#props.accessList = Object.freeze(this.#props.accessList.map((set) => { + Object.freeze(set.storageKeys); + return Object.freeze(set); + })); + } + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + static from(tx) { + if (typeof (tx) === "string") { + const payload = index_js_3.logger.getBytes(tx); + if (payload[0] >= 0x7f) { // @TODO: > vs >= ?? + return Transaction.from(_parseLegacy(payload)); + } + switch (payload[0]) { + case 1: return Transaction.from(_parseEip2930(payload)); + case 2: return Transaction.from(_parseEip1559(payload)); + } + throw new Error("unsupported transaction type"); + } + const result = new Transaction(); + 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.gasPrice != null) { + result.gasPrice = tx.gasPrice; + } + 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.hash != null) { + if (result.isSigned()) { + if (result.hash !== tx.hash) { + throw new Error("hash mismatch"); + } + } + else { + throw new Error("unsigned transaction cannot have a hashs"); + } + } + if (tx.from != null) { + if (result.isSigned()) { + if (result.from.toLowerCase() !== (tx.from || "").toLowerCase()) { + throw new Error("from mismatch"); + } + } + else { + throw new Error("unsigned transaction cannot have a from"); + } + } + 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 000000000..15e292b31 --- /dev/null +++ b/lib.commonjs/transaction/transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.js","sourceRoot":"","sources":["../../src.ts/transaction/transaction.ts"],"names":[],"mappings":";;;AACA,kDAAiD;AACjD,iDAA0D;AAC1D,gDAE2B;AAE3B,mDAAgD;AAChD,6CAA8C;AAQ9C,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAA;AACxB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAA;AACxB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;IAClB,CAAC;CACJ;AArUD,kCAqUC"} \ No newline at end of file diff --git a/lib.commonjs/utils/base58.js b/lib.commonjs/utils/base58.js new file mode 100644 index 000000000..ca6ad6381 --- /dev/null +++ b/lib.commonjs/utils/base58.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeBase58 = exports.encodeBase58 = void 0; +const logger_js_1 = require("./logger.js"); +const maths_js_1 = require("./maths.js"); +const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +let Lookup = null; +function getAlpha(letter) { + if (Lookup == null) { + Lookup = {}; + for (let i = 0; i < Alphabet.length; i++) { + Lookup[Alphabet[i]] = BigInt(i); + } + } + const result = Lookup[letter]; + if (result == null) { + logger_js_1.logger.throwArgumentError(`invalid base58 value`, "letter", letter); + } + return result; +} +const BN_0 = BigInt(0); +const BN_58 = BigInt(58); +/** + * Encode %%value%% as Base58-encoded data. + */ +function encodeBase58(_value) { + let value = (0, maths_js_1.toBigInt)(logger_js_1.logger.getBytes(_value)); + let result = ""; + while (value) { + result = Alphabet[Number(value % BN_58)] + result; + value /= BN_58; + } + return result; +} +exports.encodeBase58 = encodeBase58; +/** + * Decode the Base58-encoded %%value%%. + */ +function decodeBase58(value) { + let result = BN_0; + for (let i = 0; i < value.length; i++) { + result *= BN_58; + result += getAlpha(value[i]); + } + return (0, maths_js_1.toHex)(result); +} +exports.decodeBase58 = decodeBase58; +//# sourceMappingURL=base58.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/base58.js.map b/lib.commonjs/utils/base58.js.map new file mode 100644 index 000000000..e312acdb4 --- /dev/null +++ b/lib.commonjs/utils/base58.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base58.js","sourceRoot":"","sources":["../../src.ts/utils/base58.ts"],"names":[],"mappings":";;;AACA,2CAAqC;AACrC,yCAA6C;AAK7C,MAAM,QAAQ,GAAG,4DAA4D,CAAC;AAC9E,IAAI,MA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I,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KAChC;IACD,OAAO,IAAA,gBAAK,EAAC,MAAM,CAAC,CAAC;AACzB,CAAC;AAPD,oCAOC"} \ No newline at end of file diff --git a/lib.commonjs/utils/base64-browser.js b/lib.commonjs/utils/base64-browser.js new file mode 100644 index 000000000..20fde32ae --- /dev/null +++ b/lib.commonjs/utils/base64-browser.js @@ -0,0 +1,24 @@ +"use strict"; +// utils/base64-browser +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeBase64 = exports.decodeBase64 = void 0; +const logger_js_1 = require("./logger.js"); +function decodeBase64(textData) { + textData = atob(textData); + const data = new Uint8Array(textData.length); + for (let i = 0; i < textData.length; i++) { + data[i] = textData.charCodeAt(i); + } + return logger_js_1.logger.getBytes(data); +} +exports.decodeBase64 = decodeBase64; +function encodeBase64(_data) { + const data = logger_js_1.logger.getBytes(_data); + let textData = ""; + for (let i = 0; i < data.length; i++) { + textData += String.fromCharCode(data[i]); + } + return btoa(textData); +} +exports.encodeBase64 = encodeBase64; +//# sourceMappingURL=base64-browser.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/base64-browser.js.map b/lib.commonjs/utils/base64-browser.js.map new file mode 100644 index 000000000..60a9df832 --- /dev/null +++ b/lib.commonjs/utils/base64-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64-browser.js","sourceRoot":"","sources":["../../src.ts/utils/base64-browser.ts"],"names":[],"mappings":";AACA,uBAAuB;;;AAEvB,2CAAqC;AAKrC,SAAgB,YAAY,CAAC,QAAgB;IACzC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1B,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,IAAI,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;KACpC;IACD,OAAO,kBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAPD,oCAOC;AAED,SAAgB,YAAY,CAAC,KAAgB;IACzC,MAAM,IAAI,GAAG,kBAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAClC,QAAQ,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;KAC5C;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC;AAPD,oCAOC"} \ No newline at end of file diff --git a/lib.commonjs/utils/base64.js b/lib.commonjs/utils/base64.js new file mode 100644 index 000000000..26a0cf44b --- /dev/null +++ b/lib.commonjs/utils/base64.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeBase64 = exports.decodeBase64 = void 0; +const logger_js_1 = require("./logger.js"); +function decodeBase64(textData) { + return logger_js_1.logger.getBytesCopy(Buffer.from(textData, "base64")); +} +exports.decodeBase64 = decodeBase64; +; +function encodeBase64(data) { + return Buffer.from(logger_js_1.logger.getBytes(data)).toString("base64"); +} +exports.encodeBase64 = encodeBase64; +//# sourceMappingURL=base64.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/base64.js.map b/lib.commonjs/utils/base64.js.map new file mode 100644 index 000000000..0319cabe6 --- /dev/null +++ b/lib.commonjs/utils/base64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64.js","sourceRoot":"","sources":["../../src.ts/utils/base64.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AAKrC,SAAgB,YAAY,CAAC,QAAgB;IACzC,OAAO,kBAAM,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AAChE,CAAC;AAFD,oCAEC;AAAA,CAAC;AAEF,SAAgB,YAAY,CAAC,IAAe;IACxC,OAAO,MAAM,CAAC,IAAI,CAAC,kBAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AACjE,CAAC;AAFD,oCAEC"} \ No newline at end of file diff --git a/lib.commonjs/utils/data.js b/lib.commonjs/utils/data.js new file mode 100644 index 000000000..b9a1e8b09 --- /dev/null +++ b/lib.commonjs/utils/data.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.zeroPadBytes = exports.zeroPadValue = exports.stripZerosLeft = exports.dataSlice = exports.dataLength = exports.concat = exports.hexlify = exports.isBytesLike = exports.isHexString = void 0; +const logger_js_1 = require("./logger.js"); +function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (typeof (length) === "number" && value.length !== 2 + 2 * length) { + return false; + } + if (length === true && (value.length % 2) !== 0) { + return false; + } + return true; +} +exports.isHexString = isHexString; +function isBytesLike(value) { + return (isHexString(value, true) || (value instanceof Uint8Array)); +} +exports.isBytesLike = isBytesLike; +const HexCharacters = "0123456789abcdef"; +function hexlify(data) { + const bytes = logger_js_1.logger.getBytes(data); + let result = "0x"; + for (let i = 0; i < bytes.length; i++) { + const v = bytes[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; +} +exports.hexlify = hexlify; +function concat(datas) { + return "0x" + datas.map((d) => hexlify(d).substring(2)).join(""); +} +exports.concat = concat; +function dataLength(data) { + if (isHexString(data, true)) { + return (data.length - 2) / 2; + } + return logger_js_1.logger.getBytes(data).length; +} +exports.dataLength = dataLength; +function dataSlice(data, start, end) { + const bytes = logger_js_1.logger.getBytes(data); + if (end != null && end > bytes.length) { + logger_js_1.logger.throwError("cannot slice beyond data bounds", "BUFFER_OVERRUN", { + buffer: bytes, length: bytes.length, offset: end + }); + } + return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end)); +} +exports.dataSlice = dataSlice; +function stripZerosLeft(data) { + let bytes = hexlify(data).substring(2); + while (bytes.substring(0, 2) == "00") { + bytes = bytes.substring(2); + } + return "0x" + bytes; +} +exports.stripZerosLeft = stripZerosLeft; +function zeroPad(data, length, left) { + const bytes = logger_js_1.logger.getBytes(data); + if (length < bytes.length) { + logger_js_1.logger.throwError("padding exceeds data length", "BUFFER_OVERRUN", { + buffer: new Uint8Array(bytes), + length: length, + offset: length + 1 + }); + } + const result = new Uint8Array(length); + result.fill(0); + if (left) { + result.set(bytes, length - bytes.length); + } + else { + result.set(bytes, 0); + } + return hexlify(result); +} +function zeroPadValue(data, length) { + return zeroPad(data, length, true); +} +exports.zeroPadValue = zeroPadValue; +function zeroPadBytes(data, length) { + return zeroPad(data, length, false); +} +exports.zeroPadBytes = zeroPadBytes; +//# sourceMappingURL=data.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/data.js.map b/lib.commonjs/utils/data.js.map new file mode 100644 index 000000000..65f4896b6 --- /dev/null +++ b/lib.commonjs/utils/data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"data.js","sourceRoot":"","sources":["../../src.ts/utils/data.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AAKrC,SAAgB,WAAW,CAAC,KAAU,EAAE,MAAyB;IAC7D,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE;QAChE,OAAO,KAAK,CAAA;KACf;IAED,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE;QAAE,OAAO,KAAK,CAAC;KAAE;IACrF,IAAI,MAAM,KAAK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AE,gBAAgB,EAAE;YAC9D,MAAM,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC;YAC7B,MAAM,EAAE,MAAM;YACd,MAAM,EAAE,MAAM,GAAG,CAAC;SACrB,CAAC,CAAC;KACN;IAED,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACtC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACf,IAAI,IAAI,EAAE;QACN,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;KAC5C;SAAM;QACH,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;KACxB;IAED,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,SAAgB,YAAY,CAAC,IAAe,EAAE,MAAc;IACxD,OAAO,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC;AAFD,oCAEC;AAED,SAAgB,YAAY,CAAC,IAAe,EAAE,MAAc;IACxD,OAAO,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACxC,CAAC;AAFD,oCAEC"} \ No newline at end of file diff --git a/lib.commonjs/utils/errors.js b/lib.commonjs/utils/errors.js new file mode 100644 index 000000000..a0b980ee4 --- /dev/null +++ b/lib.commonjs/utils/errors.js @@ -0,0 +1,23 @@ +"use strict"; +//export type TransactionReceipt { +//} +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isCallException = exports.isError = void 0; +/** + * try { + * // code.... + * } catch (e) { + * if (isError(e, errors.CALL_EXCEPTION)) { + * console.log(e.data); + * } + * } + */ +function isError(error, code) { + return (error && error.code === code); +} +exports.isError = isError; +function isCallException(error) { + return isError(error, "CALL_EXCEPTION"); +} +exports.isCallException = isCallException; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/errors.js.map b/lib.commonjs/utils/errors.js.map new file mode 100644 index 000000000..abfc186b7 --- /dev/null +++ b/lib.commonjs/utils/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src.ts/utils/errors.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,GAAG;;;AA4QH;;;;;;;;GAQG;AACH,SAAgB,OAAO,CAAqD,KAAU,EAAE,IAAO;IAC3F,OAAO,CAAC,KAAK,IAAkB,KAAM,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AACzD,CAAC;AAFD,0BAEC;AAED,SAAgB,eAAe,CAAC,KAAU;IACtC,OAAO,OAAO,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;AAC5C,CAAC;AAFD,0CAEC"} \ No newline at end of file diff --git a/lib.commonjs/utils/events.js b/lib.commonjs/utils/events.js new file mode 100644 index 000000000..ac6bb3176 --- /dev/null +++ b/lib.commonjs/utils/events.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventPayload = void 0; +const properties_js_1 = require("./properties.js"); +class EventPayload { + filter; + emitter; + #listener; + constructor(emitter, listener, filter) { + this.#listener = listener; + (0, properties_js_1.defineProperties)(this, { emitter, filter }); + } + async removeListener() { + if (this.#listener == null) { + return; + } + await this.emitter.off(this.filter, this.#listener); + } +} +exports.EventPayload = EventPayload; +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/events.js.map b/lib.commonjs/utils/events.js.map new file mode 100644 index 000000000..ade0aca03 --- /dev/null +++ b/lib.commonjs/utils/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src.ts/utils/events.ts"],"names":[],"mappings":";;;AAAA,mDAAmD;AAoBnD,MAAa,YAAY;IACZ,MAAM,CAAK;IAEX,OAAO,CAAuB;IAC9B,SAAS,CAAkB;IAEpC,YAAY,OAA4B,EAAE,QAAyB,EAAE,MAAS;QAC1E,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAA,gCAAgB,EAAoB,IAAI,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IACnE,CAAC;IAED,KAAK,CAAC,cAAc;QAChB,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;YAAE,OAAO;SAAE;QACvC,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;CACJ;AAfD,oCAeC"} \ No newline at end of file diff --git a/lib.commonjs/utils/fetch.js b/lib.commonjs/utils/fetch.js new file mode 100644 index 000000000..303dca970 --- /dev/null +++ b/lib.commonjs/utils/fetch.js @@ -0,0 +1,569 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FetchResponse = exports.FetchRequest = exports.FetchCancelSignal = exports.getIpfsGatewayFunc = void 0; +const base64_js_1 = require("./base64.js"); +const data_js_1 = require("./data.js"); +const logger_js_1 = require("./logger.js"); +const properties_js_1 = require("./properties.js"); +const utf8_js_1 = require("./utf8.js"); +const geturl_js_1 = require("./geturl.js"); +const MAX_ATTEMPTS = 12; +const SLOT_INTERVAL = 250; +// The global FetchGetUrlFunc implementation. +let getUrlFunc = geturl_js_1.getUrl; +const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); +const reIpfs = new RegExp("^ipfs:/\/(ipfs/)?(.*)$", "i"); +// If locked, new Gateways cannot be added +let locked = false; +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs +async function gatewayData(url, signal) { + try { + const match = url.match(reData); + if (!match) { + throw new Error("invalid data"); + } + return new FetchResponse(200, "OK", { + "content-type": (match[1] || "text/plain"), + }, (match[1] ? (0, base64_js_1.decodeBase64)(match[3]) : unpercent(match[3]))); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); + } +} +function getIpfsGatewayFunc(base) { + async function gatewayIpfs(url, signal) { + try { + const match = url.match(reIpfs); + if (!match) { + throw new Error("invalid link"); + } + return new FetchRequest(`${base}${match[2]}`); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); + } + } + return gatewayIpfs; +} +exports.getIpfsGatewayFunc = getIpfsGatewayFunc; +const Gateways = { + "data": gatewayData, + "ipfs": getIpfsGatewayFunc("https:/\/gateway.ipfs.io/ipfs/") +}; +const fetchSignals = new WeakMap(); +class FetchCancelSignal { + #listeners; + #cancelled; + constructor(request) { + this.#listeners = []; + this.#cancelled = false; + fetchSignals.set(request, () => { + if (this.#cancelled) { + return; + } + this.#cancelled = true; + for (const listener of this.#listeners) { + setTimeout(() => { listener(); }, 0); + } + this.#listeners = []; + }); + } + addListener(listener) { + if (this.#cancelled) { + logger_js_1.logger.throwError("singal already cancelled", "UNSUPPORTED_OPERATION", { + operation: "fetchCancelSignal.addCancelListener" + }); + } + this.#listeners.push(listener); + } + get cancelled() { return this.cancelled; } + checkSignal() { + if (!this.cancelled) { + return; + } + logger_js_1.logger.throwError("cancelled", "CANCELLED", {}); + } +} +exports.FetchCancelSignal = FetchCancelSignal; +// Check the signal, throwing if it is cancelled +function checkSignal(signal) { + if (signal == null) { + throw new Error("missing signal; should not happen"); + } + signal.checkSignal(); + return signal; +} +class FetchRequest { + #allowInsecure; + #gzip; + #headers; + #method; + #timeout; + #url; + #body; + #bodyType; + #creds; + // Hooks + #preflight; + #process; + #retry; + #signal; + // URL + get url() { return this.#url; } + set url(url) { + this.#url = String(url); + } + // Body + get body() { + if (this.#body == null) { + return null; + } + return new Uint8Array(this.#body); + } + set body(body) { + if (body == null) { + this.#body = undefined; + this.#bodyType = undefined; + } + else if (typeof (body) === "string") { + this.#body = (0, utf8_js_1.toUtf8Bytes)(body); + this.#bodyType = "text/plain"; + } + else if (body instanceof Uint8Array) { + this.#body = body; + this.#bodyType = "application/octet-stream"; + } + else if (typeof (body) === "object") { + this.#body = (0, utf8_js_1.toUtf8Bytes)(JSON.stringify(body)); + this.#bodyType = "application/json"; + } + else { + throw new Error("invalid body"); + } + } + hasBody() { + return (this.#body != null); + } + // Method (default: GET with no body, POST with a body) + get method() { + if (this.#method) { + return this.#method; + } + if (this.hasBody()) { + return "POST"; + } + return "GET"; + } + set method(method) { + if (method == null) { + method = ""; + } + this.#method = String(method).toUpperCase(); + } + // Headers (automatically fills content-type if not explicitly set) + get headers() { + const headers = Object.assign({}, this.#headers); + if (this.#creds) { + headers["authorization"] = `Basic ${(0, base64_js_1.encodeBase64)((0, utf8_js_1.toUtf8Bytes)(this.#creds))}`; + } + ; + if (this.allowGzip) { + headers["accept-encoding"] = "gzip"; + } + if (headers["content-type"] == null && this.#bodyType) { + headers["content-type"] = this.#bodyType; + } + if (this.body) { + headers["content-length"] = String(this.body.length); + } + return Object.freeze(headers); + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + setHeader(key, value) { + this.#headers[String(key).toLowerCase()] = String(value); + } + clearHeaders() { + this.#headers = {}; + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + // Configure an Authorization header + get credentials() { + return this.#creds || null; + } + setCredentials(username, password) { + if (username.match(/:/)) { + logger_js_1.logger.throwArgumentError("invalid basic authentication username", "username", "[REDACTED]"); + } + this.#creds = `${username}:${password}`; + } + // Configure the request to allow gzipped responses + get allowGzip() { + return this.#gzip; + } + set allowGzip(value) { + this.#gzip = !!value; + } + // Allow credentials to be sent over an insecure (non-HTTPS) channel + get allowInsecureAuthentication() { + return !!this.#allowInsecure; + } + set allowInsecureAuthentication(value) { + this.#allowInsecure = !!value; + } + // Timeout (milliseconds) + get timeout() { return this.#timeout; } + set timeout(timeout) { + (0, logger_js_1.assertArgument)(timeout >= 0, "timeout must be non-zero", "timeout", timeout); + this.#timeout = timeout; + } + // Preflight called before each request is sent + get preflightFunc() { + return this.#preflight || null; + } + set preflightFunc(preflight) { + this.#preflight = preflight; + } + // Preflight called before each request is sent + get processFunc() { + return this.#process || null; + } + set processFunc(process) { + this.#process = process; + } + // Preflight called before each request is sent + get retryFunc() { + return this.#retry || null; + } + set retryFunc(retry) { + this.#retry = retry; + } + constructor(url) { + this.#url = String(url); + this.#allowInsecure = false; + this.#gzip = false; + this.#headers = {}; + this.#method = ""; + this.#timeout = 300; + } + async #send(attempt, expires, delay, _request, _response) { + if (attempt >= MAX_ATTEMPTS) { + return _response.makeServerError("exceeded maximum retry limit"); + } + if (getTime() > expires) { + return logger_js_1.logger.throwError("timeout", "TIMEOUT", { + operation: "request.send", reason: "timeout", request: _request + }); + } + if (delay > 0) { + await wait(delay); + } + let req = this.clone(); + const scheme = (req.url.split(":")[0] || "").toLowerCase(); + // Process any Gateways + if (scheme in Gateways) { + const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); + if (result instanceof FetchResponse) { + let response = result; + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Ignore throttling + } + } + return response; + } + req = result; + } + // We have a preflight function; update the request + if (this.preflightFunc) { + req = await this.preflightFunc(req); + } + const resp = await getUrlFunc(req, checkSignal(_request.#signal)); + let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); + if (response.statusCode === 301 || response.statusCode === 302) { + // Redirect + try { + const location = response.headers.location || ""; + return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); + } + catch (error) { } + // Things won't get any better on another attempt; abort + return response; + } + else if (response.statusCode === 429) { + // Throttle + if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) { + const retryAfter = response.headers["retry-after"]; + let delay = SLOT_INTERVAL * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + delay = parseInt(retryAfter); + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Throttle + let delay = SLOT_INTERVAL * Math.trunc(Math.random() * Math.pow(2, attempt)); + ; + if (error.stall >= 0) { + delay = error.stall; + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + return response; + } + send() { + if (this.#signal != null) { + return logger_js_1.logger.throwError("request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); + } + this.#signal = new FetchCancelSignal(this); + return this.#send(0, getTime() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + } + cancel() { + if (this.#signal == null) { + return logger_js_1.logger.throwError("request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); + } + const signal = fetchSignals.get(this); + if (!signal) { + throw new Error("missing signal; should not happen"); + } + signal(); + } + /** + * Returns a new [[FetchRequest]] that represents the redirection + * to %%location%%. + */ + redirect(location) { + // Redirection; for now we only support absolute locataions + const current = this.url.split(":")[0].toLowerCase(); + const target = location.split(":")[0].toLowerCase(); + // Don't allow redirecting: + // - non-GET requests + // - downgrading the security (e.g. https => http) + // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?] + if (this.method !== "GET" || (current === "https" && target === "http") || !location.match(/^https?:/)) { + return logger_js_1.logger.throwError(`unsupported redirect`, "UNSUPPORTED_OPERATION", { + operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})` + }); + } + // Create a copy of this request, with a new URL + const req = new FetchRequest(location); + req.method = "GET"; + req.allowGzip = this.allowGzip; + req.timeout = this.timeout; + req.#headers = Object.assign({}, this.#headers); + if (this.#body) { + req.#body = new Uint8Array(this.#body); + } + req.#bodyType = this.#bodyType; + // Do not forward credentials unless on the same domain; only absolute + //req.allowInsecure = false; + // paths are currently supported; may want a way to specify to forward? + //setStore(req.#props, "creds", getStore(this.#pros, "creds")); + return req; + } + clone() { + const clone = new FetchRequest(this.url); + // Preserve "default method" (i.e. null) + clone.#method = this.#method; + // Preserve "default body" with type, copying the Uint8Array is present + if (this.#body) { + clone.#body = this.#body; + } + clone.#bodyType = this.#bodyType; + // Preserve "default headers" + clone.#headers = Object.assign({}, this.#headers); + // Credentials is readonly, so we copy internally + clone.#creds = this.#creds; + if (this.allowGzip) { + clone.allowGzip = true; + } + clone.timeout = this.timeout; + if (this.allowInsecureAuthentication) { + clone.allowInsecureAuthentication = true; + } + clone.#preflight = this.#preflight; + clone.#process = this.#process; + clone.#retry = this.#retry; + return clone; + } + static lockConfig() { + locked = true; + } + static getGateway(scheme) { + return Gateways[scheme.toLowerCase()] || null; + } + static registerGateway(scheme, func) { + scheme = scheme.toLowerCase(); + if (scheme === "http" || scheme === "https") { + throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); + } + if (locked) { + throw new Error("gateways locked"); + } + Gateways[scheme] = func; + } + static registerGetUrl(getUrl) { + if (locked) { + throw new Error("gateways locked"); + } + getUrlFunc = getUrl; + } +} +exports.FetchRequest = FetchRequest; +; +class FetchResponse { + #statusCode; + #statusMessage; + #headers; + #body; + #request; + #error; + toString() { + return ``; + } + get statusCode() { return this.#statusCode; } + get statusMessage() { return this.#statusMessage; } + get headers() { return this.#headers; } + get body() { + return (this.#body == null) ? null : new Uint8Array(this.#body); + } + get bodyText() { + try { + return (this.#body == null) ? "" : (0, utf8_js_1.toUtf8String)(this.#body); + } + catch (error) { + return logger_js_1.logger.throwError("response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { + operation: "bodyText", info: { response: this } + }); + } + } + get bodyJson() { + try { + return JSON.parse(this.bodyText); + } + catch (error) { + return logger_js_1.logger.throwError("response body is not valid JSON", "UNSUPPORTED_OPERATION", { + operation: "bodyJson", info: { response: this } + }); + } + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + constructor(statusCode, statusMessage, headers, body, request) { + this.#statusCode = statusCode; + this.#statusMessage = statusMessage; + this.#headers = Object.freeze(Object.assign({}, Object.keys(headers).reduce((accum, k) => { + accum[k.toLowerCase()] = String(headers[k]); + return accum; + }, {}))); + this.#body = ((body == null) ? null : new Uint8Array(body)); + this.#request = (request || null); + this.#error = { message: "" }; + } + makeServerError(message, error) { + let statusMessage; + if (!message) { + message = `${this.statusCode} ${this.statusMessage}`; + statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; + } + else { + statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; + } + const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); + response.#error = { message, error }; + return response; + } + throwThrottleError(message, stall) { + if (stall == null) { + stall = -1; + } + else if (typeof (stall) !== "number" || !Number.isInteger(stall) || stall < 0) { + return logger_js_1.logger.throwArgumentError("invalid stall timeout", "stall", stall); + } + const error = new Error(message || "throttling requests"); + (0, properties_js_1.defineProperties)(error, { stall, throttle: true }); + throw error; + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + hasBody() { + return (this.#body != null); + } + get request() { return this.#request; } + ok() { + return (this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300); + } + assertOk() { + if (this.ok()) { + return; + } + let { message, error } = this.#error; + if (message === "") { + message = `server response ${this.statusCode} ${this.statusMessage}`; + } + logger_js_1.logger.throwError(message, "SERVER_ERROR", { + request: (this.request || "unknown request"), response: this, error + }); + } +} +exports.FetchResponse = FetchResponse; +function getTime() { return (new Date()).getTime(); } +function unpercent(value) { + return (0, utf8_js_1.toUtf8Bytes)(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => { + return String.fromCharCode(parseInt(code, 16)); + })); +} +function wait(delay) { + return new Promise((resolve) => setTimeout(resolve, delay)); +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/fetch.js.map b/lib.commonjs/utils/fetch.js.map new file mode 100644 index 000000000..105f5c18f --- /dev/null +++ b/lib.commonjs/utils/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src.ts/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,2CAAyD;AACzD,uCAAoC;AACpC,2CAAqD;AACrD,mDAAmD;AACnD,uCAAqD;AAErD,2CAAqC;AA2CrC,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B,6CAA6C;AAC7C,IAAI,UAAU,GAAoB,kBAAM,CAAC;AAEzC,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;AAClE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;AAEzD,0CAA0C;AAC1C,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,6EAA6E;AAC7E,KAAK,UAAU,WAAW,CAAC,GAAW,EAAE,MAA0B;IAC9D,IAAI;QACA,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAChC,IAAI,CAAC,KAAK,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;SAAE;QAChD,OAAO,IAAI,aAAa,CAAC,GAAG,EAAE,IAAI,EAAE;YAChC,cAAc,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC;SAC7C,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,wBAAY,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA,CAAC,CAAC,SAA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,OAAO,GAAG,mBAAoB,IAAI,CAAC,UAAW,IAAK,IAAI,CAAC,aAAc,EAAE,CAAC;SAC5E;QACD,kBAAM,CAAC,UAAU,CAAC,OAAO,EAAE,cAAc,EAAE;YACvC,OAAO,EAAE,CAAC,IAAI,CAAC,OAAO,IAAI,iBAAiB,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK;SACtE,CAAC,CAAC;IACP,CAAC;CACJ;AAxHD,sCAwHC;AAGD,SAAS,OAAO,KAAa,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAE7D,SAAS,SAAS,CAAC,KAAa;IAC5B,OAAO,IAAA,qBAAW,EAAC,KAAK,CAAC,OAAO,CAAC,uBAAuB,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACpE,OAAO,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;IACnD,CAAC,CAAC,CAAC,CAAC;AACR,CAAC;AAED,SAAS,IAAI,CAAC,KAAa;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AAChE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/utils/fixednumber.js b/lib.commonjs/utils/fixednumber.js new file mode 100644 index 000000000..88a60f173 --- /dev/null +++ b/lib.commonjs/utils/fixednumber.js @@ -0,0 +1,347 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FixedNumber = exports.FixedFormat = exports.parseFixed = exports.formatFixed = void 0; +const logger_js_1 = require("./logger.js"); +const maths_js_1 = require("./maths.js"); +const _constructorGuard = {}; +const NegativeOne = BigInt(-1); +function throwFault(message, fault, operation, value) { + const params = { fault: fault, operation: operation }; + if (value !== undefined) { + params.value = value; + } + return logger_js_1.logger.throwError(message, "NUMERIC_FAULT", params); +} +// Constant to pull zeros from for multipliers +let zeros = "0"; +while (zeros.length < 256) { + zeros += zeros; +} +// Returns a string "1" followed by decimal "0"s +function getMultiplier(decimals) { + if (typeof (decimals) !== "number" || decimals < 0 || decimals > 256 || decimals % 1) { + logger_js_1.logger.throwArgumentError("invalid decimal length", "decimals", decimals); + } + return BigInt("1" + zeros.substring(0, decimals)); +} +function formatFixed(_value, _decimals) { + if (_decimals == null) { + _decimals = 18; + } + let value = logger_js_1.logger.getBigInt(_value, "value"); + const decimals = logger_js_1.logger.getNumber(_decimals, "decimals"); + const multiplier = getMultiplier(decimals); + const multiplierStr = String(multiplier); + const negative = (value < 0); + if (negative) { + value *= NegativeOne; + } + let fraction = String(value % multiplier); + // Make sure there are enough place-holders + while (fraction.length < multiplierStr.length - 1) { + fraction = "0" + fraction; + } + // Strip training 0 + while (fraction.length > 1 && fraction.substring(fraction.length - 1) === "0") { + fraction = fraction.substring(0, fraction.length - 1); + } + let result = String(value / multiplier); + if (multiplierStr.length !== 1) { + result += "." + fraction; + } + if (negative) { + result = "-" + result; + } + return result; +} +exports.formatFixed = formatFixed; +function parseFixed(value, _decimals) { + if (_decimals == null) { + _decimals = 18; + } + const decimals = logger_js_1.logger.getNumber(_decimals, "decimals"); + const multiplier = getMultiplier(decimals); + if (typeof (value) !== "string" || !value.match(/^-?[0-9.]+$/)) { + logger_js_1.logger.throwArgumentError("invalid decimal value", "value", value); + } + // Is it negative? + const negative = (value.substring(0, 1) === "-"); + if (negative) { + value = value.substring(1); + } + if (value === ".") { + logger_js_1.logger.throwArgumentError("missing value", "value", value); + } + // Split it into a whole and fractional part + const comps = value.split("."); + if (comps.length > 2) { + logger_js_1.logger.throwArgumentError("too many decimal points", "value", value); + } + let whole = (comps[0] || "0"), fraction = (comps[1] || "0"); + // Trim trialing zeros + while (fraction[fraction.length - 1] === "0") { + fraction = fraction.substring(0, fraction.length - 1); + } + // Check the fraction doesn't exceed our decimals size + if (fraction.length > String(multiplier).length - 1) { + throwFault("fractional component exceeds decimals", "underflow", "parseFixed"); + } + // If decimals is 0, we have an empty string for fraction + if (fraction === "") { + fraction = "0"; + } + // Fully pad the string with zeros to get to wei + while (fraction.length < String(multiplier).length - 1) { + fraction += "0"; + } + const wholeValue = BigInt(whole); + const fractionValue = BigInt(fraction); + let wei = (wholeValue * multiplier) + fractionValue; + if (negative) { + wei *= NegativeOne; + } + return wei; +} +exports.parseFixed = parseFixed; +class FixedFormat { + signed; + width; + decimals; + name; + _multiplier; + constructor(constructorGuard, signed, width, decimals) { + if (constructorGuard !== _constructorGuard) { + logger_js_1.logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", "UNSUPPORTED_OPERATION", { + operation: "new FixedFormat" + }); + } + this.signed = signed; + this.width = width; + this.decimals = decimals; + this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + this._multiplier = getMultiplier(decimals); + Object.freeze(this); + } + static from(value) { + if (value instanceof FixedFormat) { + return value; + } + if (typeof (value) === "number") { + value = `fixed128x${value}`; + } + let signed = true; + let width = 128; + let decimals = 18; + if (typeof (value) === "string") { + if (value === "fixed") { + // defaults... + } + else if (value === "ufixed") { + signed = false; + } + else { + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + if (!match) { + return logger_js_1.logger.throwArgumentError("invalid fixed format", "format", value); + } + signed = (match[1] !== "u"); + width = parseInt(match[2]); + decimals = parseInt(match[3]); + } + } + else if (value) { + const check = (key, type, defaultValue) => { + if (value[key] == null) { + return defaultValue; + } + if (typeof (value[key]) !== type) { + logger_js_1.logger.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]); + } + return value[key]; + }; + signed = check("signed", "boolean", signed); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); + } + if (width % 8) { + logger_js_1.logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); + } + if (decimals > 80) { + logger_js_1.logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); + } + return new FixedFormat(_constructorGuard, signed, width, decimals); + } +} +exports.FixedFormat = FixedFormat; +class FixedNumber { + format; + _isFixedNumber; + //#hex: string; + #value; + constructor(constructorGuard, hex, value, format) { + if (constructorGuard !== _constructorGuard) { + logger_js_1.logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", "UNSUPPORTED_OPERATION", { + operation: "new FixedFormat" + }); + } + this.format = FixedFormat.from(format); + //this.#hex = hex; + this.#value = value; + this._isFixedNumber = true; + Object.freeze(this); + } + #checkFormat(other) { + if (this.format.name !== other.format.name) { + logger_js_1.logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other); + } + } + addUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue(a + b, this.format.decimals, this.format); + } + subUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue(a - b, this.format.decimals, this.format); + } + mulUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue((a * b) / this.format._multiplier, this.format.decimals, this.format); + } + divUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue((a * this.format._multiplier) / b, this.format.decimals, this.format); + } + floor() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (this.isNegative() && hasFraction) { + result = result.subUnsafe(ONE.toFormat(result.format)); + } + return result; + } + ceiling() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (!this.isNegative() && hasFraction) { + result = result.addUnsafe(ONE.toFormat(result.format)); + } + return result; + } + // @TODO: Support other rounding algorithms + round(decimals) { + if (decimals == null) { + decimals = 0; + } + // If we are already in range, we're done + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + if (decimals < 0 || decimals > 80 || (decimals % 1)) { + logger_js_1.logger.throwArgumentError("invalid decimal count", "decimals", decimals); + } + if (comps[1].length <= decimals) { + return this; + } + const factor = FixedNumber.from("1" + zeros.substring(0, decimals), this.format); + const bump = BUMP.toFormat(this.format); + return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor); + } + isZero() { + return (this.#value === "0.0" || this.#value === "0"); + } + isNegative() { + return (this.#value[0] === "-"); + } + toString() { return this.#value; } + toHexString(_width) { + throw new Error("TODO"); + /* + return toHex(); + if (width == null) { return this.#hex; } + + const width = logger.getNumeric(_width); + if (width % 8) { logger.throwArgumentError("invalid byte width", "width", width); } + + const hex = BigNumber.from(this.#hex).fromTwos(this.format.width).toTwos(width).toHexString(); + return zeroPadLeft(hex, width / 8); + */ + } + toUnsafeFloat() { return parseFloat(this.toString()); } + toFormat(format) { + return FixedNumber.fromString(this.#value, format); + } + static fromValue(value, decimals = 0, format = "fixed") { + return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format)); + } + static fromString(value, format = "fixed") { + const fixedFormat = FixedFormat.from(format); + const numeric = parseFixed(value, fixedFormat.decimals); + if (!fixedFormat.signed && numeric < 0) { + throwFault("unsigned value cannot be negative", "overflow", "value", value); + } + const hex = (function () { + if (fixedFormat.signed) { + return (0, maths_js_1.toHex)((0, maths_js_1.toTwos)(numeric, fixedFormat.width)); + } + return (0, maths_js_1.toHex)(numeric, fixedFormat.width / 8); + })(); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); + } + static fromBytes(_value, format = "fixed") { + const value = logger_js_1.logger.getBytes(_value, "value"); + const fixedFormat = FixedFormat.from(format); + if (value.length > fixedFormat.width / 8) { + throw new Error("overflow"); + } + let numeric = (0, maths_js_1.toBigInt)(value); + if (fixedFormat.signed) { + numeric = (0, maths_js_1.fromTwos)(numeric, fixedFormat.width); + } + const hex = (0, maths_js_1.toHex)((0, maths_js_1.toTwos)(numeric, (fixedFormat.signed ? 0 : 1) + fixedFormat.width)); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); + } + static from(value, format) { + if (typeof (value) === "string") { + return FixedNumber.fromString(value, format); + } + if (value instanceof Uint8Array) { + return FixedNumber.fromBytes(value, format); + } + try { + return FixedNumber.fromValue(value, 0, format); + } + catch (error) { + // Allow NUMERIC_FAULT to bubble up + if (error.code !== "INVALID_ARGUMENT") { + throw error; + } + } + return logger_js_1.logger.throwArgumentError("invalid FixedNumber value", "value", value); + } + static isFixedNumber(value) { + return !!(value && value._isFixedNumber); + } +} +exports.FixedNumber = FixedNumber; +const ONE = FixedNumber.from(1); +const BUMP = FixedNumber.from("0.5"); +//# sourceMappingURL=fixednumber.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/fixednumber.js.map b/lib.commonjs/utils/fixednumber.js.map new file mode 100644 index 000000000..7bc530047 --- /dev/null +++ b/lib.commonjs/utils/fixednumber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fixednumber.js","sourceRoot":"","sources":["../../src.ts/utils/fixednumber.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AACrC,yCAA+D;AAK/D,MAAM,iBAAiB,GAAG,EAAG,CAAC;AAE9B,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAE/B,SAAS,UAAU,CAAC,OAAe,EAAE,KAAa,EAAE,SAAiB,EAAE,KAAW;IAC9E,MAAM,MAAM,GAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;IAC3D,IAAI,KAAK,KAAK,SAAS,EAAE;QAAE,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;KAAE;IAClD,OAAO,kBAAM,CAAC,UAA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-browser.js new file mode 100644 index 000000000..6a4f11ac4 --- /dev/null +++ b/lib.commonjs/utils/geturl-browser.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getUrl = void 0; +const logger_js_1 = require("./logger.js"); +// @TODO: timeout is completely ignored; start a Promise.any with a reject? +async function getUrl(req, _signal) { + const protocol = req.url.split(":")[0].toLowerCase(); + if (protocol !== "http" && protocol !== "https") { + logger_js_1.logger.throwError(`unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" + }); + } + if (req.credentials && !req.allowInsecureAuthentication) { + logger_js_1.logger.throwError("insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + } + let signal = undefined; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { controller.abort(); }); + } + const init = { + method: req.method, + headers: new Headers(Array.from(req)), + body: req.body || undefined, + signal + }; + const resp = await fetch(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = await resp.arrayBuffer(); + const body = (respBody == null) ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, body + }; +} +exports.getUrl = getUrl; +//# sourceMappingURL=geturl-browser.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/geturl-browser.js.map b/lib.commonjs/utils/geturl-browser.js.map new file mode 100644 index 000000000..4259a48fe --- /dev/null +++ b/lib.commonjs/utils/geturl-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"geturl-browser.js","sourceRoot":"","sources":["../../src.ts/utils/geturl-browser.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AA2BrC,2EAA2E;AAEpE,KAAK,UAAU,MAAM,CAAC,GAAiB,EAAE,OAA2B;IACvE,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,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M,IAAI,GAAG,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA,CAAC,CAAC,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC;IAEjE,OAAO;QACH,UAAU,EAAE,IAAI,CAAC,MAAM;QACvB,aAAa,EAAE,IAAI,CAAC,UAAU;QAC9B,OAAO,EAAE,IAAI;KAChB,CAAC;AACN,CAAC;AA7CD,wBA6CC"} \ No newline at end of file diff --git a/lib.commonjs/utils/geturl.js b/lib.commonjs/utils/geturl.js new file mode 100644 index 000000000..e811ec177 --- /dev/null +++ b/lib.commonjs/utils/geturl.js @@ -0,0 +1,85 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getUrl = void 0; +const http_1 = __importDefault(require("http")); +const https_1 = __importDefault(require("https")); +const zlib_1 = require("zlib"); +const logger_js_1 = require("./logger.js"); +async function getUrl(req, signal) { + const protocol = req.url.split(":")[0].toLowerCase(); + if (protocol !== "http" && protocol !== "https") { + logger_js_1.logger.throwError(`unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" + }); + } + if (req.credentials && !req.allowInsecureAuthentication) { + logger_js_1.logger.throwError("insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + } + const method = req.method; + const headers = Object.assign({}, req.headers); + const options = { method, headers }; + const request = ((protocol === "http") ? http_1.default : https_1.default).request(req.url, options); + request.setTimeout(req.timeout); + const body = req.body; + if (body) { + request.write(Buffer.from(body)); + } + request.end(); + return new Promise((resolve, reject) => { + // @TODO: Node 15 added AbortSignal; once we drop support for + // Node14, we can add that in here too + request.once("response", (resp) => { + const statusCode = resp.statusCode || 0; + const statusMessage = resp.statusMessage || ""; + const headers = Object.keys(resp.headers || {}).reduce((accum, name) => { + let value = resp.headers[name] || ""; + if (Array.isArray(value)) { + value = value.join(", "); + } + accum[name] = value; + return accum; + }, {}); + let body = null; + //resp.setEncoding("utf8"); + resp.on("data", (chunk) => { + if (signal) { + try { + signal.checkSignal(); + } + catch (error) { + return reject(error); + } + } + if (body == null) { + body = chunk; + } + else { + const newBody = new Uint8Array(body.length + chunk.length); + newBody.set(body, 0); + newBody.set(chunk, body.length); + body = newBody; + } + }); + resp.on("end", () => { + if (headers["content-encoding"] === "gzip" && body) { + body = logger_js_1.logger.getBytes((0, zlib_1.gunzipSync)(body)); + } + resolve({ statusCode, statusMessage, headers, body }); + }); + resp.on("error", (error) => { + //@TODO: Should this just return nornal response with a server error? + error.response = { statusCode, statusMessage, headers, body }; + reject(error); + }); + }); + request.on("error", (error) => { reject(error); }); + }); +} +exports.getUrl = getUrl; +//# sourceMappingURL=geturl.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/geturl.js.map b/lib.commonjs/utils/geturl.js.map new file mode 100644 index 000000000..2ffeceb11 --- /dev/null +++ b/lib.commonjs/utils/geturl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"geturl.js","sourceRoot":"","sources":["../../src.ts/utils/geturl.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AACxB,kDAA0B;AAC1B,+BAAkC;AAElC,2CAAqC;AAK9B,KAAK,UAAU,MAAM,CAAC,GAAiB,EAAE,MAA0B;IAEtE,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IAErD,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,OAAO,EAAE;QAC7C,kBAAM,CAAC,UAAU,CAAC,wBAAyB,QAAS,EAAE,EAAE,uBAAuB,EAAE;YAC7E,IAAI,EAAE,EAAE,QAAQ,EAAE;YAClB,SAAS,EAAE,SAAS;SACvB,CAAC,CAAC;KACN;IAED,IAAI,GAAG,CAAC,WAAW,IAAI,CAAC,GAAG,CAAC,2BAA2B,EAAE;Q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CAAC;YAEH,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;gBAC3B,qEAAqE;gBAC3D,KAAM,CAAC,QAAQ,GAAG,EAAE,UAAU,EAAE,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;gBACrE,MAAM,CAAC,KAAK,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACP,CAAC;AAtFD,wBAsFC"} \ No newline at end of file diff --git a/lib.commonjs/utils/index.js b/lib.commonjs/utils/index.js new file mode 100644 index 000000000..06b21ee2b --- /dev/null +++ b/lib.commonjs/utils/index.js @@ -0,0 +1,69 @@ +"use strict"; +//// +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Utf8ErrorFuncs = exports.toUtf8String = exports.toUtf8CodePoints = exports.toUtf8Bytes = exports._toEscapedUtf8String = exports.parseUnits = exports.formatUnits = exports.parseEther = exports.formatEther = exports.setStore = exports.getStore = exports.encodeRlp = exports.decodeRlp = exports.defineProperties = exports.defineReadOnly = exports.resolveProperties = exports.toQuantity = exports.toArray = exports.toHex = exports.toNumber = exports.toBigInt = exports.mask = exports.toTwos = exports.fromTwos = exports.logger = exports.Logger = exports.assertArgument = exports.parseFixed = exports.formatFixed = exports.FixedNumber = exports.FixedFormat = exports.FetchResponse = exports.FetchRequest = exports.EventPayload = exports.isError = exports.isCallException = exports.zeroPadBytes = exports.zeroPadValue = exports.stripZerosLeft = exports.dataSlice = exports.dataLength = exports.concat = exports.hexlify = exports.isBytesLike = exports.isHexString = exports.encodeBase64 = exports.decodeBase64 = exports.encodeBase58 = exports.decodeBase58 = void 0; +var base58_js_1 = require("./base58.js"); +Object.defineProperty(exports, "decodeBase58", { enumerable: true, get: function () { return base58_js_1.decodeBase58; } }); +Object.defineProperty(exports, "encodeBase58", { enumerable: true, get: function () { return base58_js_1.encodeBase58; } }); +var base64_js_1 = require("./base64.js"); +Object.defineProperty(exports, "decodeBase64", { enumerable: true, get: function () { return base64_js_1.decodeBase64; } }); +Object.defineProperty(exports, "encodeBase64", { enumerable: true, get: function () { return base64_js_1.encodeBase64; } }); +var data_js_1 = require("./data.js"); +Object.defineProperty(exports, "isHexString", { enumerable: true, get: function () { return data_js_1.isHexString; } }); +Object.defineProperty(exports, "isBytesLike", { enumerable: true, get: function () { return data_js_1.isBytesLike; } }); +Object.defineProperty(exports, "hexlify", { enumerable: true, get: function () { return data_js_1.hexlify; } }); +Object.defineProperty(exports, "concat", { enumerable: true, get: function () { return data_js_1.concat; } }); +Object.defineProperty(exports, "dataLength", { enumerable: true, get: function () { return data_js_1.dataLength; } }); +Object.defineProperty(exports, "dataSlice", { enumerable: true, get: function () { return data_js_1.dataSlice; } }); +Object.defineProperty(exports, "stripZerosLeft", { enumerable: true, get: function () { return data_js_1.stripZerosLeft; } }); +Object.defineProperty(exports, "zeroPadValue", { enumerable: true, get: function () { return data_js_1.zeroPadValue; } }); +Object.defineProperty(exports, "zeroPadBytes", { enumerable: true, get: function () { return data_js_1.zeroPadBytes; } }); +var errors_js_1 = require("./errors.js"); +Object.defineProperty(exports, "isCallException", { enumerable: true, get: function () { return errors_js_1.isCallException; } }); +Object.defineProperty(exports, "isError", { enumerable: true, get: function () { return errors_js_1.isError; } }); +var events_js_1 = require("./events.js"); +Object.defineProperty(exports, "EventPayload", { enumerable: true, get: function () { return events_js_1.EventPayload; } }); +var fetch_js_1 = require("./fetch.js"); +Object.defineProperty(exports, "FetchRequest", { enumerable: true, get: function () { return fetch_js_1.FetchRequest; } }); +Object.defineProperty(exports, "FetchResponse", { enumerable: true, get: function () { return fetch_js_1.FetchResponse; } }); +var fixednumber_js_1 = require("./fixednumber.js"); +Object.defineProperty(exports, "FixedFormat", { enumerable: true, get: function () { return fixednumber_js_1.FixedFormat; } }); +Object.defineProperty(exports, "FixedNumber", { enumerable: true, get: function () { return fixednumber_js_1.FixedNumber; } }); +Object.defineProperty(exports, "formatFixed", { enumerable: true, get: function () { return fixednumber_js_1.formatFixed; } }); +Object.defineProperty(exports, "parseFixed", { enumerable: true, get: function () { return fixednumber_js_1.parseFixed; } }); +var logger_js_1 = require("./logger.js"); +Object.defineProperty(exports, "assertArgument", { enumerable: true, get: function () { return logger_js_1.assertArgument; } }); +Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_js_1.Logger; } }); +Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return logger_js_1.logger; } }); +var maths_js_1 = require("./maths.js"); +Object.defineProperty(exports, "fromTwos", { enumerable: true, get: function () { return maths_js_1.fromTwos; } }); +Object.defineProperty(exports, "toTwos", { enumerable: true, get: function () { return maths_js_1.toTwos; } }); +Object.defineProperty(exports, "mask", { enumerable: true, get: function () { return maths_js_1.mask; } }); +Object.defineProperty(exports, "toBigInt", { enumerable: true, get: function () { return maths_js_1.toBigInt; } }); +Object.defineProperty(exports, "toNumber", { enumerable: true, get: function () { return maths_js_1.toNumber; } }); +Object.defineProperty(exports, "toHex", { enumerable: true, get: function () { return maths_js_1.toHex; } }); +Object.defineProperty(exports, "toArray", { enumerable: true, get: function () { return maths_js_1.toArray; } }); +Object.defineProperty(exports, "toQuantity", { enumerable: true, get: function () { return maths_js_1.toQuantity; } }); +var properties_js_1 = require("./properties.js"); +Object.defineProperty(exports, "resolveProperties", { enumerable: true, get: function () { return properties_js_1.resolveProperties; } }); +Object.defineProperty(exports, "defineReadOnly", { enumerable: true, get: function () { return properties_js_1.defineReadOnly; } }); +Object.defineProperty(exports, "defineProperties", { enumerable: true, get: function () { return properties_js_1.defineProperties; } }); +var rlp_decode_js_1 = require("./rlp-decode.js"); +Object.defineProperty(exports, "decodeRlp", { enumerable: true, get: function () { return rlp_decode_js_1.decodeRlp; } }); +var rlp_encode_js_1 = require("./rlp-encode.js"); +Object.defineProperty(exports, "encodeRlp", { enumerable: true, get: function () { return rlp_encode_js_1.encodeRlp; } }); +var storage_js_1 = require("./storage.js"); +Object.defineProperty(exports, "getStore", { enumerable: true, get: function () { return storage_js_1.getStore; } }); +Object.defineProperty(exports, "setStore", { enumerable: true, get: function () { return storage_js_1.setStore; } }); +var units_js_1 = require("./units.js"); +Object.defineProperty(exports, "formatEther", { enumerable: true, get: function () { return units_js_1.formatEther; } }); +Object.defineProperty(exports, "parseEther", { enumerable: true, get: function () { return units_js_1.parseEther; } }); +Object.defineProperty(exports, "formatUnits", { enumerable: true, get: function () { return units_js_1.formatUnits; } }); +Object.defineProperty(exports, "parseUnits", { enumerable: true, get: function () { return units_js_1.parseUnits; } }); +var utf8_js_1 = require("./utf8.js"); +Object.defineProperty(exports, "_toEscapedUtf8String", { enumerable: true, get: function () { return utf8_js_1._toEscapedUtf8String; } }); +Object.defineProperty(exports, "toUtf8Bytes", { enumerable: true, get: function () { return utf8_js_1.toUtf8Bytes; } }); +Object.defineProperty(exports, "toUtf8CodePoints", { enumerable: true, get: function () { return utf8_js_1.toUtf8CodePoints; } }); +Object.defineProperty(exports, "toUtf8String", { enumerable: true, get: function () { return utf8_js_1.toUtf8String; } }); +Object.defineProperty(exports, "Utf8ErrorFuncs", { enumerable: true, get: function () { return utf8_js_1.Utf8ErrorFuncs; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/index.js.map b/lib.commonjs/utils/index.js.map new file mode 100644 index 000000000..4b260feb7 --- /dev/null +++ b/lib.commonjs/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/utils/index.ts"],"names":[],"mappings":";AACA,IAAI;;;AAeJ,yCAAyD;AAAhD,yGAAA,YAAY,OAAA;AAAE,yGAAA,YAAY,OAAA;AAEnC,yCAAyD;AAAhD,yGAAA,YAAY,OAAA;AAAE,yGAAA,YAAY,OAAA;AAEnC,qCAGmB;AA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B,OAAA;AACpB,sGAAA,WAAW,OAAA;AACX,2GAAA,gBAAgB,OAAA;AAChB,uGAAA,YAAY,OAAA;AAEZ,yGAAA,cAAc,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/utils/logger.js b/lib.commonjs/utils/logger.js new file mode 100644 index 000000000..74b3b9c7b --- /dev/null +++ b/lib.commonjs/utils/logger.js @@ -0,0 +1,231 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertArgument = exports.logger = exports.Logger = void 0; +const _version_js_1 = require("../_version.js"); +const LogLevels = ["debug", "info", "warning", "error", "off"]; +const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { + try { + // General test for normalize + /* c8 ignore start */ + if ("test".normalize(form) !== "test") { + throw new Error("bad"); + } + ; + /* c8 ignore stop */ + if (form === "NFD") { + const check = String.fromCharCode(0xe9).normalize("NFD"); + const expected = String.fromCharCode(0x65, 0x0301); + /* c8 ignore start */ + if (check !== expected) { + throw new Error("broken"); + } + /* c8 ignore stop */ + } + accum.push(form); + } + catch (error) { } + return accum; +}, []); +function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, writable: false, value, + }); +} +// IEEE 754 support 53-bits of mantissa +const maxValue = 0x1fffffffffffff; +// The type of error to use for various error codes +const ErrorConstructors = {}; +ErrorConstructors.INVALID_ARGUMENT = TypeError; +ErrorConstructors.NUMERIC_FAULT = RangeError; +ErrorConstructors.BUFFER_OVERRUN = RangeError; +class Logger { + version; + #logLevel; + constructor(version) { + defineReadOnly(this, "version", version || "_"); + this.#logLevel = 1; + } + get logLevel() { + return LogLevels[this.#logLevel]; + } + set logLevel(value) { + const logLevel = LogLevels.indexOf(value); + if (logLevel == null) { + this.throwArgumentError("invalid logLevel", "logLevel", value); + } + this.#logLevel = logLevel; + } + makeError(message, code, info) { + { + const details = []; + if (info) { + for (const key in info) { + const value = (info[key]); + try { + details.push(key + "=" + JSON.stringify(value)); + } + catch (error) { + details.push(key + "=[could not serialize object]"); + } + } + } + details.push(`code=${code}`); + details.push(`version=${this.version}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; + } + } + const create = ErrorConstructors[code] || Error; + const error = (new create(message)); + defineReadOnly(error, "code", code); + if (info) { + for (const key in info) { + defineReadOnly(error, key, (info[key])); + } + } + return error; + } + throwError(message, code, info) { + throw this.makeError(message, code, info); + } + throwArgumentError(message, name, value) { + return this.throwError(message, "INVALID_ARGUMENT", { + argument: name, + value: value + }); + } + assertNormalize(form) { + if (_normalizeForms.indexOf(form) === -1) { + this.throwError("platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", info: { form } + }); + } + } + assertPrivate(givenGuard, guard, className = "") { + if (givenGuard !== guard) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; + } + this.throwError(`private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation + }); + } + } + assertArgumentCount(count, expectedCount, message = "") { + if (message) { + message = ": " + message; + } + if (count < expectedCount) { + this.throwError("missing arguemnt" + message, "MISSING_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguemnts" + message, "UNEXPECTED_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + } + #getBytes(value, name, copy) { + if (value instanceof Uint8Array) { + if (copy) { + return new Uint8Array(value); + } + return value; + } + if (typeof (value) === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset = 2; + for (let i = 0; i < result.length; i++) { + result[i] = parseInt(value.substring(offset, offset + 2), 16); + offset += 2; + } + return result; + } + return this.throwArgumentError("invalid BytesLike value", name || "value", value); + } + getBytes(value, name) { + return this.#getBytes(value, name, false); + } + getBytesCopy(value, name) { + return this.#getBytes(value, name, true); + } + getNumber(value, name) { + switch (typeof (value)) { + case "bigint": + if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return Number(value); + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return value; + case "string": + try { + return this.getNumber(BigInt(value), name); + } + catch (e) { + this.throwArgumentError(`invalid numeric string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid numeric value", name || "value", value); + } + getBigInt(value, name) { + switch (typeof (value)) { + case "bigint": return value; + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return BigInt(value); + case "string": + try { + return BigInt(value); + } + catch (e) { + this.throwArgumentError(`invalid BigNumberish string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid BigNumberish value", name || "value", value); + } + #log(_logLevel, args) { + const logLevel = LogLevels.indexOf(_logLevel); + if (logLevel === -1) { + this.throwArgumentError("invalid log level name", "logLevel", _logLevel); + } + if (this.#logLevel > logLevel) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this.#log("debug", args); + } + info(...args) { + this.#log("info", args); + } + warn(...args) { + this.#log("warning", args); + } +} +exports.Logger = Logger; +exports.logger = new Logger(_version_js_1.version); +function assertArgument(check, message, name, value) { + if (!check) { + exports.logger.throwArgumentError(message, name, value); + } +} +exports.assertArgument = assertArgument; +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/logger.js.map b/lib.commonjs/utils/logger.js.map new file mode 100644 index 000000000..b2e40ee77 --- /dev/null +++ b/lib.commonjs/utils/logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src.ts/utils/logger.ts"],"names":[],"mappings":";;;AAAA,gDAAyC;AAWzC,MAAM,SAAS,GAAoB,CAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,CAAE,CAAC;AAElF,MAAM,eAAe,GAAG,CAAC,KAAK,E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,CAAC,SAAmB,EAAE,IAAgB;QACtC,MAAM,QAAQ,GAAG,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,QAAQ,KAAK,CAAC,CAAC,EAAE;YACjB,IAAI,CAAC,kBAAkB,CAAC,wBAAwB,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;SAC5E;QACD,IAAI,IAAI,CAAC,SAAS,GAAG,QAAQ,EAAE;YAAE,OAAO;SAAE;QAC1C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,GAAG,IAAgB;QACrB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,GAAG,IAAgB;QACpB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,IAAI,CAAC,GAAG,IAAgB;QACpB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;CACJ;AAnMD,wBAmMC;AAEY,QAAA,MAAM,GAAG,IAAI,MAAM,CAAC,qBAAO,CAAC,CAAC;AAE1C,SAAgB,cAAc,CAAC,KAAc,EAAE,OAAe,EAAE,IAAY,EAAE,KAAc;IACxF,IAAI,CAAC,KAAK,EAAE;QAAE,cAAM,CAAC,kBAAkB,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;KAAE;AACpE,CAAC;AAFD,wCAEC"} \ No newline at end of file diff --git a/lib.commonjs/utils/maths.js b/lib.commonjs/utils/maths.js new file mode 100644 index 000000000..35acf883f --- /dev/null +++ b/lib.commonjs/utils/maths.js @@ -0,0 +1,133 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toQuantity = exports.toArray = exports.toHex = exports.toNumber = exports.toBigInt = exports.mask = exports.toTwos = exports.fromTwos = void 0; +const data_js_1 = require("./data.js"); +const logger_js_1 = require("./logger.js"); +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +/** + * Convert %%value%% from a twos-compliment value of %%width%% bits. + */ +function fromTwos(_value, _width) { + const value = logger_js_1.logger.getBigInt(_value, "value"); + const width = BigInt(logger_js_1.logger.getNumber(_width, "width")); + // Top bit set; treat as a negative value + if (value >> (width - BN_1)) { + const mask = (BN_1 << width) - BN_1; + return -(((~value) & mask) + BN_1); + } + return value; +} +exports.fromTwos = fromTwos; +/** + * Convert %%value%% to a twos-compliment value of %%width%% bits. + */ +function toTwos(_value, _width) { + const value = logger_js_1.logger.getBigInt(_value, "value"); + const width = BigInt(logger_js_1.logger.getNumber(_width, "width")); + if (value < BN_0) { + const mask = (BN_1 << width) - BN_1; + return ((~(-value)) & mask) + BN_1; + } + return value; +} +exports.toTwos = toTwos; +/** + * Mask %%value%% with a bitmask of %%bits%% ones. + */ +function mask(_value, _bits) { + const value = logger_js_1.logger.getBigInt(_value, "value"); + const bits = BigInt(logger_js_1.logger.getNumber(_bits, "bits")); + return value & ((BN_1 << bits) - BN_1); +} +exports.mask = mask; +/* + * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. + */ +const Nibbles = "0123456789abcdef"; +function toBigInt(value) { + if (value instanceof Uint8Array) { + let result = "0x0"; + for (const v of value) { + result += Nibbles[v >> 4]; + result += Nibbles[v & 0x0f]; + } + return BigInt(result); + } + return logger_js_1.logger.getBigInt(value); +} +exports.toBigInt = toBigInt; +/* + * Converts %%value%% to a number. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. Throws if the value is not safe. + */ +function toNumber(value) { + return logger_js_1.logger.getNumber(toBigInt(value)); +} +exports.toNumber = toNumber; +/** + * Converts %%value%% to a Big Endian hexstring, optionally padded to + * %%width%% bytes. + */ +// Converts value to hex, optionally padding on the left to width bytes +function toHex(_value, _width) { + const value = logger_js_1.logger.getBigInt(_value, "value"); + if (value < 0) { + throw new Error("cannot convert negative value to hex"); + } + let result = value.toString(16); + if (_width == null) { + // Ensure the value is of even length + if (result.length % 2) { + result = "0" + result; + } + } + else { + const width = logger_js_1.logger.getNumber(_width, "width"); + if (width * 2 < result.length) { + throw new Error(`value ${value} exceeds width ${width}`); + } + // Pad the value to the required width + while (result.length < (width * 2)) { + result = "0" + result; + } + } + return "0x" + result; +} +exports.toHex = toHex; +/** + * Converts %%value%% to a Big Endian Uint8Array. + */ +function toArray(_value) { + const value = logger_js_1.logger.getBigInt(_value, "value"); + if (value < 0) { + throw new Error("cannot convert negative value to hex"); + } + if (value === BN_0) { + return new Uint8Array([]); + } + let hex = value.toString(16); + if (hex.length % 2) { + hex = "0" + hex; + } + const result = new Uint8Array(hex.length / 2); + for (let i = 0; i < result.length; i++) { + const offset = i * 2; + result[i] = parseInt(hex.substring(offset, offset + 2), 16); + } + return result; +} +exports.toArray = toArray; +function toQuantity(value) { + let result = (0, data_js_1.hexlify)((0, data_js_1.isBytesLike)(value) ? value : toArray(value)).substring(2); + while (result.substring(0, 1) === "0") { + result = result.substring(1); + } + if (result === "") { + result = "0"; + } + return "0x" + result; +} +exports.toQuantity = toQuantity; +//# sourceMappingURL=maths.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/maths.js.map b/lib.commonjs/utils/maths.js.map new file mode 100644 index 000000000..a478c6b93 --- /dev/null +++ b/lib.commonjs/utils/maths.js.map @@ -0,0 +1 @@ +{"version":3,"file":"maths.js","sourceRoot":"","sources":["../../src.ts/utils/maths.ts"],"names":[],"mappings":";;;AAAA,uCAAiD;AACjD,2CAAqC;AASrC,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvB;;GAEG;AACH,SAAgB,QAAQ,CAAC,MAAoB,EAAE,MAAe;IAC1D,MAAM,KAAK,GAAG,kBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChD,MAAM,K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AAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAC9E,OAAO,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;QAAE,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KAAE;IACxE,IAAI,MAAM,KAAK,EAAE,EAAE;QAAE,MAAM,GAAG,GAAG,CAAC;KAAE;IACpC,OAAO,IAAI,GAAG,MAAM,CAAC;AACzB,CAAC;AALD,gCAKC"} \ No newline at end of file diff --git a/lib.commonjs/utils/properties.js b/lib.commonjs/utils/properties.js new file mode 100644 index 000000000..bbbcb3e40 --- /dev/null +++ b/lib.commonjs/utils/properties.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defineProperties = exports.defineReadOnly = exports.resolveProperties = void 0; +async function resolveProperties(value) { + const keys = Object.keys(value); + const results = await Promise.all(keys.map((k) => Promise.resolve(value[k]))); + return results.reduce((accum, v, index) => { + accum[keys[index]] = v; + return accum; + }, {}); +} +exports.resolveProperties = resolveProperties; +function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + value: value, + writable: false, + }); +} +exports.defineReadOnly = defineReadOnly; +/* +export interface CancellablePromise extends Promise { + cancel(): Promise; +} +export type IsCancelled = () => Promise; + +export function createPromise(resolve: (isCancelled: IsCancelled, (result: T) => void) => void, reject: (error: Error) => void, isCancelled: IsCancelled): CancellablePromise { + let cancelled = false; + + const promise = new Promise((resolve, reject) => { + + }); + + (>promise).cancel = function() { + cancelled = true; + }; + + return (>promise); +} +*/ +/* +export class A implements Freezable { + foo: number; + constructor(foo: number) { + this.foo = foo; + } + freeze(): Frozen { + Object.freeze(this); + return this; + } + clone(): A { + return new A(this.foo); + } +} + +export class B implements Freezable { + a: A; + constructor(a: A) { + this.a = a; + } + freeze(): Frozen { + this.a.freeze(); + Object.freeze(this); + return this; + } + clone(): B { + return new B(this.a); + } +} + +export function test() { + const a = new A(123); + const b = new B(a); + b.a = new A(234); + const b2 = b.freeze(); + b2.a.foo = 123; // = a; +} +*/ +function checkType(value, type) { + const types = type.split("|").map(t => t.trim()); + for (let i = 0; i < types.length; i++) { + switch (type) { + case "any": + return; + case "boolean": + case "number": + case "string": + if (typeof (value) === type) { + return; + } + } + } + throw new Error("invalid value for type"); +} +function defineProperties(target, values, types, defaults) { + for (let key in values) { + let value = values[key]; + const fallback = (defaults ? defaults[key] : undefined); + if (fallback !== undefined) { + value = fallback; + } + else { + const type = (types ? types[key] : null); + if (type) { + checkType(value, type); + } + } + Object.defineProperty(target, key, { enumerable: true, value, writable: false }); + } +} +exports.defineProperties = defineProperties; +//# sourceMappingURL=properties.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/properties.js.map b/lib.commonjs/utils/properties.js.map new file mode 100644 index 000000000..edf778a99 --- /dev/null +++ b/lib.commonjs/utils/properties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../src.ts/utils/properties.ts"],"names":[],"mappings":";;;AAAO,KAAK,UAAU,iBAAiB,CAAI,KAAgD;IACvF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAChC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,KAAU,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE;QAC3C,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC;QACvB,OAAO,KAAK,CAAC;IACjB,CAAC,EAA6B,EAAG,CAAC,C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,QAAQ,CAAC;SACpB;aAAM;YACH,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA,CAAC,CAAC,IAAI,CAAC,CAAC;YACxC,IAAI,IAAI,EAAE;gBAAE,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;aAAE;SACxC;QACD,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;KACpF;AACL,CAAC;AAlBD,4CAkBC"} \ No newline at end of file diff --git a/lib.commonjs/utils/rlp-decode.js b/lib.commonjs/utils/rlp-decode.js new file mode 100644 index 000000000..9dae71755 --- /dev/null +++ b/lib.commonjs/utils/rlp-decode.js @@ -0,0 +1,87 @@ +"use strict"; +//See: https://github.com/ethereum/wiki/wiki/RLP +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeRlp = void 0; +const data_js_1 = require("./data.js"); +const logger_js_1 = require("./logger.js"); +function hexlifyByte(value) { + let result = value.toString(16); + while (result.length < 2) { + result = "0" + result; + } + return "0x" + result; +} +function unarrayifyInteger(data, offset, length) { + let result = 0; + for (let i = 0; i < length; i++) { + result = (result * 256) + data[offset + i]; + } + return result; +} +function _decodeChildren(data, offset, childOffset, length) { + const result = []; + while (childOffset < offset + 1 + length) { + const decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + if (childOffset > offset + 1 + length) { + logger_js_1.logger.throwError("child data too short", "BUFFER_OVERRUN", { + buffer: data, length, offset + }); + } + } + return { consumed: (1 + length), result: result }; +} +// returns { consumed: number, result: Object } +function _decode(data, offset) { + if (data.length === 0) { + logger_js_1.logger.throwError("data too short", "BUFFER_OVERRUN", { + buffer: data, length: 0, offset: 1 + }); + } + const checkOffset = (offset) => { + if (offset > data.length) { + logger_js_1.logger.throwError("data short segment too short", "BUFFER_OVERRUN", { + buffer: data, length: data.length, offset + }); + } + }; + // Array with extra length prefix + if (data[offset] >= 0xf8) { + const lengthLength = data[offset] - 0xf7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } + else if (data[offset] >= 0xc0) { + const length = data[offset] - 0xc0; + checkOffset(offset + 1 + length); + return _decodeChildren(data, offset, offset + 1, length); + } + else if (data[offset] >= 0xb8) { + const lengthLength = data[offset] - 0xb7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + const result = (0, data_js_1.hexlify)(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { consumed: (1 + lengthLength + length), result: result }; + } + else if (data[offset] >= 0x80) { + const length = data[offset] - 0x80; + checkOffset(offset + 1 + length); + const result = (0, data_js_1.hexlify)(data.slice(offset + 1, offset + 1 + length)); + return { consumed: (1 + length), result: result }; + } + return { consumed: 1, result: hexlifyByte(data[offset]) }; +} +function decodeRlp(_data) { + const data = logger_js_1.logger.getBytes(_data, "data"); + const decoded = _decode(data, 0); + if (decoded.consumed !== data.length) { + logger_js_1.logger.throwArgumentError("unexpected junk after rlp payload", "data", _data); + } + return decoded.result; +} +exports.decodeRlp = decodeRlp; +//# sourceMappingURL=rlp-decode.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/rlp-decode.js.map b/lib.commonjs/utils/rlp-decode.js.map new file mode 100644 index 000000000..9fa9f60f3 --- /dev/null +++ b/lib.commonjs/utils/rlp-decode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp-decode.js","sourceRoot":"","sources":["../../src.ts/utils/rlp-decode.ts"],"names":[],"mappings":";AAAA,gDAAgD;;;AAEhD,uCAAoC;AACpC,2CAAqC;AAKrC,SAAS,WAAW,CAAC,KAAa;IAC9B,IAAI,MAAM,GAAG,KAAK,CA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AAK,EAAE,MAAM,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACjC,IAAI,OAAO,CAAC,QAAQ,KAAK,IAAI,CAAC,MAAM,EAAE;QAClC,kBAAM,CAAC,kBAAkB,CAAC,mCAAmC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;KACjF;IACD,OAAO,OAAO,CAAC,MAAM,CAAC;AAC1B,CAAC;AAPD,8BAOC"} \ No newline at end of file diff --git a/lib.commonjs/utils/rlp-encode.js b/lib.commonjs/utils/rlp-encode.js new file mode 100644 index 000000000..9f0c0edb4 --- /dev/null +++ b/lib.commonjs/utils/rlp-encode.js @@ -0,0 +1,50 @@ +"use strict"; +//See: https://github.com/ethereum/wiki/wiki/RLP +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeRlp = void 0; +const logger_js_1 = require("./logger.js"); +function arrayifyInteger(value) { + const result = []; + while (value) { + result.unshift(value & 0xff); + value >>= 8; + } + return result; +} +function _encode(object) { + if (Array.isArray(object)) { + let payload = []; + object.forEach(function (child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(0xc0 + payload.length); + return payload; + } + const length = arrayifyInteger(payload.length); + length.unshift(0xf7 + length.length); + return length.concat(payload); + } + const data = Array.prototype.slice.call(logger_js_1.logger.getBytes(object, "object")); + if (data.length === 1 && data[0] <= 0x7f) { + return data; + } + else if (data.length <= 55) { + data.unshift(0x80 + data.length); + return data; + } + const length = arrayifyInteger(data.length); + length.unshift(0xb7 + length.length); + return length.concat(data); +} +const nibbles = "0123456789abcdef"; +function encodeRlp(object) { + let result = "0x"; + for (const v of _encode(object)) { + result += nibbles[v >> 4]; + result += nibbles[v & 0xf]; + } + return result; +} +exports.encodeRlp = encodeRlp; +//# sourceMappingURL=rlp-encode.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/rlp-encode.js.map b/lib.commonjs/utils/rlp-encode.js.map new file mode 100644 index 000000000..631c4a758 --- /dev/null +++ b/lib.commonjs/utils/rlp-encode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp-encode.js","sourceRoot":"","sources":["../../src.ts/utils/rlp-encode.ts"],"names":[],"mappings":";AAAA,gDAAgD;;;AAEhD,2CAAqC;AAKrC,SAAS,eAAe,CAAC,KAAa;IAClC,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,OAAO,KAAK,EAAE;QACV,MAAM,CAAC,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;QAC7B,KAAK,KAAK,CAAC,CAAC;KACf;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,SAAS,OAAO,CAAC,MAA2B;IACxC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACvB,IAAI,OAAO,GAAkB,EAAE,CAAC;QAChC,MAAM,CAAC,OAAO,CAAC,UAAS,KAAK;YACzB,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;QAEH,IAAI,OAAO,CAAC,MAAM,IAAI,EAAE,EAAE;YACtB,OAAO,CAAC,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;YACtC,OAAO,OAAO,CAAC;SAClB;QAED,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC/C,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;QAErC,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;KAEjC;IAED,MAAM,IAAI,GAAkB,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IAE1F,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE;QACtC,OAAO,IAAI,CAAC;KAEf;SAAM,IAAI,IAAI,CAAC,MAAM,IAAI,EAAE,EAAE;QAC1B,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;KACf;IAED,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5C,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAErC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAED,MAAM,OAAO,GAAG,kBAAkB,CAAC;AAEnC,SAAgB,SAAS,CAAC,MAAyB;IAC/C,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,EAAE;QAC7B,MAAM,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1B,MAAM,IAAI,OAAO,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;KAC9B;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAPD,8BAOC"} \ No newline at end of file diff --git a/lib.commonjs/utils/rlp.js b/lib.commonjs/utils/rlp.js new file mode 100644 index 000000000..16aedfcd6 --- /dev/null +++ b/lib.commonjs/utils/rlp.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeRlp = exports.decodeRlp = void 0; +var rlp_decode_js_1 = require("./rlp-decode.js"); +Object.defineProperty(exports, "decodeRlp", { enumerable: true, get: function () { return rlp_decode_js_1.decodeRlp; } }); +var rlp_encode_js_1 = require("./rlp-encode.js"); +Object.defineProperty(exports, "encodeRlp", { enumerable: true, get: function () { return rlp_encode_js_1.encodeRlp; } }); +//# sourceMappingURL=rlp.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/rlp.js.map b/lib.commonjs/utils/rlp.js.map new file mode 100644 index 000000000..07f289412 --- /dev/null +++ b/lib.commonjs/utils/rlp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp.js","sourceRoot":"","sources":["../../src.ts/utils/rlp.ts"],"names":[],"mappings":";;;AAGA,iDAA4C;AAAnC,0GAAA,SAAS,OAAA;AAClB,iDAA4C;AAAnC,0GAAA,SAAS,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/utils/storage.js b/lib.commonjs/utils/storage.js new file mode 100644 index 000000000..4b41424b2 --- /dev/null +++ b/lib.commonjs/utils/storage.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setStore = exports.getStore = void 0; +function getStore(store, key) { + return store[key]; +} +exports.getStore = getStore; +function setStore(store, key, value) { + if (Object.isFrozen(store)) { + throw new Error(`frozen object is immuatable; cannot set ${String(key)}`); + } + store[key] = value; +} +exports.setStore = setStore; +//# sourceMappingURL=storage.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/storage.js.map b/lib.commonjs/utils/storage.js.map new file mode 100644 index 000000000..d05fdffa9 --- /dev/null +++ b/lib.commonjs/utils/storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src.ts/utils/storage.ts"],"names":[],"mappings":";;;AAAA,SAAgB,QAAQ,CAAuB,KAAQ,EAAE,GAAM;IAC3D,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAFD,4BAEC;AAED,SAAgB,QAAQ,CAAuB,KAAQ,EAAE,GAAM,EAAE,KAAW;IACxE,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,2CAA4C,MAAM,CAAC,GAAG,CAAE,EAAE,CAAC,CAAC;KAC/E;IACD,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AACvB,CAAC;AALD,4BAKC"} \ No newline at end of file diff --git a/lib.commonjs/utils/units.js b/lib.commonjs/utils/units.js new file mode 100644 index 000000000..d218493d0 --- /dev/null +++ b/lib.commonjs/utils/units.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseEther = exports.formatEther = exports.parseUnits = exports.formatUnits = void 0; +const fixednumber_js_1 = require("./fixednumber.js"); +const logger_js_1 = require("./logger.js"); +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether", +]; +/** + * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal + * places. The %%unit%% may be the number of decimal places or the name of + * a unit (e.g. ``"gwei"`` for 9 decimal places). + * + */ +function formatUnits(value, unit) { + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + if (index === -1) { + logger_js_1.logger.throwArgumentError("invalid unit", "unit", unit); + } + unit = 3 * index; + } + return (0, fixednumber_js_1.formatFixed)(value, (unit != null) ? unit : 18); +} +exports.formatUnits = formatUnits; +/** + * Converts the //decimal string// %%value%% to a [[BigInt]], assuming + * %%unit%% decimal places. The %%unit%% may the number of decimal places + * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places). + */ +function parseUnits(value, unit) { + if (typeof (value) !== "string") { + logger_js_1.logger.throwArgumentError("value must be a string", "value", value); + } + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + if (index === -1) { + logger_js_1.logger.throwArgumentError("invalid unit", "unit", unit); + } + unit = 3 * index; + } + return (0, fixednumber_js_1.parseFixed)(value, (unit != null) ? unit : 18); +} +exports.parseUnits = parseUnits; +/** + * Converts %%value%% into a //decimal string// using 18 decimal places. + */ +function formatEther(wei) { + return formatUnits(wei, 18); +} +exports.formatEther = formatEther; +/** + * Converts the //decimal string// %%ether%% to a [[BigInt]], using 18 + * decimal places. + */ +function parseEther(ether) { + return parseUnits(ether, 18); +} +exports.parseEther = parseEther; +//# sourceMappingURL=units.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/units.js.map b/lib.commonjs/utils/units.js.map new file mode 100644 index 000000000..ca348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,IAAI,GAAG,CAAC,GAAG,KAAK,CAAC;KACpB;IACD,OAAO,IAAA,2BAAU,EAAC,KAAK,EAAE,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA,CAAC,CAAC,EAAE,CAAC,CAAC;AACxD,CAAC;AAXD,gCAWC;AAED;;GAEG;AACH,SAAgB,WAAW,CAAC,GAAiB;IACzC,OAAO,WAAW,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;AAChC,CAAC;AAFD,kCAEC;AAED;;;GAGG;AACH,SAAgB,UAAU,CAAC,KAAa;IACpC,OAAO,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjC,CAAC;AAFD,gCAEC"} \ No newline at end of file diff --git a/lib.commonjs/utils/utf8.js b/lib.commonjs/utils/utf8.js new file mode 100644 index 000000000..ae1227dba --- /dev/null +++ b/lib.commonjs/utils/utf8.js @@ -0,0 +1,214 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toUtf8CodePoints = exports.toUtf8String = exports._toUtf8String = exports._toEscapedUtf8String = exports.toUtf8Bytes = exports.Utf8ErrorFuncs = void 0; +const logger_js_1 = require("./logger.js"); +function errorFunc(reason, offset, bytes, output, badCodepoint) { + return logger_js_1.logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === "OVERRUN") { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === "OVERLONG") { + output.push((badCodepoint != null) ? badCodepoint : -1); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes, output, badCodepoint); +} +// Common error handing strategies +exports.Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = exports.Utf8ErrorFuncs.error; + } + const bytes = logger_js_1.logger.getBytes(_bytes, "bytes"); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result); + } + else { + i += onError("BAD_PREFIX", i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError("OVERRUN", i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError("MISSING_CONTINUE", i, bytes, result); + res = null; + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +function toUtf8Bytes(str, form) { + if (form != null) { + logger_js_1.logger.assertNormalize(form); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return new Uint8Array(result); +} +exports.toUtf8Bytes = toUtf8Bytes; +; +function escapeChar(value) { + const hex = ("0000" + value.toString(16)); + return "\\u" + hex.substring(hex.length - 4); +} +function _toEscapedUtf8String(bytes, onError) { + return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => { + if (codePoint < 256) { + switch (codePoint) { + case 8: return "\\b"; + case 9: return "\\t"; + case 10: return "\\n"; + case 13: return "\\r"; + case 34: return "\\\""; + case 92: return "\\\\"; + } + if (codePoint >= 32 && codePoint < 127) { + return String.fromCharCode(codePoint); + } + } + if (codePoint <= 0xffff) { + return escapeChar(codePoint); + } + codePoint -= 0x10000; + return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00); + }).join("") + '"'; +} +exports._toEscapedUtf8String = _toEscapedUtf8String; +function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +exports._toUtf8String = _toUtf8String; +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +exports.toUtf8String = toUtf8String; +function toUtf8CodePoints(str, form) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +exports.toUtf8CodePoints = toUtf8CodePoints; +//# sourceMappingURL=utf8.js.map \ No newline at end of file diff --git a/lib.commonjs/utils/utf8.js.map b/lib.commonjs/utils/utf8.js.map new file mode 100644 index 000000000..b9b5e1373 --- /dev/null +++ b/lib.commonjs/utils/utf8.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utf8.js","sourceRoot":"","sources":["../../src.ts/utils/utf8.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AA4CrC,SAAS,SAAS,CAAC,MAAuB,EAAE,MAAc,EAAE,KAAwB,EAAE,MAAqB,EAAE,YAAqB;IAC9H,OAAO,kBAAM,CAAC,kBAAkB,CAAC,+BAAgC,MAAO,KAAM,MAAO,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC7G,CAAC;AAED,SAAS,UAAU,CAAC,MAAuB,EAAE,MAAc,EAAE,KAAwB,EAAE,MAAqB,EAAE,YAAqB;IAE/H,uGAAuG;IACvG,IAAI,MAAM,KAAK,YAAY,IAAI,MAAM,KAAK,qBAAqB,EAAE;QAC7D,IAAI,CAAC,GAAG,CAAC,CAAC;QACV,KAAK,IAAI,CAAC,GAAG,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AAC,YAAY,CACtB,CAAC,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,EACtC,CAAC,CAAC,SAAS,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,CACjC,CAAC;IACN,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAChB,CAAC;AAXD,sCAWC;AAED,SAAgB,YAAY,CAAC,KAAgB,EAAE,OAAuB;IAClE,OAAO,aAAa,CAAC,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC5D,CAAC;AAFD,oCAEC;AAED,SAAgB,gBAAgB,CAAC,GAAW,EAAE,IAA+B;IACzE,OAAO,iBAAiB,CAAC,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;AACrD,CAAC;AAFD,4CAEC"} \ 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 000000000..fca5ad704 --- /dev/null +++ b/lib.commonjs/wallet/base-wallet.js @@ -0,0 +1,66 @@ +"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"); +class BaseWallet extends index_js_3.AbstractSigner { + address; + #signingKey; + constructor(privateKey, provider) { + super(provider); + this.#signingKey = privateKey; + const address = (0, index_js_4.computeAddress)(this.signingKey.publicKey); + (0, index_js_5.defineProperties)(this, { address }); + } + // Store these in getters to reduce visibility in console.log + get signingKey() { return this.#signingKey; } + 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 tx = Object.assign({}, _tx, 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 (tx.from != null) { + if ((0, index_js_1.getAddress)(tx.from) !== this.address) { + index_js_5.logger.throwArgumentError("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.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) => { + if (this.provider == null) { + return index_js_5.logger.throwError("cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name } + }); + } + const address = await this.provider.resolveName(name); + if (address == null) { + return index_js_5.logger.throwError("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 000000000..64bc09303 --- /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,oDAAuD;AACvD,sDAAsE;AACtE,gDAAgF;AAQhF,MAAa,UAAW,SAAQ,yBAAc;IACjC,OAAO,CAAU;IAEjB,WAAW,CAAa;IAEjC,YAAY,UAAsB,EAAE,QAA0B;QAC1D,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChB,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAE9B,MAAM,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AK,CAAC,CAAC,CAAC,UAAU,CAAC;IAC5G,CAAC;CACJ;AAvED,gCAuEC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/hdwallet.js b/lib.commonjs/wallet/hdwallet.js new file mode 100644 index 000000000..af7ff7018 --- /dev/null +++ b/lib.commonjs/wallet/hdwallet.js @@ -0,0 +1,291 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getAccountPath = exports.HDNodeWalletManager = exports.HDNodeVoidWallet = exports.HDNodeWallet = exports.defaultPath = void 0; +const index_js_1 = require("../crypto/index.js"); +const index_js_2 = require("../providers/index.js"); +const index_js_3 = require("../transaction/index.js"); +const index_js_4 = require("../utils/index.js"); +const lang_en_js_1 = require("../wordlists/lang-en.js"); +const mnemonic_js_1 = require("./mnemonic.js"); +const base_wallet_js_1 = require("./base-wallet.js"); +exports.defaultPath = "m/44'/60'/0'/0/0"; +// "Bitcoin seed" +const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); +const HardenedBit = 0x80000000; +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const Nibbles = "0123456789abcdef"; +function zpad(value, length) { + let result = ""; + while (value) { + result = Nibbles[value % 16] + result; + value = Math.trunc(value / 16); + } + while (result.length < length * 2) { + result = "0" + result; + } + return "0x" + result; +} +function encodeBase58Check(_value) { + const value = index_js_4.logger.getBytes(_value); + const check = (0, index_js_4.dataSlice)((0, index_js_1.sha256)((0, index_js_1.sha256)(value)), 0, 4); + const bytes = (0, index_js_4.concat)([value, check]); + return (0, index_js_4.encodeBase58)(bytes); +} +const _guard = {}; +function ser_I(index, chainCode, publicKey, privateKey) { + const data = new Uint8Array(37); + if (index & HardenedBit) { + if (privateKey == null) { + return index_js_4.logger.throwError("cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { + operation: "deriveChild" + }); + } + // Data = 0x00 || ser_256(k_par) + data.set(index_js_4.logger.getBytes(privateKey), 1); + } + else { + // Data = ser_p(point(k_par)) + data.set(index_js_4.logger.getBytes(publicKey)); + } + // Data += ser_32(i) + for (let i = 24; i >= 0; i -= 8) { + data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); + } + const I = index_js_4.logger.getBytes((0, index_js_1.computeHmac)("sha512", chainCode, data)); + return { IL: I.slice(0, 32), IR: I.slice(32) }; +} +function derivePath(node, path) { + const components = path.split("/"); + if (components.length === 0 || (components[0] === "m" && node.depth !== 0)) { + throw new Error("invalid path - " + path); + } + if (components[0] === "m") { + components.shift(); + } + let result = node; + for (let i = 0; i < components.length; i++) { + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index = parseInt(component.substring(0, component.length - 1)); + if (index >= HardenedBit) { + throw new Error("invalid path index - " + component); + } + result = result.deriveChild(HardenedBit + index); + } + else if (component.match(/^[0-9]+$/)) { + const index = parseInt(component); + if (index >= HardenedBit) { + throw new Error("invalid path index - " + component); + } + result = result.deriveChild(index); + } + else { + throw new Error("invalid path component - " + component); + } + } + return result; +} +class HDNodeWallet extends base_wallet_js_1.BaseWallet { + publicKey; + fingerprint; + parentFingerprint; + mnemonic; + chainCode; + path; + index; + depth; + constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) { + super(signingKey, provider); + index_js_4.logger.assertPrivate(guard, _guard, "HDNodeWallet"); + (0, index_js_4.defineProperties)(this, { publicKey: signingKey.compressedPublicKey }); + const fingerprint = (0, index_js_4.dataSlice)((0, index_js_1.ripemd160)((0, index_js_1.sha256)(this.publicKey)), 0, 4); + (0, index_js_4.defineProperties)(this, { + parentFingerprint, fingerprint, + chainCode, path, index, depth + }); + (0, index_js_4.defineProperties)(this, { mnemonic }); + } + connect(provider) { + return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); + } + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return encodeBase58Check((0, index_js_4.concat)([ + "0x0488ADE4", zpad(this.depth, 1), this.parentFingerprint, + zpad(this.index, 4), this.chainCode, + (0, index_js_4.concat)(["0x00", this.privateKey]) + ])); + } + hasPath() { return (this.path != null); } + neuter() { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); + } + deriveChild(_index) { + const index = index_js_4.logger.getNumber(_index, "index"); + if (index > 0xffffffff) { + throw new Error("invalid index - " + String(index)); + } + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); + const ki = new index_js_1.SigningKey((0, index_js_4.toHex)(((0, index_js_4.toBigInt)(IL) + BigInt(this.privateKey)) % N, 32)); + return new HDNodeWallet(_guard, ki, this.fingerprint, (0, index_js_4.hexlify)(IR), path, index, this.depth + 1, this.mnemonic, this.provider); + } + derivePath(path) { + return derivePath(this, path); + } + static #fromSeed(_seed, mnemonic) { + const seed = index_js_4.logger.getBytes(_seed, "seed"); + if (seed.length < 16 || seed.length > 64) { + throw new Error("invalid seed"); + } + const I = index_js_4.logger.getBytes((0, index_js_1.computeHmac)("sha512", MasterSecret, seed)); + const signingKey = new index_js_1.SigningKey((0, index_js_4.hexlify)(I.slice(0, 32))); + return new HDNodeWallet(_guard, signingKey, "0x00000000", (0, index_js_4.hexlify)(I.slice(32)), "m", 0, 0, mnemonic, null); + } + static fromSeed(seed) { + return HDNodeWallet.#fromSeed(seed, null); + } + static fromPhrase(phrase, password = "", path = exports.defaultPath, wordlist = lang_en_js_1.langEn) { + if (!path) { + path = exports.defaultPath; + } + const mnemonic = mnemonic_js_1.Mnemonic.fromPhrase(phrase, password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromMnemonic(mnemonic, path = exports.defaultPath) { + if (!path) { + path = exports.defaultPath; + } + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromExtendedKey(extendedKey) { + const bytes = index_js_4.logger.getBytes((0, index_js_4.decodeBase58)(extendedKey)); // @TODO: redact + if (bytes.length !== 82 || encodeBase58Check(bytes.slice(0, 78)) !== extendedKey) { + index_js_4.logger.throwArgumentError("invalid extended key", "extendedKey", "[ REDACTED ]"); + } + const depth = bytes[4]; + const parentFingerprint = (0, index_js_4.hexlify)(bytes.slice(5, 9)); + const index = parseInt((0, index_js_4.hexlify)(bytes.slice(9, 13)).substring(2), 16); + const chainCode = (0, index_js_4.hexlify)(bytes.slice(13, 45)); + const key = bytes.slice(45, 78); + switch ((0, index_js_4.hexlify)(bytes.slice(0, 4))) { + // Public Key + case "0x0488b21e": + case "0x043587cf": { + const publicKey = (0, index_js_4.hexlify)(key); + return new HDNodeVoidWallet(_guard, (0, index_js_3.computeAddress)(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); + } + // Private Key + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new HDNodeWallet(_guard, new index_js_1.SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); + } + return index_js_4.logger.throwArgumentError("invalid extended key prefix", "extendedKey", "[ REDACTED ]"); + } + static createRandom(password = "", path = exports.defaultPath, wordlist = lang_en_js_1.langEn) { + if (!path) { + path = exports.defaultPath; + } + const mnemonic = mnemonic_js_1.Mnemonic.fromEntropy((0, index_js_1.randomBytes)(16), password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } +} +exports.HDNodeWallet = HDNodeWallet; +class HDNodeVoidWallet extends index_js_2.VoidSigner { + publicKey; + fingerprint; + parentFingerprint; + chainCode; + path; + index; + depth; + constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) { + super(address, provider); + index_js_4.logger.assertPrivate(guard, _guard, "HDNodeVoidWallet"); + (0, index_js_4.defineProperties)(this, { publicKey }); + const fingerprint = (0, index_js_4.dataSlice)((0, index_js_1.ripemd160)((0, index_js_1.sha256)(publicKey)), 0, 4); + (0, index_js_4.defineProperties)(this, { + publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth + }); + } + connect(provider) { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); + } + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return encodeBase58Check((0, index_js_4.concat)([ + "0x0488B21E", + zpad(this.depth, 1), + this.parentFingerprint, + zpad(this.index, 4), + this.chainCode, + this.publicKey, + ])); + } + hasPath() { return (this.path != null); } + deriveChild(_index) { + const index = index_js_4.logger.getNumber(_index, "index"); + if (index > 0xffffffff) { + throw new Error("invalid index - " + String(index)); + } + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); + const Ki = index_js_1.SigningKey._addPoints(IL, this.publicKey, true); + const address = (0, index_js_3.computeAddress)(Ki); + return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, (0, index_js_4.hexlify)(IR), path, index, this.depth + 1, this.provider); + } + derivePath(path) { + return derivePath(this, path); + } +} +exports.HDNodeVoidWallet = HDNodeVoidWallet; +class HDNodeWalletManager { + #root; + constructor(phrase, password = "", path = "m/44'/60'/0'/0", locale = lang_en_js_1.langEn) { + this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale); + } + getSigner(index = 0) { + return this.#root.deriveChild(index); + } +} +exports.HDNodeWalletManager = HDNodeWalletManager; +function getAccountPath(_index) { + const index = index_js_4.logger.getNumber(_index, "index"); + if (index < 0 || index >= HardenedBit) { + index_js_4.logger.throwArgumentError("invalid account index", "index", index); + } + return `m/44'/60'/${index}'/0/0`; +} +exports.getAccountPath = getAccountPath; +//# sourceMappingURL=hdwallet.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/hdwallet.js.map b/lib.commonjs/wallet/hdwallet.js.map new file mode 100644 index 000000000..0993d35be --- /dev/null +++ b/lib.commonjs/wallet/hdwallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hdwallet.js","sourceRoot":"","sources":["../../src.ts/wallet/hdwallet.ts"],"names":[],"mappings":";;;AAAA,iDAA6F;AAC7F,oDAAmD;AACnD,sDAAyD;AACzD,gDAE2B;AAC3B,wDAAiD;AAEjD,+CAAyC;AACzC,qDAA8C;AAOjC,QAAA,WAAW,GAAG,kBAAkB,CAAC;AAG9C,iBAAiB;AACjB,MAAM,YAAY,GAAG,IAAI,UAAU,CAAC,CAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAE,CAAC,CAAC;AAEjG,MAAM,WAAW,GAAG,UAAU,CAAC;AAE/B,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAEvF,MAAM,OAAO,GAAG,kBAAkB,CAAC;AACnC,SAAS,IAAI,CAAC,KAAa,EAAE,MAAc;IACvC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,OAAO,KAAK,EAAE;QACV,MAAM,GAAG,OAAO,CAAC,KAAK,GAAG,EAAE,CAAC,GAAG,MAAM,CAAC;QACtC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC,CAAC;KAClC;IACD,OAAO,MAAM,CAAC,M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AAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAEpD,CAAC;IAED,UAAU,CAAC,IAAY;QACnB,OAAO,UAAU,CAAmB,IAAI,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;CACJ;AA1ED,4CA0EC;AAED,MAAa,mBAAmB;IAC5B,KAAK,CAAe;IAEpB,YAAY,MAAc,EAAE,QAAQ,GAAG,EAAE,EAAE,IAAI,GAAG,gBAAgB,EAAE,SAAmB,mBAAM;QACzF,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACzE,CAAC;IAED,SAAS,CAAC,KAAK,GAAG,CAAC;QACf,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;CACJ;AAVD,kDAUC;AAED,SAAgB,cAAc,CAAC,MAAe;IAC1C,MAAM,KAAK,GAAG,iBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChD,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,WAAW,EAAE;QACnC,iBAAM,CAAC,kBAAkB,CAAC,uBAAuB,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;KACtE;IACD,OAAO,aAAc,KAAM,OAAO,CAAC;AACvC,CAAC;AAND,wCAMC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/index.js b/lib.commonjs/wallet/index.js new file mode 100644 index 000000000..7db150996 --- /dev/null +++ b/lib.commonjs/wallet/index.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Wallet = exports.Mnemonic = exports.encryptKeystoreJson = exports.decryptKeystoreJson = exports.decryptKeystoreJsonSync = exports.isKeystoreJson = exports.decryptCrowdsaleJson = exports.isCrowdsaleJson = exports.HDNodeWalletManager = exports.HDNodeVoidWallet = exports.HDNodeWallet = exports.getAccountPath = exports.defaultPath = void 0; +var hdwallet_js_1 = require("./hdwallet.js"); +Object.defineProperty(exports, "defaultPath", { enumerable: true, get: function () { return hdwallet_js_1.defaultPath; } }); +Object.defineProperty(exports, "getAccountPath", { enumerable: true, get: function () { return hdwallet_js_1.getAccountPath; } }); +Object.defineProperty(exports, "HDNodeWallet", { enumerable: true, get: function () { return hdwallet_js_1.HDNodeWallet; } }); +Object.defineProperty(exports, "HDNodeVoidWallet", { enumerable: true, get: function () { return hdwallet_js_1.HDNodeVoidWallet; } }); +Object.defineProperty(exports, "HDNodeWalletManager", { enumerable: true, get: function () { return hdwallet_js_1.HDNodeWalletManager; } }); +var json_crowdsale_js_1 = require("./json-crowdsale.js"); +Object.defineProperty(exports, "isCrowdsaleJson", { enumerable: true, get: function () { return json_crowdsale_js_1.isCrowdsaleJson; } }); +Object.defineProperty(exports, "decryptCrowdsaleJson", { enumerable: true, get: function () { return json_crowdsale_js_1.decryptCrowdsaleJson; } }); +var json_keystore_js_1 = require("./json-keystore.js"); +Object.defineProperty(exports, "isKeystoreJson", { enumerable: true, get: function () { return json_keystore_js_1.isKeystoreJson; } }); +Object.defineProperty(exports, "decryptKeystoreJsonSync", { enumerable: true, get: function () { return json_keystore_js_1.decryptKeystoreJsonSync; } }); +Object.defineProperty(exports, "decryptKeystoreJson", { enumerable: true, get: function () { return json_keystore_js_1.decryptKeystoreJson; } }); +Object.defineProperty(exports, "encryptKeystoreJson", { enumerable: true, get: function () { return json_keystore_js_1.encryptKeystoreJson; } }); +var mnemonic_js_1 = require("./mnemonic.js"); +Object.defineProperty(exports, "Mnemonic", { enumerable: true, get: function () { return mnemonic_js_1.Mnemonic; } }); +var wallet_js_1 = require("./wallet.js"); +Object.defineProperty(exports, "Wallet", { enumerable: true, get: function () { return wallet_js_1.Wallet; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/index.js.map b/lib.commonjs/wallet/index.js.map new file mode 100644 index 000000000..866518271 --- /dev/null +++ b/lib.commonjs/wallet/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/wallet/index.ts"],"names":[],"mappings":";;;AAAA,6CAQuB;AAPnB,0GAAA,WAAW,OAAA;AAEX,6GAAA,cAAc,OAAA;AAEd,2GAAA,YAAY,OAAA;AACZ,+GAAA,gBAAgB,OAAA;AAChB,kHAAA,mBAAmB,OAAA;AAEvB,yDAA4E;AAAnE,oHAAA,eAAe,OAAA;AAAE,yHAAA,oBAAoB,OAAA;AAC9C,uDAI4B;AAHxB,kHAAA,cAAc,OAAA;AACd,2HAAA,uBAAuB,OAAA;AAAE,uHAAA,mBAAmB,OAAA;AAC5C,uHAAA,mBAAmB,OAAA;AAEvB,6CAAyC;AAAhC,uGAAA,QAAQ,OAAA;AACjB,yCAAqC;AAA5B,mGAAA,MAAM,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/wallet/json-crowdsale.js b/lib.commonjs/wallet/json-crowdsale.js new file mode 100644 index 000000000..71ee96f68 --- /dev/null +++ b/lib.commonjs/wallet/json-crowdsale.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decryptCrowdsaleJson = exports.isCrowdsaleJson = void 0; +const aes_js_1 = require("aes-js"); +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../crypto/index.js"); +const id_js_1 = require("../hash/id.js"); +const index_js_3 = require("../utils/index.js"); +const utils_js_1 = require("./utils.js"); +function isCrowdsaleJson(json) { + try { + const data = JSON.parse(json); + if (data.encseed) { + return true; + } + } + catch (error) { } + return false; +} +exports.isCrowdsaleJson = isCrowdsaleJson; +// See: https://github.com/ethereum/pyethsaletool +function decryptCrowdsaleJson(json, _password) { + const data = JSON.parse(json); + const password = (0, utils_js_1.getPassword)(_password); + // Ethereum Address + const address = (0, index_js_1.getAddress)((0, utils_js_1.spelunk)(data, "ethaddr:string!")); + // Encrypted Seed + const encseed = (0, utils_js_1.looseArrayify)((0, utils_js_1.spelunk)(data, "encseed:string!")); + if (!encseed || (encseed.length % 16) !== 0) { + index_js_3.logger.throwArgumentError("invalid encseed", "json", json); + } + const key = index_js_3.logger.getBytes((0, index_js_2.pbkdf2)(password, password, 2000, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + // Decrypt the seed + const aesCbc = new aes_js_1.CBC(key, iv); + const seed = (0, aes_js_1.pkcs7Strip)(index_js_3.logger.getBytes(aesCbc.decrypt(encryptedSeed))); + // This wallet format is weird... Convert the binary encoded hex to a string. + let seedHex = ""; + for (let i = 0; i < seed.length; i++) { + seedHex += String.fromCharCode(seed[i]); + } + return { address, privateKey: (0, id_js_1.id)(seedHex) }; +} +exports.decryptCrowdsaleJson = decryptCrowdsaleJson; +//# sourceMappingURL=json-crowdsale.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/json-crowdsale.js.map b/lib.commonjs/wallet/json-crowdsale.js.map new file mode 100644 index 000000000..2c36739ca --- /dev/null +++ b/lib.commonjs/wallet/json-crowdsale.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json-crowdsale.js","sourceRoot":"","sources":["../../src.ts/wallet/json-crowdsale.ts"],"names":[],"mappings":";;;AAAA,mCAAyC;AAEzC,kDAAiD;AACjD,iDAA4C;AAC5C,yCAAmC;AACnC,gDAA2C;AAE3C,yCAAiE;AAQjE,SAAgB,eAAe,CAAC,IAAY;IACxC,IAAI;QACA,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,IAAI,CAAC,OAAO,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;KACrC;IAAC,OAAO,KAAK,EAAE,GAAG;IACnB,OAAO,KAAK,CAAC;AACjB,CAAC;AAND,0CAMC;AAED,iDAAiD;AACjD,SAAgB,oBAAoB,CAAC,IAAY,EAAE,SAA8B;IAC7E,MAAM,IAAI,GAAG,I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,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;KAC3C;IAED,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAA,UAAE,EAAC,OAAO,CAAC,EAAE,CAAC;AAChD,CAAC;AA7BD,oDA6BC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/json-keystore.js b/lib.commonjs/wallet/json-keystore.js new file mode 100644 index 000000000..1adc23041 --- /dev/null +++ b/lib.commonjs/wallet/json-keystore.js @@ -0,0 +1,286 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encryptKeystoreJson = exports.decryptKeystoreJson = exports.decryptKeystoreJsonSync = exports.isKeystoreJson = void 0; +const aes_js_1 = require("aes-js"); +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../crypto/index.js"); +const index_js_3 = require("../transaction/index.js"); +const index_js_4 = require("../utils/index.js"); +const utils_js_1 = require("./utils.js"); +const _version_js_1 = require("../_version.js"); +const defaultPath = "m/44'/60'/0'/0/0"; +function isKeystoreJson(json) { + try { + const data = JSON.parse(json); + const version = ((data.version != null) ? parseInt(data.version) : 0); + if (version === 3) { + return true; + } + } + catch (error) { } + return false; +} +exports.isKeystoreJson = isKeystoreJson; +function decrypt(data, key, ciphertext) { + const cipher = (0, utils_js_1.spelunk)(data, "crypto.cipher:string"); + if (cipher === "aes-128-ctr") { + const iv = (0, utils_js_1.spelunk)(data, "crypto.cipherparams.iv:data!"); + const aesCtr = new aes_js_1.CTR(key, iv); + return (0, index_js_4.hexlify)(aesCtr.decrypt(ciphertext)); + } + return index_js_4.logger.throwError("unsupported cipher", "UNSUPPORTED_OPERATION", { + operation: "decrypt" + }); +} +function getAccount(data, _key) { + const key = index_js_4.logger.getBytes(_key); + const ciphertext = (0, utils_js_1.spelunk)(data, "crypto.ciphertext:data!"); + const computedMAC = (0, index_js_4.hexlify)((0, index_js_2.keccak256)((0, index_js_4.concat)([key.slice(16, 32), ciphertext]))).substring(2); + if (computedMAC !== (0, utils_js_1.spelunk)(data, "crypto.mac:string!").toLowerCase()) { + return index_js_4.logger.throwArgumentError("incorrect password", "password", "[ REDACTED ]"); + } + const privateKey = decrypt(data, key.slice(0, 16), ciphertext); + const address = (0, index_js_3.computeAddress)(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (check.substring(0, 2) !== "0x") { + check = "0x" + check; + } + if ((0, index_js_1.getAddress)(check) !== address) { + index_js_4.logger.throwArgumentError("keystore address/privateKey mismatch", "address", data.address); + } + } + const account = { address, privateKey }; + // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase + const version = (0, utils_js_1.spelunk)(data, "x-ethers.version:string"); + if (version === "0.1") { + const mnemonicKey = key.slice(32, 64); + const mnemonicCiphertext = (0, utils_js_1.spelunk)(data, "x-ethers.mnemonicCiphertext:data!"); + const mnemonicIv = (0, utils_js_1.spelunk)(data, "x-ethers.mnemonicCounter:data!"); + const mnemonicAesCtr = new aes_js_1.CTR(mnemonicKey, mnemonicIv); + account.mnemonic = { + path: ((0, utils_js_1.spelunk)(data, "x-ethers.path:string") || defaultPath), + locale: ((0, utils_js_1.spelunk)(data, "x-ethers.locale:string") || "en"), + entropy: (0, index_js_4.hexlify)(index_js_4.logger.getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))) + }; + } + return account; +} +function getKdfParams(data) { + const kdf = (0, utils_js_1.spelunk)(data, "crypto.kdf:string"); + if (kdf && typeof (kdf) === "string") { + const throwError = function (name, value) { + return index_js_4.logger.throwArgumentError("invalid key-derivation function parameters", name, value); + }; + if (kdf.toLowerCase() === "scrypt") { + const salt = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.salt:data!"); + const N = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.n:int!"); + const r = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.r:int!"); + const p = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.p:int!"); + // Check for all required parameters + if (!N || !r || !p) { + return throwError("kdf", kdf); + } + // Make sure N is a power of 2 + if ((N & (N - 1)) !== 0) { + return throwError("N", N); + } + const dkLen = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.dklen:int!"); + if (dkLen !== 32) { + return throwError("dklen", dkLen); + } + return { name: "scrypt", salt, N, r, p, dkLen: 64 }; + } + else if (kdf.toLowerCase() === "pbkdf2") { + const salt = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.salt:data!"); + const prf = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.prf:string!"); + const algorithm = prf.split("-").pop(); + if (algorithm !== "sha256" && algorithm !== "sha512") { + return throwError("prf", prf); + } + const count = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.c:int!"); + const dkLen = (0, utils_js_1.spelunk)(data, "crypto.kdfparams.dklen:int!"); + if (dkLen !== 32) { + throwError("dklen", dkLen); + } + return { name: "pbkdf2", salt, count, dkLen, algorithm }; + } + } + return index_js_4.logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf); +} +function decryptKeystoreJsonSync(json, _password) { + const data = JSON.parse(json); + const password = (0, utils_js_1.getPassword)(_password); + const params = getKdfParams(data); + if (params.name === "pbkdf2") { + const { salt, count, dkLen, algorithm } = params; + const key = (0, index_js_2.pbkdf2)(password, salt, count, dkLen, algorithm); + return getAccount(data, key); + } + else if (params.name === "scrypt") { + const { salt, N, r, p, dkLen } = params; + const key = (0, index_js_2.scryptSync)(password, salt, N, r, p, dkLen); + return getAccount(data, key); + } + throw new Error("unreachable"); +} +exports.decryptKeystoreJsonSync = decryptKeystoreJsonSync; +function stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +async function decryptKeystoreJson(json, _password, progress) { + const data = JSON.parse(json); + const password = (0, utils_js_1.getPassword)(_password); + const params = getKdfParams(data); + if (params.name === "pbkdf2") { + if (progress) { + progress(0); + await stall(0); + } + const { salt, count, dkLen, algorithm } = params; + const key = (0, index_js_2.pbkdf2)(password, salt, count, dkLen, algorithm); + if (progress) { + progress(1); + await stall(0); + } + return getAccount(data, key); + } + else if (params.name === "scrypt") { + const { salt, N, r, p, dkLen } = params; + const key = await (0, index_js_2.scrypt)(password, salt, N, r, p, dkLen, progress); + return getAccount(data, key); + } + throw new Error("unreachable"); +} +exports.decryptKeystoreJson = decryptKeystoreJson; +async function encryptKeystoreJson(account, password, options, progressCallback) { + // Check the address matches the private key + //if (getAddress(account.address) !== computeAddress(account.privateKey)) { + // throw new Error("address/privateKey mismatch"); + //} + // Check the mnemonic (if any) matches the private key + /* + if (hasMnemonic(account)) { + const mnemonic = account.mnemonic; + const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath); + + if (node.privateKey != account.privateKey) { + throw new Error("mnemonic mismatch"); + } + } + */ + // The options are optional, so adjust the call as needed + if (typeof (options) === "function" && !progressCallback) { + progressCallback = options; + options = {}; + } + if (!options) { + options = {}; + } + const privateKey = index_js_4.logger.getBytes(account.privateKey, "privateKey"); + const passwordBytes = (0, utils_js_1.getPassword)(password); + /* + let mnemonic: null | Mnemonic = null; + let entropy: Uint8Array = null + let path: string = null; + let locale: string = null; + if (hasMnemonic(account)) { + const srcMnemonic = account.mnemonic; + entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en")); + path = srcMnemonic.path || defaultPath; + locale = srcMnemonic.locale || "en"; + mnemonic = Mnemonic.from( + } + */ + // Check/generate the salt + const salt = (options.salt != null) ? index_js_4.logger.getBytes(options.salt, "options.slat") : (0, index_js_2.randomBytes)(32); + // Override initialization vector + const iv = (options.iv != null) ? index_js_4.logger.getBytes(options.iv, "options.iv") : (0, index_js_2.randomBytes)(16); + if (iv.length !== 16) { + index_js_4.logger.throwArgumentError("invalid options.iv", "options.iv", options.iv); + } + // Override the uuid + const uuidRandom = (options.uuid != null) ? index_js_4.logger.getBytes(options.uuid, "options.uuid") : (0, index_js_2.randomBytes)(16); + if (uuidRandom.length !== 16) { + index_js_4.logger.throwArgumentError("invalid options.uuid", "options.uuid", options.iv); + } + if (uuidRandom.length !== 16) { + throw new Error("invalid uuid"); + } + // Override the scrypt password-based key derivation function parameters + let N = (1 << 17), r = 8, p = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N = options.scrypt.N; + } + if (options.scrypt.r) { + r = options.scrypt.r; + } + if (options.scrypt.p) { + p = options.scrypt.p; + } + } + // We take 64 bytes: + // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) + // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet) + const _key = await (0, index_js_2.scrypt)(passwordBytes, salt, N, r, p, 64, progressCallback); + const key = index_js_4.logger.getBytes(_key); + // This will be used to encrypt the wallet (as per Web3 secret storage) + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + // Encrypt the private key + const aesCtr = new aes_js_1.CTR(derivedKey, iv); + const ciphertext = index_js_4.logger.getBytes(aesCtr.encrypt(privateKey)); + // Compute the message authentication code, used to check the password + const mac = (0, index_js_2.keccak256)((0, index_js_4.concat)([macPrefix, ciphertext])); + // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + const data = { + address: account.address.substring(2).toLowerCase(), + id: (0, utils_js_1.uuidV4)(uuidRandom), + version: 3, + Crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: (0, index_js_4.hexlify)(iv).substring(2), + }, + ciphertext: (0, index_js_4.hexlify)(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: (0, index_js_4.hexlify)(salt).substring(2), + n: N, + dklen: 32, + p: p, + r: r + }, + mac: mac.substring(2) + } + }; + // If we have a mnemonic, encrypt it into the JSON wallet + if (account.mnemonic) { + const client = (options.client != null) ? options.client : `ethers/${_version_js_1.version}`; + const path = account.mnemonic.path || defaultPath; + const locale = account.mnemonic.locale || "en"; + const mnemonicKey = key.slice(32, 64); + const entropy = index_js_4.logger.getBytes(account.mnemonic.entropy, "account.mnemonic.entropy"); + const mnemonicIv = (0, index_js_2.randomBytes)(16); + const mnemonicAesCtr = new aes_js_1.CTR(mnemonicKey, mnemonicIv); + const mnemonicCiphertext = index_js_4.logger.getBytes(mnemonicAesCtr.encrypt(entropy)); + const now = new Date(); + const timestamp = (now.getUTCFullYear() + "-" + + (0, utils_js_1.zpad)(now.getUTCMonth() + 1, 2) + "-" + + (0, utils_js_1.zpad)(now.getUTCDate(), 2) + "T" + + (0, utils_js_1.zpad)(now.getUTCHours(), 2) + "-" + + (0, utils_js_1.zpad)(now.getUTCMinutes(), 2) + "-" + + (0, utils_js_1.zpad)(now.getUTCSeconds(), 2) + ".0Z"); + const gethFilename = ("UTC--" + timestamp + "--" + data.address); + data["x-ethers"] = { + client, gethFilename, path, locale, + mnemonicCounter: (0, index_js_4.hexlify)(mnemonicIv).substring(2), + mnemonicCiphertext: (0, index_js_4.hexlify)(mnemonicCiphertext).substring(2), + version: "0.1" + }; + } + return JSON.stringify(data); +} +exports.encryptKeystoreJson = encryptKeystoreJson; +//# sourceMappingURL=json-keystore.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/json-keystore.js.map b/lib.commonjs/wallet/json-keystore.js.map new file mode 100644 index 000000000..a97c0c033 --- /dev/null +++ b/lib.commonjs/wallet/json-keystore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json-keystore.js","sourceRoot":"","sources":["../../src.ts/wallet/json-keystore.ts"],"names":[],"mappings":";;;AAAA,mCAA6B;AAE7B,kDAAiD;AACjD,iDAAwF;AACxF,sDAAyD;AACzD,gDAA4D;AAE5D,yCAAgE;AAKhE,gDAAyC;AAEzC,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAoCvC,SAAgB,cAAc,CAAC,IAAY;IACvC,IAAI;QACA,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9B,MAAM,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA,CAAC,CAAC,CAAC,CAA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,UAAU,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;YACjD,kBAAkB,EAAE,IAAA,kBAAO,EAAC,kBAAkB,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;YAC5D,OAAO,EAAE,KAAK;SACjB,CAAC;KACL;IAED,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AA1ID,kDA0IC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/mnemonic.js b/lib.commonjs/wallet/mnemonic.js new file mode 100644 index 000000000..287cc19c8 --- /dev/null +++ b/lib.commonjs/wallet/mnemonic.js @@ -0,0 +1,128 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Mnemonic = void 0; +const index_js_1 = require("../crypto/index.js"); +const index_js_2 = require("../utils/index.js"); +const lang_en_js_1 = require("../wordlists/lang-en.js"); +// Returns a byte with the MSB bits set +function getUpperMask(bits) { + return ((1 << bits) - 1) << (8 - bits) & 0xff; +} +// Returns a byte with the LSB bits set +function getLowerMask(bits) { + return ((1 << bits) - 1) & 0xff; +} +function mnemonicToEntropy(mnemonic, wordlist = lang_en_js_1.langEn) { + index_js_2.logger.assertNormalize("NFKD"); + if (wordlist == null) { + wordlist = lang_en_js_1.langEn; + } + const words = wordlist.split(mnemonic); + if ((words.length % 3) !== 0 || words.length < 12 || words.length > 24) { + index_js_2.logger.throwArgumentError("invalid mnemonic length", "mnemonic", "[ REDACTED ]"); + } + const entropy = new Uint8Array(Math.ceil(11 * words.length / 8)); + let offset = 0; + for (let i = 0; i < words.length; i++) { + let index = wordlist.getWordIndex(words[i].normalize("NFKD")); + if (index === -1) { + index_js_2.logger.throwArgumentError(`invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); + } + for (let bit = 0; bit < 11; bit++) { + if (index & (1 << (10 - bit))) { + entropy[offset >> 3] |= (1 << (7 - (offset % 8))); + } + offset++; + } + } + const entropyBits = 32 * words.length / 3; + const checksumBits = words.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum = index_js_2.logger.getBytes((0, index_js_1.sha256)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { + index_js_2.logger.throwArgumentError("invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); + } + return (0, index_js_2.hexlify)(entropy.slice(0, entropyBits / 8)); +} +function entropyToMnemonic(entropy, wordlist = lang_en_js_1.langEn) { + if ((entropy.length % 4) || entropy.length < 16 || entropy.length > 32) { + index_js_2.logger.throwArgumentError("invalid entropy size", "entropy", "[ REDACTED ]"); + } + if (wordlist == null) { + wordlist = lang_en_js_1.langEn; + } + const indices = [0]; + let remainingBits = 11; + for (let i = 0; i < entropy.length; i++) { + // Consume the whole byte (with still more to go) + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + // This byte will complete an 11-bit index + } + else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); + // Start the next word + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; + } + } + // Compute the checksum bits + const checksumBits = entropy.length / 4; + const checksum = parseInt((0, index_js_1.sha256)(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); + // Shift the checksum into the word indices + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= (checksum >> (8 - checksumBits)); + return wordlist.join(indices.map((index) => wordlist.getWord(index))); +} +const _guard = {}; +class Mnemonic { + phrase; + password; + wordlist; + entropy; + constructor(guard, entropy, phrase, password, wordlist) { + if (password == null) { + password = ""; + } + if (wordlist == null) { + wordlist = lang_en_js_1.langEn; + } + index_js_2.logger.assertPrivate(guard, _guard, "Mnemonic"); + (0, index_js_2.defineProperties)(this, { phrase, password, wordlist, entropy }); + } + computeSeed() { + const salt = (0, index_js_2.toUtf8Bytes)("mnemonic" + this.password, "NFKD"); + return (0, index_js_1.pbkdf2)((0, index_js_2.toUtf8Bytes)(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); + } + static fromPhrase(phrase, password, wordlist) { + // Normalize the case and space; throws if invalid + const entropy = mnemonicToEntropy(phrase, wordlist); + phrase = entropyToMnemonic(index_js_2.logger.getBytes(entropy), wordlist); + return new Mnemonic(_guard, entropy, phrase, password, wordlist); + } + static fromEntropy(_entropy, password, wordlist) { + const entropy = index_js_2.logger.getBytes(_entropy, "entropy"); + const phrase = entropyToMnemonic(entropy, wordlist); + return new Mnemonic(_guard, (0, index_js_2.hexlify)(entropy), phrase, password, wordlist); + } + static entropyToPhrase(_entropy, wordlist) { + const entropy = index_js_2.logger.getBytes(_entropy, "entropy"); + return entropyToMnemonic(entropy, wordlist); + } + static phraseToEntropy(phrase, wordlist) { + return mnemonicToEntropy(phrase, wordlist); + } + static isValidMnemonic(phrase, wordlist) { + try { + mnemonicToEntropy(phrase, wordlist); + return true; + } + catch (error) { } + return false; + } +} +exports.Mnemonic = Mnemonic; +//# sourceMappingURL=mnemonic.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/mnemonic.js.map b/lib.commonjs/wallet/mnemonic.js.map new file mode 100644 index 000000000..427a0c58a --- /dev/null +++ b/lib.commonjs/wallet/mnemonic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mnemonic.js","sourceRoot":"","sources":["../../src.ts/wallet/mnemonic.ts"],"names":[],"mappings":";;;AAAA,iDAAoD;AACpD,gDAAmF;AACnF,wDAAiD;AAMjD,uCAAuC;AACvC,SAAS,YAAY,CAAC,IAAY;IAC/B,OAAO,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;AACjD,CAAC;AAED,uCAAuC;AACvC,SAAS,YAAY,CAAC,IAAY;IAC/B,OAAO,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;AACnC,CAAC;AAG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AAC,CAAC;IACrE,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,QAAmB,EAAE,QAAwB,EAAE,QAA0B;QACxF,MAAM,OAAO,GAAG,iBAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QACrD,MAAM,MAAM,GAAG,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACpD,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,IAAA,kBAAO,EAAC,OAAO,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,QAAmB,EAAE,QAA0B;QAClE,MAAM,OAAO,GAAG,iBAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QACrD,OAAO,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,MAAc,EAAE,QAA0B;QAC7D,OAAO,iBAAiB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,MAAc,EAAE,QAA0B;QAC7D,IAAI;YACA,iBAAiB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YACpC,OAAO,IAAI,CAAC;SACf;QAAC,OAAO,KAAK,EAAE,GAAG;QACnB,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ;AAhDD,4BAgDC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/utils.js b/lib.commonjs/wallet/utils.js new file mode 100644 index 000000000..ce721d754 --- /dev/null +++ b/lib.commonjs/wallet/utils.js @@ -0,0 +1,145 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uuidV4 = exports.spelunk = exports.getPassword = exports.zpad = exports.looseArrayify = void 0; +const index_js_1 = require("../utils/index.js"); +function looseArrayify(hexString) { + if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') { + hexString = '0x' + hexString; + } + return index_js_1.logger.getBytesCopy(hexString); +} +exports.looseArrayify = looseArrayify; +function zpad(value, length) { + value = String(value); + while (value.length < length) { + value = '0' + value; + } + return value; +} +exports.zpad = zpad; +function getPassword(password) { + if (typeof (password) === 'string') { + return (0, index_js_1.toUtf8Bytes)(password, "NFKC"); + } + return index_js_1.logger.getBytesCopy(password); +} +exports.getPassword = getPassword; +function spelunk(object, _path) { + const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); + if (match == null) { + return index_js_1.logger.throwArgumentError("invalid path", "path", _path); + } + const path = match[1]; + const type = match[3]; + const reqd = (match[4] === "!"); + let cur = object; + for (const comp of path.toLowerCase().split('.')) { + // Search for a child object with a case-insensitive matching key + if (Array.isArray(cur)) { + if (!comp.match(/^[0-9]+$/)) { + break; + } + cur = cur[parseInt(comp)]; + } + else if (typeof (cur) === "object") { + let found = null; + for (const key in cur) { + if (key.toLowerCase() === comp) { + found = cur[key]; + break; + } + } + cur = found; + } + else { + cur = null; + } + if (cur == null) { + break; + } + } + if (reqd && cur == null) { + index_js_1.logger.throwArgumentError("missing required value", "path", path); + } + if (type && cur != null) { + if (type === "int") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9]+$/)) { + return parseInt(cur); + } + else if (Number.isSafeInteger(cur)) { + return cur; + } + } + if (type === "number") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9.]*$/)) { + return parseFloat(cur); + } + } + if (type === "data") { + if (typeof (cur) === "string") { + return looseArrayify(cur); + } + } + if (type === "array" && Array.isArray(cur)) { + return cur; + } + if (type === typeof (cur)) { + return cur; + } + index_js_1.logger.throwArgumentError(`wrong type found for ${type} `, "path", path); + } + return cur; +} +exports.spelunk = spelunk; +/* +export function follow(object: any, path: string): null | string { + let currentChild = object; + + for (const comp of path.toLowerCase().split('/')) { + + // Search for a child object with a case-insensitive matching key + let matchingChild = null; + for (const key in currentChild) { + if (key.toLowerCase() === comp) { + matchingChild = currentChild[key]; + break; + } + } + + if (matchingChild === null) { return null; } + + currentChild = matchingChild; + } + + return currentChild; +} + +// "path/to/something:type!" +export function followRequired(data: any, path: string): string { + const value = follow(data, path); + if (value != null) { return value; } + return logger.throwArgumentError("invalid value", `data:${ path }`, + JSON.stringify(data)); +} +*/ +// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4) +function uuidV4(randomBytes) { + const bytes = index_js_1.logger.getBytes(randomBytes, "randomBytes"); + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + bytes[6] = (bytes[6] & 0x0f) | 0x40; + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const value = (0, index_js_1.hexlify)(bytes); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34), + ].join("-"); +} +exports.uuidV4 = uuidV4; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/utils.js.map b/lib.commonjs/wallet/utils.js.map new file mode 100644 index 000000000..6346a518b --- /dev/null +++ b/lib.commonjs/wallet/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src.ts/wallet/utils.ts"],"names":[],"mappings":";;;AAAA,gDAAiE;AAKjE,SAAgB,aAAa,CAAC,SAAiB;IAC3C,IAAI,OAAM,CAAC,SAAS,CAAC,KAAK,QAAQ,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE;QACtE,SAAS,GAAG,IAAI,GAAG,SAAS,CAAC;KAChC;IACD,OAAO,iBAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AAC1C,CAAC;AALD,sCAKC;AAED,SAAgB,IAAI,CAAC,KAAsB,EAAE,MAAc;IACvD,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,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I,KAAK,OAAM,CAAC,GAAG,CAAC,EAAE;YAAE,OAAO,GAAG,CAAC;SAAE;QAEzC,iBAAM,CAAC,kBAAkB,CAAC,wBAAyB,IAAK,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;KAC9E;IAED,OAAO,GAAG,CAAC;AACf,CAAC;AAjED,0BAiEC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8BE;AACF,0DAA0D;AAC1D,SAAgB,MAAM,CAAC,WAAsB;IACzC,MAAM,KAAK,GAAG,iBAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IAE1D,kBAAkB;IAClB,wCAAwC;IACxC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAEpC,cAAc;IACd,uCAAuC;IACvC,uCAAuC;IACvC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAEpC,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;IAE7B,OAAO;QACJ,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;QACtB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QACvB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QACvB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QACvB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;KACzB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChB,CAAC;AArBD,wBAqBC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/wallet.js b/lib.commonjs/wallet/wallet.js new file mode 100644 index 000000000..2ca75d3d9 --- /dev/null +++ b/lib.commonjs/wallet/wallet.js @@ -0,0 +1,169 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Wallet = void 0; +const index_js_1 = require("../crypto/index.js"); +const index_js_2 = require("../transaction/index.js"); +const index_js_3 = require("../utils/index.js"); +const base_wallet_js_1 = require("./base-wallet.js"); +const hdwallet_js_1 = require("./hdwallet.js"); +const json_crowdsale_js_1 = require("./json-crowdsale.js"); +const json_keystore_js_1 = require("./json-keystore.js"); +const mnemonic_js_1 = require("./mnemonic.js"); +function tryWallet(value) { + try { + if (!value || !value.signingKey) { + return null; + } + const key = trySigningKey(value.signingKey); + if (key == null || (0, index_js_2.computeAddress)(key.publicKey) !== value.address) { + return null; + } + if (value.mnemonic) { + const wallet = hdwallet_js_1.HDNodeWallet.fromMnemonic(value.mnemonic); + if (wallet.privateKey !== key.privateKey) { + return null; + } + } + return value; + } + catch (e) { + console.log(e); + } + return null; +} +// Try using value as mnemonic to derive the defaultPath HDodeWallet +function tryMnemonic(value) { + try { + if (value == null || typeof (value.phrase) !== "string" || + typeof (value.password) !== "string" || + value.wordlist == null) { + return null; + } + return hdwallet_js_1.HDNodeWallet.fromPhrase(value.phrase, value.password, null, value.wordlist); + } + catch (error) { + console.log(error); + } + return null; +} +function trySigningKey(value) { + try { + if (!value || !(0, index_js_3.isHexString)(value.privateKey, 32)) { + return null; + } + const key = value.privateKey; + if (index_js_1.SigningKey.computePublicKey(key) !== value.publicKey) { + return null; + } + return new index_js_1.SigningKey(key); + } + catch (e) { + console.log(e); + } + return null; +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +class Wallet extends base_wallet_js_1.BaseWallet { + #mnemonic; + constructor(key, provider) { + let signingKey = null; + let mnemonic = null; + // A normal private key + if (typeof (key) === "string") { + signingKey = new index_js_1.SigningKey(key); + } + // Try Wallet + if (signingKey == null) { + const wallet = tryWallet(key); + if (wallet) { + signingKey = wallet.signingKey; + mnemonic = wallet.mnemonic || null; + } + } + // Try Mnemonic, with the defaultPath wallet + if (signingKey == null) { + const wallet = tryMnemonic(key); + if (wallet) { + signingKey = wallet.signingKey; + mnemonic = wallet.mnemonic || null; + } + } + // A signing key + if (signingKey == null) { + signingKey = trySigningKey(key); + } + if (signingKey == null) { + index_js_3.logger.throwArgumentError("invalid key", "key", "[ REDACTED ]"); + } + super(signingKey, provider); + this.#mnemonic = mnemonic; + } + // Store this in a getter to reduce visibility in console.log + get mnemonic() { return this.#mnemonic; } + connect(provider) { + return new Wallet(this, provider); + } + async encrypt(password, options, progressCallback) { + throw new Error("TODO"); + } + encryptSync(password, options) { + throw new Error("TODO"); + } + static async fromEncryptedJson(json, password, progress) { + let account = null; + if ((0, json_keystore_js_1.isKeystoreJson)(json)) { + account = await (0, json_keystore_js_1.decryptKeystoreJson)(json, password, progress); + } + else if ((0, json_crowdsale_js_1.isCrowdsaleJson)(json)) { + if (progress) { + progress(0); + await stall(0); + } + account = (0, json_crowdsale_js_1.decryptCrowdsaleJson)(json, password); + if (progress) { + progress(1); + await stall(0); + } + } + else { + return index_js_3.logger.throwArgumentError("invalid JSON wallet", "json", "[ REDACTED ]"); + } + const wallet = new Wallet(account.privateKey); + if (wallet.address !== account.address) { + index_js_3.logger.throwArgumentError("address/privateKey mismatch", "json", "[ REDACTED ]"); + } + // @TODO: mnemonic + return wallet; + } + static fromEncryptedJsonSync(json, password) { + let account = null; + if ((0, json_keystore_js_1.isKeystoreJson)(json)) { + account = (0, json_keystore_js_1.decryptKeystoreJsonSync)(json, password); + } + else if ((0, json_crowdsale_js_1.isCrowdsaleJson)(json)) { + account = (0, json_crowdsale_js_1.decryptCrowdsaleJson)(json, password); + } + else { + return index_js_3.logger.throwArgumentError("invalid JSON wallet", "json", "[ REDACTED ]"); + } + const wallet = new Wallet(account.privateKey); + if (wallet.address !== account.address) { + index_js_3.logger.throwArgumentError("address/privateKey mismatch", "json", "[ REDACTED ]"); + } + // @TODO: mnemonic + return wallet; + } + static createRandom(provider, password, wordlist) { + return new Wallet(mnemonic_js_1.Mnemonic.fromEntropy((0, index_js_1.randomBytes)(16), password, wordlist), provider); + } + static fromMnemonic(mnemonic, provider) { + return new Wallet(mnemonic, provider); + } + static fromPhrase(phrase, provider, password = "", wordlist) { + return new Wallet(mnemonic_js_1.Mnemonic.fromPhrase(phrase, password, wordlist), provider); + } +} +exports.Wallet = Wallet; +//# sourceMappingURL=wallet.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/wallet.js.map b/lib.commonjs/wallet/wallet.js.map new file mode 100644 index 000000000..58ffc212f --- /dev/null +++ b/lib.commonjs/wallet/wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wallet.js","sourceRoot":"","sources":["../../src.ts/wallet/wallet.ts"],"names":[],"mappings":";;;AAAA,iDAA6D;AAC7D,sDAAyD;AACzD,gDAAwD;AAExD,qDAA8C;AAC9C,+CAA6C;AAC7C,2DAA6E;AAC7E,yDAE4B;AAC5B,+CAAyC;AAUzC,SAAS,SAAS,CAAC,KAAU;IACzB,IAAI;QACA,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QACjD,MAAM,GAAG,GAAG,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC5C,IAAI,GAAG,IAAI,IAAI,IAAI,IAAA,yBAAc,EAAC,GAAG,CAAC,SAAS,CAAC,KAAK,KAAK,CAAC,OAAO,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QACpF,IAAI,KAAK,CAAC,QAAQ,EAAE;YAChB,MAAM,MAAM,GAAG,0BAAY,CAAC,YAAY,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YACzD,IAAI,MAAM,CAAC,UAAU,KAAK,GAAG,CAAC,UAAU,EAAE;gBAAE,OAAO,IAAI,CAAC;aAAE;SAC7D;QACD,OAAO,KAAK,CAAC;KAChB;IAAC,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;KAAE;IAC/B,OAAO,IAAI,CAAC;A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,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;IACjF,CAAC;CACJ;AAzGD,wBAyGC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/bit-reader.js b/lib.commonjs/wordlists/bit-reader.js new file mode 100644 index 000000000..17d4de935 --- /dev/null +++ b/lib.commonjs/wordlists/bit-reader.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeBits = void 0; +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +function decodeBits(width, data) { + const maxValue = (1 << width) - 1; + const result = []; + let accum = 0, bits = 0, flood = 0; + for (let i = 0; i < data.length; i++) { + // Accumulate 6 bits of data + accum = ((accum << 6) | Base64.indexOf(data[i])); + bits += 6; + // While we have enough for a word... + while (bits >= width) { + // ...read the word + const value = (accum >> (bits - width)); + accum &= (1 << (bits - width)) - 1; + bits -= width; + // A value of 0 indicates we exceeded maxValue, it + // floods over into the next value + if (value === 0) { + flood += maxValue; + } + else { + result.push(value + flood); + flood = 0; + } + } + } + return result; +} +exports.decodeBits = decodeBits; +//# sourceMappingURL=bit-reader.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/bit-reader.js.map b/lib.commonjs/wordlists/bit-reader.js.map new file mode 100644 index 000000000..e8c4d26a1 --- /dev/null +++ b/lib.commonjs/wordlists/bit-reader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bit-reader.js","sourceRoot":"","sources":["../../src.ts/wordlists/bit-reader.ts"],"names":[],"mappings":";;;AAAA,MAAM,MAAM,GAAG,kEAAkE,CAAC;AAElF,SAAgB,UAAU,CAAC,KAAa,EAAE,IAAY;IAClD,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,MAAM,GAAkB,EAAG,CAAC;IAClC,IAAI,KAAK,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;IACnC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAElC,4BAA4B;QAC5B,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACjD,IAAI,IAAI,CAAC,CAAC;QAEV,qCAAqC;QACrC,OAAO,IAAI,IAAI,KAAK,EAAE;YAClB,mBAAmB;YACnB,MAAM,KAAK,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC;YACxC,KAAK,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC;YACnC,IAAI,IAAI,KAAK,CAAC;YAEd,kDAAkD;YAClD,kCAAkC;YAClC,IAAI,KAAK,KAAK,CAAC,EAAE;gBACb,KAAK,IAAI,QAAQ,CAAC;aACrB;iBAAM;gBACH,MAAM,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC;gBAC3B,KAAK,GAAG,CAAC,CAAC;aACb;SACJ;KACJ;IAED,OAAO,MAAM,CAAC;AAClB,CAAC;AA7BD,gCA6BC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/decode-owl.js b/lib.commonjs/wordlists/decode-owl.js new file mode 100644 index 000000000..83301a797 --- /dev/null +++ b/lib.commonjs/wordlists/decode-owl.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeOwl = exports.decode = void 0; +const logger_js_1 = require("../utils/logger.js"); +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words, sep) { + let initial = 97; + return words.reduce((accum, word) => { + if (word === sep) { + initial++; + } + else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } + else { + initial = 97; + accum.push(word); + } + return accum; + }, []); +} +function decode(data, subs) { + // Replace all the substitutions with their expanded form + for (let i = subsChrs.length - 1; i >= 0; i--) { + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + } + // Get all tle clumps; each suffix, first-increment and second-increment + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { + if (semi) { + for (let i = parseInt(semi); i >= 0; i--) { + clumps.push(";"); + } + } + else { + clumps.push(item.toLowerCase()); + } + return ""; + }); + /* c8 ignore start */ + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); + } + /* c8 ignore stop */ + return unfold(unfold(clumps, ";"), ":"); +} +exports.decode = decode; +function decodeOwl(data) { + (0, logger_js_1.assertArgument)(data[0] === "0", "unsupported auwl data", "data", data); + return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); +} +exports.decodeOwl = decodeOwl; +//# sourceMappingURL=decode-owl.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/decode-owl.js.map b/lib.commonjs/wordlists/decode-owl.js.map new file mode 100644 index 000000000..2e33778ba --- /dev/null +++ b/lib.commonjs/wordlists/decode-owl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-owl.js","sourceRoot":"","sources":["../../src.ts/wordlists/decode-owl.ts"],"names":[],"mappings":";;;AAAA,kDAAoD;AAGpD,MAAM,QAAQ,GAAG,+BAA+B,CAAC;AACjD,MAAM,IAAI,GAAG,WAAW,CAAC;AAEzB,SAAS,MAAM,CAAC,KAAoB,EAAE,GAAW;IAC7C,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;QAChC,IAAI,IAAI,KAAK,GAAG,EAAE;YACd,OAAO,EAAE,CAAC;SACb;aAAM,IAAI,IAAI,CA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AAC,QAAQ,CAAE,EAAE,CAAC,CAAC;KAAE;IAC9E,oBAAoB;IAEpB,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAtBD,wBAsBC;AAED,SAAgB,SAAS,CAAC,IAAY;IAClC,IAAA,0BAAc,EAAC,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,uBAAuB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAEvE,OAAO,MAAM,CACT,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EACvC,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AACpD,CAAC;AAND,8BAMC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/decode-owla.js b/lib.commonjs/wordlists/decode-owla.js new file mode 100644 index 000000000..e5b91852d --- /dev/null +++ b/lib.commonjs/wordlists/decode-owla.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decodeOwlA = void 0; +const logger_js_1 = require("../utils/logger.js"); +const bit_reader_js_1 = require("./bit-reader.js"); +const decode_owl_js_1 = require("./decode-owl.js"); +function decodeOwlA(data, accents) { + let words = (0, decode_owl_js_1.decodeOwl)(data).join(","); + // Inject the accents + accents.split(/,/g).forEach((accent) => { + const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); + (0, logger_js_1.assertArgument)(match !== null, "internal error parsing accents", "accents", accents); + let posOffset = 0; + const positions = (0, bit_reader_js_1.decodeBits)(parseInt(match[3]), match[4]); + const charCode = parseInt(match[2]); + const regex = new RegExp(`([${match[1]}])`, "g"); + words = words.replace(regex, (all, letter) => { + const rem = --positions[posOffset]; + if (rem === 0) { + letter = String.fromCharCode(letter.charCodeAt(0), charCode); + posOffset++; + } + return letter; + }); + }); + return words.split(","); +} +exports.decodeOwlA = decodeOwlA; +//# sourceMappingURL=decode-owla.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/decode-owla.js.map b/lib.commonjs/wordlists/decode-owla.js.map new file mode 100644 index 000000000..d54ff2977 --- /dev/null +++ b/lib.commonjs/wordlists/decode-owla.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-owla.js","sourceRoot":"","sources":["../../src.ts/wordlists/decode-owla.ts"],"names":[],"mappings":";;;AAAA,kDAAoD;AAEpD,mDAA6C;AAC7C,mDAA4C;AAE5C,SAAgB,UAAU,CAAC,IAAY,EAAE,OAAe;IACpD,IAAI,KAAK,GAAG,IAAA,yBAAS,EAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEtC,qBAAqB;IACrB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QAEnC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAC5D,IAAA,0BAAc,EAAC,KAAK,KAAK,IAAI,EAAE,gCAAgC,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAErF,IAAI,SAAS,GAAG,CAAC,CAAC;QAClB,MAAM,SAAS,GAAG,IAAA,0BAAU,EAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,KAAM,KAAK,CAAC,CAAC,CAAE,IAAI,EAAE,GAAG,CAAC,CAAC;QACnD,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACzC,MAAM,GAAG,GAAG,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;YACnC,IAAI,GAAG,KAAK,CAAC,EAAE;gBACX,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;gBAC7D,SAAS,EAAE,CAAC;aACf;YACD,OAAO,MAAM,CAAC;QAClB,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC;AAxBD,gCAwBC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/generation/encode-latin.js b/lib.commonjs/wordlists/generation/encode-latin.js new file mode 100644 index 000000000..512beed7d --- /dev/null +++ b/lib.commonjs/wordlists/generation/encode-latin.js @@ -0,0 +1,353 @@ +"use strict"; +// OWL Data Format +// +// The Official WordList data format exported by this encoder +// encodes sorted latin-1 words (letters only) based on the +// fact that sorted words have prefixes with substantial +// overlap. +// +// For example, the words: +// [ Another, Apple, Apricot, Bread ] +// could be folded once with a single special character, such +// as ":" to yield: +// [ nother, pple, pricot, :, read ]. +// The First letter has been removed, but can be inferred by +// starting at A and incrementing to the next letter when ":" +// is encountered. +// +// The fold operation can be repeated for large sets as even within +// each folded set, there is substatial overlap in prefix. With the +// second special symbol ";", we get: +// [ ; x 13, other, :, ple, ricot, :, ; x 18, ead ] +// which can be further compressed by using numbers instead of the +// special character: +// [ 13, other, :, ple, ricot, :, 18, ead ] +// and to keep all values within a single byte, we only allow a +// maximum value of 10 (using 0 through 9 to represent 1 through 10), +// we get: +// [ 9, 2, other, :, ple, ricot, :, 9, 7, ead ] +// and we use camel-case to imply the bounrary, giving the final string: +// "92Other:PleRicot:97Ead" +// +// Once the entire latin-1 set has been collapsed, we use the remaining +// printable characters (except " and \, which require 2 bytes to represent +// in string) to substiture for the most common 2-letter pairs of letters +// in the string. +// +// OWLA Accent Format +// +// OWLA first removes all accents, and encodes that data using the OWL +// data format and encodes the accents as a base-64 series of 6-bit +// packed bits representing the distance from one followed letter to the +// next. +// +// For example, the acute accent in a given language may follow either +// a or e, in which case the follow-set is "ae". Each letter in the entire +// set is indexed, so the set of words with the accents: +// "thisA/ppleDoe/sNotMa/tterToMe/" +// " 1^ 2^ 3^ 4^ 5^ 6^ " <-- follow-set members, ALL a's and e's +// which gives the positions: +// [ 0, 2, 3, 4, 6 ] +// which then reduce to the distances +// [ 0, 2, 1, 1, 2 ] +// each of which fit into a 2-bit value, so this can be encoded as the +// base-64 encoded string: +// 00 10 01 01 10 = 001001 1010xx +// +// The base-64 set used has all number replaced with their +// shifted-counterparts to prevent comflicting with the numbers used in +// the fold operation to indicate the number of ";". +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeOwl = exports.extractAccents = exports.BitWriter = void 0; +const fs_1 = __importDefault(require("fs")); +const id_js_1 = require("../../hash/id.js"); +const decode_owl_js_1 = require("../decode-owl.js"); +const decode_owla_js_1 = require("../decode-owla.js"); +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z'`]*$/i; +function fold(words, sep) { + const output = []; + let initial = 97; + for (const word of words) { + if (word.match(Word)) { + while (initial < word.charCodeAt(0)) { + initial++; + output.push(sep); + } + output.push(word.substring(1)); + } + else { + initial = 97; + output.push(word); + } + } + return output; +} +function camelcase(words) { + return words.map((word) => { + if (word.match(Word)) { + return word[0].toUpperCase() + word.substring(1); + } + else { + return word; + } + }).join(""); +} +//let cc = 0, ce = 0; +/* +function getChar(c: string): string { + //if (c === "e") { ce++; } + if (c >= 'a' && c <= 'z') { return c; } + if (c.charCodeAt(1)) { + throw new Error(`bad char: "${ c }"`); + } + //cc++; + return ""; + if (c.charCodeAt(0) === 768) { return "`"; } + if (c.charCodeAt(0) === 769) { return "'"; } + if (c.charCodeAt(0) === 771) { return "~"; } + throw new Error(`Unsupported character: ${ c } (${ c.charCodeAt(0) }, ${ c.charCodeAt(1) })`); +} +function mangle(text: string): { word: string, special: string } { + const result: Array = [ ]; + for (let i = 0; i < text.length; i++) { + const c = getChar(text[i]); + result.push(c); + } + + const word = result.join(""); + if (word[1] >= 'a' && word[1] <= 'z') { return { word, special: " " }; } + return { word: word[0] + word.substring(2), special: word[1] }; +} +*/ +/* + Store: [ accent ][ targets ][ rle data; base64-tail ] + ` ae 3, 100 = (63, 37), 15 + ~ n 63, 64 = (63, 1), 27 +*/ +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +class BitWriter { + width; + #data; + #bitLength; + constructor(width) { + this.width = width; + this.#data = []; + this.#bitLength = 0; + } + write(value) { + const maxValue = ((1 << this.width) - 1); + while (value > maxValue) { + this.#data.push(0); + this.#bitLength += this.width; + value -= maxValue; + } + this.#data.push(value); + this.#bitLength += this.width; + } + get length() { + return 1 + Math.trunc((this.#bitLength + 5) / 6); + } + get data() { + let result = String(this.width); + let bits = 0; + let accum = 0; + const data = this.#data.slice(); + let bitMod = this.#bitLength % 6; + while (bitMod !== 0 && bitMod < 6) { + data.push(0); + bitMod += this.width; + } + for (const value of data) { + accum <<= this.width; + accum |= value; + bits += this.width; + if (bits < 6) { + continue; + } + result += Base64[accum >> (bits - 6)]; + bits -= 6; + accum &= ((1 << bits) - 1); + } + if (result.length !== this.length) { + throw new Error(`Hmm: ${this.length} ${result.length} ${result}`); + } + return result; + } +} +exports.BitWriter = BitWriter; +; +function sorted(text) { + const letters = text.split(""); + letters.sort(); + return letters.join(""); +} +// if (c.charCodeAt(0) === 768) { return "`"; } +// if (c.charCodeAt(0) === 769) { return "'"; } +// if (c.charCodeAt(0) === 771) { return "~"; } +function extractAccents(words) { + // Build a list that maps accents to the letters it can follow + const followsMap = new Map(); + for (const word of words) { + for (let i = 0; i < word.length; i++) { + const c = word[i]; + if (c >= 'a' && c <= 'z') { + continue; + } + // Make sure this positions and codepoint make sense + if (c.charCodeAt(1)) { + throw new Error(`unsupported codepoint: "${c}"`); + } + if (i === 0) { + throw new Error(`unmatched accent: ${c}`); + } + const ac = c.charCodeAt(0), lastLetter = word[i - 1]; + ; + const follows = (followsMap.get(ac) || ""); + if (follows.indexOf(lastLetter) === -1) { + followsMap.set(ac, sorted(follows + lastLetter)); + } + } + } + // Build the positions of each follow-set for those accents + const positionsMap = new Map(); + for (const [accent, follows] of followsMap) { + let count = 0; + for (const word of words) { + for (let i = 0; i < word.length; i++) { + const c = word[i], ac = c.charCodeAt(0); + if (follows.indexOf(c) >= 0) { + count++; + } + if (ac === accent) { + const pos = positionsMap.get(ac) || []; + pos.push(count); + positionsMap.set(ac, pos); + } + } + } + } + const accents = []; + for (const [accent, follows] of followsMap) { + let last = -1; + const positions = (positionsMap.get(accent) || []).map((value, index) => { + const delta = value - last; + last = value; + if (index === 0) { + return value; + } + return delta; + }); + // Find the best encoding of the position data + let positionData = ""; + for (let i = 2; i < 7; i++) { + const bitWriter = new BitWriter(i); + for (const p of positions) { + bitWriter.write(p); + } + if (positionData === "" || bitWriter.length < positionData.length) { + positionData = bitWriter.data; + } + } + const positionsLength = positions.length; + const positionDataLength = positionData.length; + accents.push({ accent, follows, positions, positionsLength, positionData, positionDataLength }); + } + words = words.map((word) => { + let result = ""; + for (let i = 0; i < word.length; i++) { + const c = word[i]; + if (c >= 'a' && c <= 'z') { + result += c; + } + } + return result; + }); + return { accents, words }; +} +exports.extractAccents = extractAccents; +// Encode Official WordList +function encodeOwl(words) { + // Fold the sorted words by indicating delta for the first 2 letters + let data = camelcase(fold(fold(words, ":"), ";")); + // Replace semicolons with counts (e.g. ";;;" with "3") + data = data.replace(/(;+)/g, (all, semis) => { + let result = ""; + while (semis.length) { + let count = semis.length; + if (count > 10) { + count = 10; + } + result += String(count - 1); + semis = semis.substring(count); + } + return result; + }); + // Finds the best option for a shortcut replacement using the + // unused ascii7 characters + function findBest() { + const tally = {}; + const l = 2; + for (let i = l; i < data.length; i++) { + const key = data.substring(i - l, i); + tally[key] = (tally[key] || 0) + 1; + } + const sorted = Object.keys(tally).map((text) => { + return { text, count: tally[text], save: (tally[text] * (text.length - 1)) }; + }); + sorted.sort((a, b) => (b.save - a.save)); + return sorted[0].text; + } + // Make substitutions + let subs = ""; + for (let i = 0; i < subsChrs.length; i++) { + const n = subsChrs[i], o = findBest(); + subs += o; + data = data.split(o).join(n); + } + return { data, subs }; +} +exports.encodeOwl = encodeOwl; +// Returns either: +// - OWL data for accent-free latin-1: { data, accentds: "" } +// - OWLA data for accented latin-1: { data, accents } +function encodeWords(_words) { + const { accents, words } = extractAccents(_words); + const { data, subs } = encodeOwl(words); + const accentData = accents.map(({ accent, follows, positionData }) => { + return `${follows}${accent}${positionData}`; + }).join(","); + return { + data: `0${subs}${data}`, + accents: accentData + }; +} +// CLI +const content = fs_1.default.readFileSync(process.argv[2]).toString(); +const words = content.split("\n").filter(Boolean); +const { data, accents } = encodeWords(words); +if (accents) { + const rec = (0, decode_owla_js_1.decodeOwlA)(data, accents); + console.log("DATA: ", JSON.stringify(data)); + console.log("ACCENTS: ", JSON.stringify(accents)); + console.log("LENGTH: ", data.length); + console.log("CHECKSUM: ", (0, id_js_1.id)(content)); + console.log("RATIO: ", Math.trunc(100 * data.length / content.length) + "%"); + if (rec.join("\n") !== words.join("\n")) { + throw new Error("no match!"); + } +} +else { + const rec = (0, decode_owl_js_1.decodeOwl)(data); + console.log("DATA: ", JSON.stringify(data)); + console.log("LENGTH: ", data.length); + console.log("CHECKSUM: ", (0, id_js_1.id)(content)); + console.log("RATIO: ", Math.trunc(100 * data.length / content.length) + "%"); + if (rec.join("\n") !== words.join("\n")) { + throw new Error("no match!"); + } +} +//# sourceMappingURL=encode-latin.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/generation/encode-latin.js.map b/lib.commonjs/wordlists/generation/encode-latin.js.map new file mode 100644 index 000000000..55b0910ea --- /dev/null +++ b/lib.commonjs/wordlists/generation/encode-latin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-latin.js","sourceRoot":"","sources":["../../../src.ts/wordlists/generation/encode-latin.ts"],"names":[],"mappings":";AACA,kBAAkB;AAClB,EAAE;AACF,6DAA6D;AAC7D,2DAA2D;AAC3D,wDAAwD;AACxD,WAAW;AACX,EAAE;AACF,0BAA0B;AAC1B,uCAAuC;AACvC,6DAA6D;AAC7D,mBAAmB;AACnB,uCAAuC;AACvC,4DAA4D;AAC5D,6DAA6D;AAC7D,kBAAkB;AAClB,EAAE;AACF,mEAAmE;AACnE,mEAAmE;AACnE,qCAAqC;AACrC,qDAAqD;AACrD,kEAAkE;AAClE,qBAAqB;AACrB,6CAA6C;AAC7C,+DAA+D;AAC/D,qEAAqE;AACrE,UAAU;AACV,iDAAiD;AACjD,wEAAwE;AACxE,6BAA6B;AAC7B,EAAE;AACF,uEAAuE;AACvE,2EAA2E;AAC3E,yEAAyE;AACzE,iBAAiB;AACjB,EAAE;AACF,qBAAqB;AACrB,EAAE;AACF,sEAAsE;AACtE,mEAAmE;AACnE,wEAAwE;AACxE,QAAQ;AACR,EAAE;AACF,sEAAsE;AACtE,0EAA0E;AAC1E,wDAAwD;AACxD,qCAAqC;AACrC,6EAA6E;AAC7E,6BAA6B;AAC7B,sBAAsB;AACtB,qCAAqC;AACrC,sBAAsB;AACtB,sEAAsE;AACtE,0BAA0B;AAC1B,qCAAqC;AACrC,EAAE;AACF,0DAA0D;AAC1D,uEAAuE;AACvE,oDAAoD;;;;;;AAEpD,4CAAoB;AAEpB,4CAAsC;AAEtC,oDAA6C;AAC7C,sDAA+C;AAE/C,MAAM,QAAQ,GAAG,+BAA+B,CAAC;AAEjD,MAAM,IAAI,GAAG,aAAa,CAAC;AAE3B,SAAS,IAAI,CAAC,KAAoB,EAAE,GAAW;IAC3C,MAAM,MAAM,GAAkB,EAAG,CAAC;IAElC,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,IAAI,IAAI,CAAC,K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ChF,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;KAAE;CAC7E;KAAM;IACH,MAAM,GAAG,GAAG,IAAA,yBAAS,EAAC,IAAI,CAAC,CAAC;IAC5B,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAA,UAAE,EAAC,OAAO,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC;IAChF,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;KAAE;CAC7E"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/index.js b/lib.commonjs/wordlists/index.js new file mode 100644 index 000000000..0f2b9dd3c --- /dev/null +++ b/lib.commonjs/wordlists/index.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WordlistOwlA = exports.WordlistOwl = exports.wordlists = exports.LangEn = exports.langEn = exports.Wordlist = void 0; +var wordlist_js_1 = require("./wordlist.js"); +Object.defineProperty(exports, "Wordlist", { enumerable: true, get: function () { return wordlist_js_1.Wordlist; } }); +var lang_en_js_1 = require("./lang-en.js"); +Object.defineProperty(exports, "langEn", { enumerable: true, get: function () { return lang_en_js_1.langEn; } }); +Object.defineProperty(exports, "LangEn", { enumerable: true, get: function () { return lang_en_js_1.LangEn; } }); +var wordlists_js_1 = require("./wordlists.js"); +Object.defineProperty(exports, "wordlists", { enumerable: true, get: function () { return wordlists_js_1.wordlists; } }); +var wordlist_owl_js_1 = require("./wordlist-owl.js"); +Object.defineProperty(exports, "WordlistOwl", { enumerable: true, get: function () { return wordlist_owl_js_1.WordlistOwl; } }); +var wordlist_owla_js_1 = require("./wordlist-owla.js"); +Object.defineProperty(exports, "WordlistOwlA", { enumerable: true, get: function () { return wordlist_owla_js_1.WordlistOwlA; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/index.js.map b/lib.commonjs/wordlists/index.js.map new file mode 100644 index 000000000..5c938a034 --- /dev/null +++ b/lib.commonjs/wordlists/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/wordlists/index.ts"],"names":[],"mappings":";;;AACA,6CAAyC;AAAhC,uGAAA,QAAQ,OAAA;AACjB,2CAA8C;AAArC,oGAAA,MAAM,OAAA;AAAE,oGAAA,MAAM,OAAA;AACvB,+CAA2C;AAAlC,yGAAA,SAAS,OAAA;AAElB,qDAAgD;AAAvC,8GAAA,WAAW,OAAA;AACpB,uDAAkD;AAAzC,gHAAA,YAAY,OAAA"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-cz.js b/lib.commonjs/wordlists/lang-cz.js new file mode 100644 index 000000000..22d25019a --- /dev/null +++ b/lib.commonjs/wordlists/lang-cz.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.langCz = exports.LangCz = void 0; +const wordlist_owl_js_1 = require("./wordlist-owl.js"); +const words = "0itatkastcenaovo$taouleraeki&chor*teci%enbalodaeladet'!Chn=0Di#%E%^1Resa2Rese3CeT'#0EjKohol0Pu)%0A&sDul#Ekdo)Ke)Ti#Ul|3}aOgan%0FaltI$@tPi,%TmaTronom0LasL{i#Ol0Tobus4Yl:B#}R'?TaUb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al RavaR( Rud#Rvu1A^An C`]N (NoOv&Y/l Zav(1I/aR! 0B'.Br0Ed~EnkuEs_aOnR!Uk'odYk"; +const checksum = "0x25f44555f4af25b51a711136e1c7d6e50ce9f8917d39d6b1f076b2bb4d2fac1a"; +class LangCz extends wordlist_owl_js_1.WordlistOwl { + constructor() { super("cz", words, checksum); } +} +exports.LangCz = LangCz; +exports.langCz = new LangCz(); +//# sourceMappingURL=lang-cz.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-cz.js.map b/lib.commonjs/wordlists/lang-cz.js.map new file mode 100644 index 000000000..502ce8e2f --- /dev/null +++ b/lib.commonjs/wordlists/lang-cz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-cz.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-cz.ts"],"names":[],"mappings":";;;AAAA,uDAAgD;AAEhD,MAAM,KAAK,GAAG,q9NAAq9N,CAAC;AACp+N,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AAEtF,MAAa,MAAO,SAAQ,6BAAW;IACnC,gBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClD;AAFD,wBAEC;AAEY,QAAA,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-en.js b/lib.commonjs/wordlists/lang-en.js new file mode 100644 index 000000000..f891a34b3 --- /dev/null +++ b/lib.commonjs/wordlists/lang-en.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.langEn = exports.LangEn = void 0; +const wordlist_owl_js_1 = require("./wordlist-owl.js"); +const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3En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ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; +const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; +class LangEn extends wordlist_owl_js_1.WordlistOwl { + constructor() { super("en", words, checksum); } +} +exports.LangEn = LangEn; +exports.langEn = new LangEn(); +//# sourceMappingURL=lang-en.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-en.js.map b/lib.commonjs/wordlists/lang-en.js.map new file mode 100644 index 000000000..c61b0a008 --- /dev/null +++ b/lib.commonjs/wordlists/lang-en.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-en.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-en.ts"],"names":[],"mappings":";;;AAAA,uDAAgD;AAEhD,MAAM,KAAK,GAAG,u3LAAu3L,CAAC;AACt4L,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AAEtF,MAAa,MAAO,SAAQ,6BAAW;IACnC,gBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClD;AAFD,wBAEC;AAEY,QAAA,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-es.js b/lib.commonjs/wordlists/lang-es.js new file mode 100644 index 000000000..ac865e58c --- /dev/null +++ b/lib.commonjs/wordlists/lang-es.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.langEs = exports.LangEs = void 0; +const wordlist_owla_js_1 = require("./wordlist-owla.js"); +const words = "0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_L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aIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! b) { + return 1; + } + return 0; + } + // Load all the words + for (let length = 3; length <= 9; length++) { + const d = data[length - 3]; + for (let offset = 0; offset < d.length; offset += length) { + const word = []; + for (let i = 0; i < length; i++) { + const k = mapping.indexOf(d[offset + i]); + word.push(227); + word.push((k & 0x40) ? 130 : 129); + word.push((k & 0x3f) + 128); + } + wordlist.push(toString(word)); + } + } + wordlist.sort(sortJapanese); + // For some reason kyoku and kiyoku are flipped in node (!!). + // The order SHOULD be: + // - kyoku + // - kiyoku + // This should ignore "if", but that doesn't work here?? + /* c8 ignore start */ + if (hex(wordlist[442]) === KiYoKu && hex(wordlist[443]) === KyoKu) { + const tmp = wordlist[442]; + wordlist[442] = wordlist[443]; + wordlist[443] = tmp; + } + /* c8 ignore stop */ + // Verify the computed list matches the official list + /* istanbul ignore if */ + const checksum = (0, id_js_1.id)(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== "0xcb36b09e6baa935787fd762ce65e80b0c6a8dabdfbc3a7f86ac0e2c4fd111600") { + throw new Error("BIP39 Wordlist for ja (Japanese) FAILED"); + } + /* c8 ignore stop */ + _wordlist = wordlist; + return wordlist; +} +class LangJa extends wordlist_js_1.Wordlist { + constructor() { super("ja"); } + getWord(index) { + const words = loadWords(); + if (index < 0 || index >= words.length) { + index_js_1.logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords().indexOf(word); + } + split(mnemonic) { + //logger.assertNormalize(); + return mnemonic.split(/(?:\u3000| )+/g); + } + join(words) { + return words.join("\u3000"); + } +} +exports.langJa = new LangJa(); +//# sourceMappingURL=lang-ja.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-ja.js.map b/lib.commonjs/wordlists/lang-ja.js.map new file mode 100644 index 000000000..8e2ac29c4 --- /dev/null +++ b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C,CAAC;IAChC,CAAC;CACJ;AAEY,QAAA,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-ko.js b/lib.commonjs/wordlists/lang-ko.js new file mode 100644 index 000000000..44d44b11c --- /dev/null +++ b/lib.commonjs/wordlists/lang-ko.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.langKo = void 0; +const id_js_1 = require("../hash/id.js"); +const index_js_1 = require("../utils/index.js"); +const wordlist_js_1 = require("./wordlist.js"); +const data = [ + "OYAa", + "ATAZoATBl3ATCTrATCl8ATDloATGg3ATHT8ATJT8ATJl3ATLlvATLn4ATMT8ATMX8ATMboATMgoAToLbAToMTATrHgATvHnAT3AnAT3JbAT3MTAT8DbAT8JTAT8LmAT8MYAT8MbAT#LnAUHT8AUHZvAUJXrAUJX8AULnrAXJnvAXLUoAXLgvAXMn6AXRg3AXrMbAX3JTAX3QbAYLn3AZLgvAZrSUAZvAcAZ8AaAZ8AbAZ8AnAZ8HnAZ8LgAZ8MYAZ8MgAZ8OnAaAboAaDTrAaFTrAaJTrAaJboAaLVoAaMXvAaOl8AaSeoAbAUoAbAg8AbAl4AbGnrAbMT8AbMXrAbMn4AbQb8AbSV8AbvRlAb8AUAb8AnAb8HgAb8JTAb8NTAb8RbAcGboAcLnvAcMT8AcMX8AcSToAcrAaAcrFnAc8AbAc8MgAfGgrAfHboAfJnvAfLV8AfLkoAfMT8AfMnoAfQb8AfScrAfSgrAgAZ8AgFl3AgGX8AgHZvAgHgrAgJXoAgJX8AgJboAgLZoAgLn4AgOX8AgoATAgoAnAgoCUAgoJgAgoLXAgoMYAgoSeAgrDUAgrJTAhrFnAhrLjAhrQgAjAgoAjJnrAkMX8AkOnoAlCTvAlCV8AlClvAlFg4AlFl6AlFn3AloSnAlrAXAlrAfAlrFUAlrFbAlrGgAlrOXAlvKnAlvMTAl3AbAl3MnAnATrAnAcrAnCZ3AnCl8An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crMXoMg8SToAfMlvAXLg3MnFl3AnvOT3AnFl3OUoATHT8OU3RnLXrOXrOXrSnObPbvFn6Og8HgrSnOg8OX8DbPTvAgoJgPU3RYLnrPXrDnJZrPb8CTGgvPlrLTDlvPlvFUJnoQUvFXrQlQeMnoAl3QlrQlrSnRTFTrJUoSTDlLiLXSTFg6HT3STJgoMn4STrFTJTrSTrLZFl3ST4FnMXoSUrDlHUoScvHTvSnSfLkvMXo", + "AUoAcrMXoAZ8HboAg8AbOg6ATFgAg8AloMXoAl3AT8JTrAl8MX8MXoCT3SToJU8Cl8Db8MXoDT8HgrATrDboOT8MXoGTOTrATMnGT8LhrAZ8GnvFnGnQXHToGgvAcrHTvAXvLl3HbrAZoMXoHgBlFXLg3HgMnFXrSnHgrSb8JUoHn6HT8LgvITvATrJUoJUoLZrRnvJU8HT8Jb8JXvFX8QT8JXvLToJTrJYrQnGnQXJgrJnoATrJnoJU8ScvJnvMnvMXoLTCTLgrJXLTJlRTvQlLbRnJlQYvLbrMb8LnvLbvFn3RnoLdCVSTGZrLeSTvGXCnLg3MnoLn3MToLlrETvMT8SToAl3MbrDU6GTvMb8LX4LhrPlrLXGXCnSToLf8Rg3STrDb8LTrSTvLTHXMnSb3RYLnMnSgOg6ATFg", + "HUDlGnrQXrJTrHgLnrAcJYMb8DULc8LTvFgGnCk3Mg8JbAnLX4QYvFYHnMXrRUoJnGnvFnRlvFTJlQnoSTrBXHXrLYSUJgLfoMT8Se8DTrHbDb", + "AbDl8SToJU8An3RbAb8ST8DUSTrGnrAgoLbFU6Db8LTrMg8AaHT8Jb8ObDl8SToJU8Pb3RlvFYoJl" +]; +const codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"; +function getHangul(code) { + if (code >= 40) { + code = code + 168 - 40; + } + else if (code >= 19) { + code = code + 97 - 19; + } + return (0, index_js_1.toUtf8String)(new Uint8Array([225, (code >> 6) + 132, (code & 0x3f) + 128])); +} +let _wordlist = null; +function loadWords() { + if (_wordlist != null) { + return _wordlist; + } + const wordlist = []; + data.forEach((data, length) => { + length += 4; + for (let i = 0; i < data.length; i += length) { + let word = ""; + for (let j = 0; j < length; j++) { + word += getHangul(codes.indexOf(data[i + j])); + } + wordlist.push(word); + } + }); + wordlist.sort(); + // Verify the computed list matches the official list + /* istanbul ignore if */ + const checksum = (0, id_js_1.id)(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== "0xf9eddeace9c5d3da9c93cf7d3cd38f6a13ed3affb933259ae865714e8a3ae71a") { + throw new Error("BIP39 Wordlist for ko (Korean) FAILED"); + } + /* c8 ignore stop */ + _wordlist = wordlist; + return wordlist; +} +class LangKo extends wordlist_js_1.Wordlist { + constructor() { + super("ko"); + } + getWord(index) { + const words = loadWords(); + if (index < 0 || index >= words.length) { + index_js_1.logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords().indexOf(word); + } +} +exports.langKo = new LangKo(); +//# sourceMappingURL=lang-ko.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-ko.js.map b/lib.commonjs/wordlists/lang-ko.js.map new file mode 100644 index 000000000..c975aa4e3 --- /dev/null +++ b/lib.commonjs/wordlists/lang-ko.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-ko.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-ko.ts"],"names":[],"mappings":";;;AAAA,yCAAmC;AACnC,gDAAyD;AAEzD,+CAAyC;AAGzC,MAAM,IAAI,GAAG;IACT,MAAM;IACN,y5JAAy5J;IACz5J,8lIAA8lI;IAC9lI,i8BAAi8B;IACj8B,koCAAkoC;IACloC,yaAAya;IACza,gHAAgH;IAChH,+EAA+E;CAClF,CAAA;AAED,MAAM,KAAK,GAAG,wEAAwE,CAAA;AAEtF,SAAS,SAAS,CAAC,IAAY;IAC3B,IAAI,IAAI,IAAI,EAAE,EAAE;QACZ,IAAI,GAAG,IAAI,GAAG,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,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;KAC5D;IACD,oBAAoB;IAEpB,SAAS,GAAG,QAAQ,CAAC;IAErB,OAAO,QAAQ,CAAC;AACpB,CAAC;AAGD,MAAM,MAAO,SAAQ,sBAAQ;IACzB;QACI,KAAK,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC;IAED,OAAO,CAAC,KAAa;QACjB,MAAM,KAAK,GAAG,SAAS,EAAE,CAAC;QAC1B,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;YACpC,iBAAM,CAAC,kBAAkB,CAAC,uBAAwB,KAAM,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC/E;QACD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAED,YAAY,CAAC,IAAY;QACrB,OAAO,SAAS,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;CACJ;AAEY,QAAA,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-pt.js b/lib.commonjs/wordlists/lang-pt.js new file mode 100644 index 000000000..027233e0d --- /dev/null +++ b/lib.commonjs/wordlists/lang-pt.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.langPt = exports.LangPt = void 0; +const wordlist_owl_js_1 = require("./wordlist-owl.js"); +const words = "0arad!ototealirertainrasoent hoandoaR#riareha!aroele'oronul0Aca%AixoAl A%rDuz'El]Er$IsmoO$ Rum S-&T(i&TigoVo[=0F&.Il#P' S?S* So&/Sun$Tr&0Ac#Adu+Al/A[f E End(Er_EuIng'Ir?IvoOl{oRac Revi=RizU&Um0Di$rM-.R>o+TismoT|@Tu 0Ali An%Ar@Ent&Es,I?Is Ul,1Ila1Ar E=Ei%Ulejo:B BosaC&]uCh `C@GagemI+c>~/Se#S)n%Ta)Te=rTidaTomTuc Unil]3B(IjoIr^IsebolLd!eLezaLgaLisc Ndi$Ng&aNz(RimbauRl*d>_Sou_XigaZ(_3CoCu=En&Foc&Furc G|naLhe%Mest[Mo$rOlog@OmboOsf(aPol Rr-$Scoi$Sne$SpoSsex$TolaZ _2Ind#OcoOque 2A$BagemC#CejoChec]Ico.L^LetimL]LoMb{oNdeNecoNi)Rb~h>d>e&R+c]V*oXe?2AncoAsaAvezaEuIgaIl/Inc OaOchu+Onze O$Uxo2C]DismoF LeRacoScaS$Z*a:Bimb Rn{oRpe%R['>)zRv&/SacoScaSeb[S%loS~oT a)Tiv UleUs?U%l V&oV(na3BolaDil]G}]Lebr L~ Nou+N,N%ioRc Rr#R%'oRvejaTimV^2Aco)Al{aAm#Ap^ArmeAticeAveEfeEg^E'oEqueIco%If[In`oOc&/Ov(UmboU.Uva0CatrizCl}eD!eD['aEn%Gcui$Rurg@T 2A[zaE_Ic OneUbe2A=Ag'Ba@B($rBr C^El/Ent_E,Gum`oIb'IfaIo%L L{aLh(Lid'Lme@L}oLunaM<=Mb* M-.MitivaMov(MplexoMumNc]N=rNec.Nfu,Ng` Nhec(Njug Nsum'Nt+$Nvi%Op( P{oPi?PoQue%lRagemRdi&Rne)R}h>p|&R[ioR%joRuj>voSs-oS%laT}e%U_UveVilZ*]2A%+AvoEcheE=rEmeErEspoI^Im*&Io~oIseItic Os)UaUz{o2B+m SafioSbo.Sc<,S-/Sfi#Sgas%Sigu&SlizeSmam SovaSpesaS)queSvi T&h T-$rT} Tri$UsaV(Vi=Vot#Z-a3Ag+maAle$Da)Fu,Gi.Lat#Lu-%M*u'Nast@Nh{oOceseRe$Sc[)Sf ceSp oSque%Ssip S)n%T?UrnoV(,Vi,rV~g Z(5Br?L|i=M?M*#NativoNz`>m-%Rs&SagemUr#U$r2EnagemIbleOg @2El EndeE$PloQues><%Vi=,:1Lod'O Olog@0Ific It&Uc#1Ei$Etiv 3E.1Ab| Eg(Ei$rEncoEv?Im* Ogi 0B goBol#Br~/Buti=EndaErg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Lo[sN)gemQu{oRe)Rr(Sc~ Sil]S,u+Z Zio3A=D Ge.Ic~ L{oLhiceLu=Nce=rNdav&N( Nt[Rb&Rd!eRe?Rg}h>m`/RnizRs R%n%SpaSti=T|i&3Adu$AgemAj Atu+Br?D{aDr @ElaGaG-%Gi G| L ejoNcoNhe)NilOle)R!>tudeSi.S$Tr&V{oZ*/5A=rArG&L<%LeibolL)gemLumo,Nt!e5L$Vuz`a::D[zRope3QueRe.Rife3Ng ::Ng#Rp 3BuL?9Mb Olog@5Mbi="; +const checksum = "0x2219000926df7b50d8aa0a3d495826b988287df4657fbd100e6fe596c8f737ac"; +class LangPt extends wordlist_owl_js_1.WordlistOwl { + constructor() { super("pt", words, checksum); } +} +exports.LangPt = LangPt; +exports.langPt = new LangPt(); +//# sourceMappingURL=lang-pt.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-pt.js.map b/lib.commonjs/wordlists/lang-pt.js.map new file mode 100644 index 000000000..90d460518 --- /dev/null +++ b/lib.commonjs/wordlists/lang-pt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-pt.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-pt.ts"],"names":[],"mappings":";;;AAAA,uDAAgD;AAEhD,MAAM,KAAK,GAAG,s0OAAs0O,CAAC;AACr1O,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AAEtF,MAAa,MAAO,SAAQ,6BAAW;IACnC,gBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClD;AAFD,wBAEC;AAEY,QAAA,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-zh.js b/lib.commonjs/wordlists/lang-zh.js new file mode 100644 index 000000000..0aaf61720 --- /dev/null +++ b/lib.commonjs/wordlists/lang-zh.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.langZhTw = exports.langZhCn = void 0; +const index_js_1 = require("../hash/index.js"); +const index_js_2 = require("../utils/index.js"); +const wordlist_js_1 = require("./wordlist.js"); +const data = "}aE#4A=Yv&co#4N#6G=cJ&SM#66|/Z#4t&kn~46#4K~4q%b9=IR#7l,mB#7W_X2*dl}Uo~7s}Uf&Iw#9c&cw~6O&H6&wx&IG%v5=IQ~8a&Pv#47$PR&50%Ko&QM&3l#5f,D9#4L|/H&tQ;v0~6n]nN> 2), + 128 + codes.indexOf(data[i * 3 + 1]), + 128 + codes.indexOf(data[i * 3 + 2]), + ]; + if (locale === "zh_tw") { + const common = s % 4; + for (let i = common; i < 3; i++) { + bytes[i] = codes.indexOf(deltaData[deltaOffset++]) + ((i == 0) ? 228 : 128); + } + } + wordlist.push((0, index_js_2.toUtf8String)(new Uint8Array(bytes))); + } + // Verify the computed list matches the official list + const checksum = (0, index_js_1.id)(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== Checks[locale]) { + throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`); + } + /* c8 ignore stop */ + _wordlist[locale] = wordlist; + return wordlist; +} +class LangZh extends wordlist_js_1.Wordlist { + constructor(country) { super("zh_" + country); } + getWord(index) { + const words = loadWords(this.locale); + if (index < 0 || index >= words.length) { + index_js_2.logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords(this.locale).indexOf(word); + } + split(mnemonic) { + mnemonic = mnemonic.replace(/(?:\u3000| )+/g, ""); + return mnemonic.split(""); + } +} +exports.langZhCn = new LangZh("cn"); +exports.langZhTw = new LangZh("tw"); +//# sourceMappingURL=lang-zh.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/lang-zh.js.map b/lib.commonjs/wordlists/lang-zh.js.map new file mode 100644 index 000000000..d9c794689 --- /dev/null +++ b/lib.commonjs/wordlists/lang-zh.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-zh.js","sourceRoot":"","sources":["../../src.ts/wordlists/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AC;IAED,KAAK,CAAC,QAAgB;QAClB,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;QAClD,OAAO,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC9B,CAAC;CACJ;AAEY,QAAA,QAAQ,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC;AAC5B,QAAA,QAAQ,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlist-owl.js b/lib.commonjs/wordlists/wordlist-owl.js new file mode 100644 index 000000000..430d117e8 --- /dev/null +++ b/lib.commonjs/wordlists/wordlist-owl.js @@ -0,0 +1,50 @@ +"use strict"; +// Use the encode-latin.js script to create the necessary +// data files to be consumed by this class +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WordlistOwl = void 0; +const id_js_1 = require("../hash/id.js"); +const logger_js_1 = require("../utils/logger.js"); +const decode_owl_js_1 = require("./decode-owl.js"); +const wordlist_js_1 = require("./wordlist.js"); +class WordlistOwl extends wordlist_js_1.Wordlist { + #data; + #checksum; + constructor(locale, data, checksum) { + super(locale); + this.#data = data; + this.#checksum = checksum; + this.#words = null; + } + get _data() { return this.#data; } + _decodeWords() { + return (0, decode_owl_js_1.decodeOwl)(this.#data); + } + #words; + #loadWords() { + if (this.#words == null) { + const words = this._decodeWords(); + // Verify the computed list matches the official list + const checksum = (0, id_js_1.id)(words.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== this.#checksum) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); + } + /* c8 ignore stop */ + this.#words = words; + } + return this.#words; + } + getWord(index) { + const words = this.#loadWords(); + if (index < 0 || index >= words.length) { + logger_js_1.logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return this.#loadWords().indexOf(word); + } +} +exports.WordlistOwl = WordlistOwl; +//# sourceMappingURL=wordlist-owl.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlist-owl.js.map b/lib.commonjs/wordlists/wordlist-owl.js.map new file mode 100644 index 000000000..eb0a6db1f --- /dev/null +++ b/lib.commonjs/wordlists/wordlist-owl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist-owl.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist-owl.ts"],"names":[],"mappings":";AACA,yDAAyD;AACzD,0CAA0C;;;AAE1C,yCAAmC;AACnC,kDAA4C;AAE5C,mDAA4C;AAC5C,+CAAyC;AAEzC,MAAa,WAAY,SAAQ,sBAAQ;IACrC,KAAK,CAAS;IACd,SAAS,CAAS;IAElB,YAAY,MAAc,EAAE,IAAY,EAAE,QAAgB;QACtD,KAAK,CAAC,MAAM,CAAC,CAAC;QACd,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACvB,CAAC;IAED,IAAI,KAAK,KAAa,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAE1C,YAAY;QACR,OAAO,IAAA,yBAAS,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,MAAM,CAAuB;IAC7B,UAAU;QACN,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,EAAE;YACrB,MAAM,KAAK,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YAElC,qDAAqD;YACrD,MAAM,QAAQ,GAAG,IAAA,UAAE,EAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;YAC7C,qBAAqB;YACrB,IAAI,QAAQ,KAAK,IAAI,CAAC,SAAS,EAAE;gBAC7B,MAAM,IAAI,KAAK,CAAC,sBAAuB,IAAI,CAAC,MAAO,SAAS,CAAC,CAAC;aACjE;YACD,oBAAoB;YAEpB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;SACvB;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAED,OAAO,CAAC,KAAa;QACjB,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QAChC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;YACpC,kBAAM,CAAC,kBAAkB,CAAC,uBAAwB,KAAM,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC/E;QACD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAED,YAAY,CAAC,IAAY;QACrB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,CAAC;CACJ;AA9CD,kCA8CC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlist-owla.js b/lib.commonjs/wordlists/wordlist-owla.js new file mode 100644 index 000000000..696ecd9ae --- /dev/null +++ b/lib.commonjs/wordlists/wordlist-owla.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WordlistOwlA = void 0; +const wordlist_owl_js_1 = require("./wordlist-owl.js"); +const decode_owla_js_1 = require("./decode-owla.js"); +class WordlistOwlA extends wordlist_owl_js_1.WordlistOwl { + #accent; + constructor(locale, data, accent, checksum) { + super(locale, data, checksum); + this.#accent = accent; + } + get _accent() { return this.#accent; } + _decodeWords() { + return (0, decode_owla_js_1.decodeOwlA)(this._data, this._accent); + } +} +exports.WordlistOwlA = WordlistOwlA; +//# sourceMappingURL=wordlist-owla.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlist-owla.js.map b/lib.commonjs/wordlists/wordlist-owla.js.map new file mode 100644 index 000000000..67bc6e9be --- /dev/null +++ b/lib.commonjs/wordlists/wordlist-owla.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist-owla.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist-owla.ts"],"names":[],"mappings":";;;AACA,uDAAgD;AAChD,qDAA8C;AAE9C,MAAa,YAAa,SAAQ,6BAAW;IACzC,OAAO,CAAS;IAEhB,YAAY,MAAc,EAAE,IAAY,EAAE,MAAc,EAAE,QAAgB;QACtE,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,IAAI,OAAO,KAAa,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE9C,YAAY;QACR,OAAO,IAAA,2BAAU,EAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC;CACJ;AAbD,oCAaC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlist.js b/lib.commonjs/wordlists/wordlist.js new file mode 100644 index 000000000..d2b4de61b --- /dev/null +++ b/lib.commonjs/wordlists/wordlist.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Wordlist = void 0; +const index_js_1 = require("../utils/index.js"); +class Wordlist { + locale; + constructor(locale) { + (0, index_js_1.defineProperties)(this, { locale }); + } + // Subclasses may override this + split(mnemonic) { + return mnemonic.toLowerCase().split(/ +/g); + } + // Subclasses may override this + join(words) { + return words.join(" "); + } +} +exports.Wordlist = Wordlist; +//# sourceMappingURL=wordlist.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlist.js.map b/lib.commonjs/wordlists/wordlist.js.map new file mode 100644 index 000000000..a3d39664c --- /dev/null +++ b/lib.commonjs/wordlists/wordlist.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist.ts"],"names":[],"mappings":";;;AAAA,gDAAqD;AAErD,MAAsB,QAAQ;IAC1B,MAAM,CAAU;IAEhB,YAAY,MAAc;QACtB,IAAA,2BAAgB,EAAW,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,+BAA+B;IAC/B,KAAK,CAAC,QAAgB;QAClB,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;IAC9C,CAAC;IAED,+BAA+B;IAC/B,IAAI,CAAC,KAAoB;QACrB,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;CAIJ;AAnBD,4BAmBC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlists-browser.js b/lib.commonjs/wordlists/wordlists-browser.js new file mode 100644 index 000000000..11dfccac3 --- /dev/null +++ b/lib.commonjs/wordlists/wordlists-browser.js @@ -0,0 +1,9 @@ +"use strict"; +// wordlists/wordlists-browser.js +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlists = void 0; +const lang_en_js_1 = require("./lang-en.js"); +exports.wordlists = Object.freeze({ + en: lang_en_js_1.langEn +}); +//# sourceMappingURL=wordlists-browser.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlists-browser.js.map b/lib.commonjs/wordlists/wordlists-browser.js.map new file mode 100644 index 000000000..d0e7dae58 --- /dev/null +++ b/lib.commonjs/wordlists/wordlists-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists-browser.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists-browser.ts"],"names":[],"mappings":";AACA,iCAAiC;;;AAEjC,6CAA4C;AAI/B,QAAA,SAAS,GAA6B,MAAM,CAAC,MAAM,CAAC;IAC7D,EAAE,EAAF,mBAAE;CACL,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlists-extra.js b/lib.commonjs/wordlists/wordlists-extra.js new file mode 100644 index 000000000..bdfb6c94c --- /dev/null +++ b/lib.commonjs/wordlists/wordlists-extra.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlists = void 0; +const lang_cz_js_1 = require("./lang-cz.js"); +const lang_es_js_1 = require("./lang-es.js"); +const lang_fr_js_1 = require("./lang-fr.js"); +const lang_ja_js_1 = require("./lang-ja.js"); +const lang_ko_js_1 = require("./lang-ko.js"); +const lang_it_js_1 = require("./lang-it.js"); +const lang_pt_js_1 = require("./lang-pt.js"); +const lang_zh_js_1 = require("./lang-zh.js"); +exports.wordlists = Object.freeze({ + cz: lang_cz_js_1.langCz, es: lang_es_js_1.langEs, fr: lang_fr_js_1.langFr, ja: lang_ja_js_1.langJa, ko: lang_ko_js_1.langKo, it: lang_it_js_1.langIt, pt: lang_pt_js_1.langPt, zh_cn: lang_zh_js_1.langZhCn, zh_tw: lang_zh_js_1.langZhTw +}); +//# sourceMappingURL=wordlists-extra.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlists-extra.js.map b/lib.commonjs/wordlists/wordlists-extra.js.map new file mode 100644 index 000000000..f33c845c1 --- /dev/null +++ b/lib.commonjs/wordlists/wordlists-extra.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists-extra.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists-extra.ts"],"names":[],"mappings":";;;AACA,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAAoE;AAIvD,QAAA,SAAS,GAA6B,MAAM,CAAC,MAAM,CAAC;IAC7D,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,KAAK,EAAL,qBAAK,EAAE,KAAK,EAAL,qBAAK;CAC3C,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlists.js b/lib.commonjs/wordlists/wordlists.js new file mode 100644 index 000000000..422fbb8ea --- /dev/null +++ b/lib.commonjs/wordlists/wordlists.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wordlists = void 0; +const lang_cz_js_1 = require("./lang-cz.js"); +const lang_en_js_1 = require("./lang-en.js"); +const lang_es_js_1 = require("./lang-es.js"); +const lang_fr_js_1 = require("./lang-fr.js"); +const lang_ja_js_1 = require("./lang-ja.js"); +const lang_ko_js_1 = require("./lang-ko.js"); +const lang_it_js_1 = require("./lang-it.js"); +const lang_pt_js_1 = require("./lang-pt.js"); +const lang_zh_js_1 = require("./lang-zh.js"); +exports.wordlists = Object.freeze({ + cz: lang_cz_js_1.langCz, en: lang_en_js_1.langEn, es: lang_es_js_1.langEs, fr: lang_fr_js_1.langFr, ja: lang_ja_js_1.langJa, ko: lang_ko_js_1.langKo, it: lang_it_js_1.langIt, pt: lang_pt_js_1.langPt, zh_cn: lang_zh_js_1.langZhCn, zh_tw: lang_zh_js_1.langZhTw +}); +//# sourceMappingURL=wordlists.js.map \ No newline at end of file diff --git a/lib.commonjs/wordlists/wordlists.js.map b/lib.commonjs/wordlists/wordlists.js.map new file mode 100644 index 000000000..a189013d3 --- /dev/null +++ b/lib.commonjs/wordlists/wordlists.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists.ts"],"names":[],"mappings":";;;AAAA,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAA4C;AAC5C,6CAAoE;AAIvD,QAAA,SAAS,GAA6B,MAAM,CAAC,MAAM,CAAC;IAC7D,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,EAAE,EAAF,mBAAE,EAAE,KAAK,EAAL,qBAAK,EAAE,KAAK,EAAL,qBAAK;CAC/C,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_admin/update-version-const.js b/lib.esm/_admin/update-version-const.js new file mode 100644 index 000000000..f780f66af --- /dev/null +++ b/lib.esm/_admin/update-version-const.js @@ -0,0 +1,7 @@ +import { atomicWrite } from "./utils/fs.js"; +import { resolve } from "./utils/path.js"; +import { loadJson } from "./utils/json.js"; +const version = loadJson(resolve("package.json")).version; +const content = `export const version = "${version}";\n`; +atomicWrite(resolve("src.ts/_version.ts"), content); +//# sourceMappingURL=update-version-const.js.map \ No newline at end of file diff --git a/lib.esm/_admin/update-version-const.js.map b/lib.esm/_admin/update-version-const.js.map new file mode 100644 index 000000000..1f2540c39 --- /dev/null +++ b/lib.esm/_admin/update-version-const.js.map @@ -0,0 +1 @@ +{"version":3,"file":"update-version-const.js","sourceRoot":"","sources":["../../src.ts/_admin/update-version-const.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC;AAE1D,MAAM,OAAO,GAAG,2BAA4B,OAAQ,MAAM,CAAC;AAC3D,WAAW,CAAC,OAAO,CAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_admin/utils/fs.js b/lib.esm/_admin/utils/fs.js new file mode 100644 index 000000000..61ed7f290 --- /dev/null +++ b/lib.esm/_admin/utils/fs.js @@ -0,0 +1,8 @@ +import fs from "fs"; +import { resolve } from "./path.js"; +export function atomicWrite(path, value) { + const tmp = resolve(".atomic-tmp"); + fs.writeFileSync(tmp, value); + fs.renameSync(tmp, path); +} +//# sourceMappingURL=fs.js.map \ No newline at end of file diff --git a/lib.esm/_admin/utils/fs.js.map b/lib.esm/_admin/utils/fs.js.map new file mode 100644 index 000000000..8c6507df4 --- /dev/null +++ b/lib.esm/_admin/utils/fs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../../src.ts/_admin/utils/fs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,KAA0B;IAChE,MAAM,GAAG,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACnC,EAAE,CAAC,aAAa,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAC7B,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/lib.esm/_admin/utils/json.js b/lib.esm/_admin/utils/json.js new file mode 100644 index 000000000..603ebd40b --- /dev/null +++ b/lib.esm/_admin/utils/json.js @@ -0,0 +1,26 @@ +import fs from "fs"; +import { atomicWrite } from "./fs.js"; +export function loadJson(path) { + return JSON.parse(fs.readFileSync(path).toString()); +} +export function saveJson(filename, data, sort) { + let replacer = undefined; + if (sort) { + replacer = (key, value) => { + if (Array.isArray(value)) { + // pass + } + else if (value && typeof (value) === "object") { + const keys = Object.keys(value); + keys.sort(); + return keys.reduce((accum, key) => { + accum[key] = value[key]; + return accum; + }, {}); + } + return value; + }; + } + atomicWrite(filename, JSON.stringify(data, replacer, 2) + "\n"); +} +//# sourceMappingURL=json.js.map \ No newline at end of file diff --git a/lib.esm/_admin/utils/json.js.map b/lib.esm/_admin/utils/json.js.map new file mode 100644 index 000000000..fa12cde63 --- /dev/null +++ b/lib.esm/_admin/utils/json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json.js","sourceRoot":"","sources":["../../../src.ts/_admin/utils/json.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGtC,MAAM,UAAU,QAAQ,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;AACxD,CAAC;AAID,MAAM,UAAU,QAAQ,CAAC,QAAgB,EAAE,IAAS,EAAE,IAAc;IAEhE,IAAI,QAAQ,GAA2B,SAAS,CAAC;IACjD,IAAI,IAAI,EAAE;QACN,QAAQ,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACtB,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBACtB,OAAO;aACV;iBAAM,IAAI,KAAK,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;gBAC5C,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBAChC,IAAI,CAAC,IAAI,EAAE,CAAC;gBACZ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;oBAC9B,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;oBACxB,OAAO,KAAK,CAAC;gBACjB,CAAC,EAAuB,EAAE,CAAC,CAAC;aAC/B;YACD,OAAO,KAAK,CAAC;QACjB,CAAC,CAAC;KACL;IAED,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;AACpE,CAAC"} \ No newline at end of file diff --git a/lib.esm/_admin/utils/path.js b/lib.esm/_admin/utils/path.js new file mode 100644 index 000000000..728ff88ab --- /dev/null +++ b/lib.esm/_admin/utils/path.js @@ -0,0 +1,12 @@ +import { dirname, resolve as _resolve } from "path"; +import { fileURLToPath } from 'url'; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export const ROOT = _resolve(__dirname, "../../../"); +console.log(ROOT); +export function resolve(...args) { + args = args.slice(); + args.unshift(ROOT); + return _resolve.apply(null, args); +} +//# sourceMappingURL=path.js.map \ No newline at end of file diff --git a/lib.esm/_admin/utils/path.js.map b/lib.esm/_admin/utils/path.js.map new file mode 100644 index 000000000..5096d5ef3 --- /dev/null +++ b/lib.esm/_admin/utils/path.js.map @@ -0,0 +1 @@ +{"version":3,"file":"path.js","sourceRoot":"","sources":["../../../src.ts/_admin/utils/path.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,MAAM,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEtC,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AACrD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAElB,MAAM,UAAU,OAAO,CAAC,GAAG,IAAmB;IAC1C,IAAI,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;IACpB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACnB,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACtC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-abi.js b/lib.esm/_tests/test-abi.js new file mode 100644 index 000000000..c54cfb567 --- /dev/null +++ b/lib.esm/_tests/test-abi.js @@ -0,0 +1,41 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { defaultAbiCoder } from "../index.js"; +function equal(actual, expected) { + switch (expected.type) { + case "address": + case "boolean": + case "hexstring": + case "string": + assert.equal(actual, expected.value); + return; + case "number": + assert.equal(actual, BigInt(expected.value)); + return; + case "array": + case "object": + assert.ok(Array.isArray(actual), "!array"); + assert.equal(actual.length, expected.value.length, ".length mismatch"); + for (let i = 0; i < actual.length; i++) { + equal(actual[i], expected.value[i]); + } + return; + } + throw new Error(`unsupported: ${expected}`); +} +describe("Tests ABI Coder", function () { + const tests = loadTests("abi"); + for (const test of tests) { + it(`tests ABI encoding: (${test.name})`, function () { + const encoded = defaultAbiCoder.encode([test.type], [test.value]); + assert.equal(encoded, test.encoded, "encoded"); + }); + } + for (const test of tests) { + it(`tests ABI decoding: (${test.name})`, function () { + const decoded = defaultAbiCoder.decode([test.type], test.encoded)[0]; + equal(decoded, test.verbose); + }); + } +}); +//# sourceMappingURL=test-abi.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-abi.js.map b/lib.esm/_tests/test-abi.js.map new file mode 100644 index 000000000..cfc34c446 --- /dev/null +++ b/lib.esm/_tests/test-abi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-abi.js","sourceRoot":"","sources":["../../src.ts/_tests/test-abi.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,SAAS,KAAK,CAAC,MAAW,EAAE,QAA4B;IACpD,QAAQ,QAAQ,CAAC,IAAI,EAAE;QACnB,KAAK,SAAS,CAAC;QAAC,KAAK,SAAS,CAAC;QAAC,KAAK,WAAW,CAAC;QAAC,KAAK,QAAQ;YAC3D,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;YACrC,OAAO;QACX,KAAK,QAAQ;YACT,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;YAC7C,OA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CAAC,OAAO,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-address.js b/lib.esm/_tests/test-address.js new file mode 100644 index 000000000..cee8d90b9 --- /dev/null +++ b/lib.esm/_tests/test-address.js @@ -0,0 +1,110 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { getAddress, getIcapAddress, getCreateAddress, getCreate2Address } from "../index.js"; +describe("computes checksum address", function () { + const tests = loadTests("accounts"); + for (const test of tests) { + it(`computes the checksum address: ${test.name}`, function () { + assert.equal(getAddress(test.address), test.address); + assert.equal(getAddress(test.icap), test.address); + assert.equal(getAddress(test.address.substring(2)), test.address); + assert.equal(getAddress(test.address.toLowerCase()), test.address); + assert.equal(getAddress("0x" + test.address.substring(2).toUpperCase()), test.address); + }); + } + const invalidAddresses = [ + { name: "null", value: null }, + { name: "number", value: 1234 }, + { name: "emtpy bytes", value: "0x" }, + { name: "too short", value: "0x8ba1f109551bd432803012645ac136ddd64dba" }, + { name: "too long", value: "0x8ba1f109551bd432803012645ac136ddd64dba7200" }, + ]; + invalidAddresses.forEach(({ name, value }) => { + it(`fails on invalid address: ${name}`, function () { + assert.throws(function () { + getAddress(value); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid address/) && + error.argument === "address" && + error.value === value); + }); + }); + }); + it("fails on invalid checksum", function () { + const value = "0x8ba1f109551bD432803012645Ac136ddd64DBa72"; + assert.throws(function () { + getAddress(value); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^bad address checksum/) && + error.argument === "address" && + error.value === value); + }); + }); + it("fails on invalid IBAN checksum", function () { + const value = "XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37"; + assert.throws(function () { + getAddress(value); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^bad icap checksum/) && + error.argument === "address" && + error.value === value); + }); + }); +}); +describe("computes ICAP address", function () { + const tests = loadTests("accounts"); + for (const test of tests) { + it(`computes the ICAP address: ${test.name}`, function () { + assert.equal(getIcapAddress(test.address), test.icap); + assert.equal(getAddress(test.address.toLowerCase()), test.address); + assert.equal(getAddress("0x" + test.address.substring(2).toUpperCase()), test.address); + }); + } +}); +describe("computes create address", function () { + const tests = loadTests("create"); + for (const { sender, creates } of tests) { + for (const { name, nonce, address } of creates) { + it(`computes the create address: ${name}`, function () { + assert.equal(getCreateAddress({ from: sender, nonce }), address); + }); + } + } +}); +describe("computes create2 address", function () { + const tests = loadTests("create2"); + for (const { sender, creates } of tests) { + for (const { name, salt, initCodeHash, address } of creates) { + it(`computes the create2 address: ${name}`, function () { + assert.equal(getCreate2Address(sender, salt, initCodeHash), address); + }); + } + } + const sender = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; + const salt = "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"; + const initCodeHash = "0x8452c9b9140222b08593a26daa782707297be9f7b3e8281d7b4974769f19afd0"; + it("fails on invalid salt", function () { + const badSalt = "0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36dea"; + assert.throws(function () { + getCreate2Address(sender, badSalt, initCodeHash); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "salt" && + error.value === badSalt); + }); + }); + it("fails on invalid initCodeHash", function () { + const badInitCodeHash = "0x8452c9b9140222b08593a26daa782707297be9f7b3e8281d7b4974769f19af"; + assert.throws(function () { + getCreate2Address(sender, salt, badInitCodeHash); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "initCodeHash" && + error.value === badInitCodeHash); + }); + }); +}); +//# sourceMappingURL=test-address.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-address.js.map b/lib.esm/_tests/test-address.js.map new file mode 100644 index 000000000..cb762a880 --- /dev/null +++ b/lib.esm/_tests/test-address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-address.js","sourceRoot":"","sources":["../../src.ts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AAS,KAAU;YAClB,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,kBAAkB;gBACrC,KAAK,CAAC,QAAQ,KAAK,cAAc;gBACjC,KAAK,CAAC,KAAK,KAAK,eAAe,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-contract.js b/lib.esm/_tests/test-contract.js new file mode 100644 index 000000000..86aed7e10 --- /dev/null +++ b/lib.esm/_tests/test-contract.js @@ -0,0 +1,99 @@ +"use strict"; +/* +import { Typed } from "../abi/index.js"; +import * as providers from "../providers/index.js"; + +import { Contract } from "../index.js"; + +import { log } from "./utils.js"; +*/ +//import type { Addressable } from "@ethersproject/address"; +//import type { BigNumberish } from "@ethersproject/logger"; +/* +import type { + ConstantContractMethod, ContractMethod, ContractEvent +} from "../index.js"; +*/ +// @TODO +/* +describe("Test Contract Calls", function() { + it("finds typed methods", async function() { + const contract = new Contract("0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72", [ + "function foo(string s) view returns (uint)", + "function foo(uint8) view returns (uint)", + "function foo(uint u, bool b) view returns (uint)", + ]); + const value = Typed.string("42"); + await contract.foo.populateTransaction(value, Typed.overrides({ value: 100 })) + contract["foo(string)"].fragment + }); +}); +*/ +/* +describe("Test Contract Interface", function() { + it("builds contract interfaces", async function() { + this.timeout(60000); + + interface Erc20Interface { + // Constant Methods + balanceOf: ConstantContractMethod<[ address: string | Addressable ], bigint>; + decimals: ConstantContractMethod<[ ], bigint>; + + name: ConstantContractMethod<[ ], string>; + symbol: ConstantContractMethod<[ ], string>; + + // Mutation Methods + transferFrom: ContractMethod<[ address: string | Addressable, + address: string | Addressable, amount: BigNumberish ], boolean>; + + // Events + filters: { + Transfer: ContractEvent<[ from: Addressable | string, to: BigNumberish ]>; + } + } + + const erc20Abi = [ + "function balanceOf(address owner) view returns (uint)", + "function decimals() view returns (uint)", + "function name() view returns (string)", + "function symbol() view returns (string)", + + "function transferFrom(address from, address to, uint amount) returns (boolean)", + + "event Transfer(address indexed from, address indexed to, uint amount)" + ]; + + class Erc20Contract extends BaseContract.buildClass(erc20Abi) { }; + + const provider = new providers.InfuraProvider(); + // ENS + //const addr = "0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72"; + // DAI + const addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; + const contract = new Erc20Contract(addr, provider); + console.log("SYMBOL", await contract.symbol()); + console.log("DECIMALS", await contract.decimals()); + console.log(await contract.balanceOf("0x5555763613a12D8F3e73be831DFf8598089d3dCa")); + console.log(await contract.balanceOf("ricmoo.eth")); + + await contract.on(contract.filters.Transfer, (from, to, value, event) => { + console.log("HELLO!", { from, to, value, event }); + event.removeListener(); + }); + const logs = await contract.queryFilter("Transfer", -10); + console.log(logs, logs[0], logs[0].args.from); + }); +}); +*/ +/* +describe("Test Contract Calls", function() { + it("calls ERC-20 methods", async function() { + const provider = new providers.AnkrProvider(); + const contract = new Contract("0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72", [ + "function balanceOf(address owner) view returns (uint)", + ], provider); + log(this, `balance: ${ await contract.balanceOf("0x5555763613a12D8F3e73be831DFf8598089d3dCa") }`); + }); +}); +*/ +//# sourceMappingURL=test-contract.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-contract.js.map b/lib.esm/_tests/test-contract.js.map new file mode 100644 index 000000000..736766abd --- /dev/null +++ b/lib.esm/_tests/test-contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-contract.js","sourceRoot":"","sources":["../../src.ts/_tests/test-contract.ts"],"names":[],"mappings":";AAAA;;;;;;;EAOE;AACF,4DAA4D;AAC5D,4DAA4D;AAE5D;;;;EAIE;AAEF,QAAQ;AACR;;;;;;;;;;;;;EAaE;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuDE;AACF;;;;;;;;;;EAUE"} \ No newline at end of file diff --git a/lib.esm/_tests/test-crypto-algoswap.js b/lib.esm/_tests/test-crypto-algoswap.js new file mode 100644 index 000000000..08a7c9d43 --- /dev/null +++ b/lib.esm/_tests/test-crypto-algoswap.js @@ -0,0 +1,82 @@ +import assert from "assert"; +import { lock, computeHmac, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync } from "../index.js"; +describe("test registration", function () { + let hijack = ""; + function getHijack(algo) { + return function (...args) { + hijack = `hijacked ${algo}: ${JSON.stringify(args)}`; + return "0x42"; + }; + } + const tests = [ + { + name: "keccak256", + params: ["0x"], + hijackTag: 'hijacked keccak256: [{}]', + algorithm: keccak256 + }, + { + name: "sha256", + params: ["0x"], + hijackTag: 'hijacked sha256: [{}]', + algorithm: sha256 + }, + { + name: "sha512", + params: ["0x"], + hijackTag: 'hijacked sha512: [{}]', + algorithm: sha512 + }, + { + name: "ripemd160", + params: ["0x"], + hijackTag: 'hijacked ripemd160: [{}]', + algorithm: ripemd160 + }, + { + name: "pbkdf2", + params: ["0x", "0x", 1024, 32, "sha256"], + hijackTag: 'hijacked pbkdf2: [{},{},1024,32,"sha256"]', + algorithm: pbkdf2 + }, + { + name: "scryptSync", + params: ["0x", "0x", 1024, 8, 1, 32], + hijackTag: 'hijacked scryptSync: [{},{},1024,8,1,32]', + algorithm: scryptSync + }, + { + name: "scrypt", + params: ["0x", "0x", 1024, 8, 1, 32], + hijackTag: 'hijacked scrypt: [{},{},1024,8,1,32,null]', + algorithm: scrypt + }, + { + name: "computeHmac", + params: ["sha256", "0x", "0x"], + hijackTag: 'hijacked computeHmac: ["sha256",{},{}]', + algorithm: computeHmac + }, + ]; + tests.forEach(({ name, params, hijackTag, algorithm }) => { + it(`swaps in hijacked callback: ${name}`, async function () { + const initial = await algorithm(...params); + algorithm.register(getHijack(name)); + assert.equal(await algorithm(...params), "0x42"); + assert.equal(hijack, hijackTag); + algorithm.register(algorithm._); + assert.equal(await algorithm(...params), initial); + }); + }); + it("prevents swapping after locked", function () { + lock(); + tests.forEach(({ name, params, hijackTag, algorithm }) => { + assert.throws(function () { + algorithm.register(getHijack("test")); + }, function (error) { + return (error.message === `${name} is locked`); + }); + }); + }); +}); +//# sourceMappingURL=test-crypto-algoswap.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-crypto-algoswap.js.map b/lib.esm/_tests/test-crypto-algoswap.js.map new file mode 100644 index 000000000..736a7350e --- /dev/null +++ b/lib.esm/_tests/test-crypto-algoswap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-crypto-algoswap.js","sourceRoot":"","sources":["../../src.ts/_tests/test-crypto-algoswap.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EACH,IAAI,EAEJ,WAAW,EAEX,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAEpC,MAAM,EAAE,MAAM,EAAE,UAAU,EAC7B,MAAM,aAAa,CAAC;AAkBrB,QAAQ,CAAC,mBAAmB,EAAE;IAE1B,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,SAAS,SAAS,CAAC,IAAY;QAC3B,OAAO,UAAS,GAAG,IAAgB;YAC/B,MAAM,GAAG,YAAa,IAAK,KAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAE,EAAE,CAAC;YACzD,OAAO,MAAM,CAAC;QAClB,CAAC,CAAA;IACL,CAAC;IAED,MAAM,KAAK,GAAoB;QAC3B;YACI,IAAI,EAAE,WAAW;YACjB,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,0BAA0B;YACrC,SAAS,EAAE,SAAS;SACvB;QACD;YACI,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,uBAAuB;YAClC,SAAS,EAAE,MAAM;SACpB;QACD;YACI,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,CAAE,IAAI,CAAE;YAChB,SAAS,EAAE,uBAAuB;YAClC,SAAS,EAAE,MAAM;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EAAE,SAAS,CAAC,CAAC;YAEhC,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;YAChC,MAAM,CAAC,KAAK,CAAC,MAAM,SAAS,CAAC,GAAG,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,gCAAgC,EAAE;QACjC,IAAI,EAAE,CAAC;QAEP,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE;YACrD,MAAM,CAAC,MAAM,CAAC;gBACV,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;YAC1C,CAAC,EAAE,UAAS,KAAU;gBAClB,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,GAAI,IAAK,YAAY,CAAC,CAAC;YACrD,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AAEP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-crypto.js b/lib.esm/_tests/test-crypto.js new file mode 100644 index 000000000..d19525ea6 --- /dev/null +++ b/lib.esm/_tests/test-crypto.js @@ -0,0 +1,214 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { computeHmac, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync } from "../index.js"; +describe("test hashing", function () { + const tests = loadTests("hashes"); + tests.forEach((test) => { + it(`computes sha2-256: ${test.name}`, function () { + assert.equal(sha256(test.data), test.sha256); + }); + }); + tests.forEach((test) => { + it(`computes sha2-512: ${test.name}`, function () { + assert.equal(sha512(test.data), test.sha512); + }); + }); + tests.forEach((test) => { + it(`computes ripemd160: ${test.name}`, function () { + assert.equal(ripemd160(test.data), test.ripemd160); + }); + }); + tests.forEach((test) => { + it(`computes keccak256: ${test.name}`, function () { + assert.equal(keccak256(test.data), test.keccak256); + }); + }); +}); +describe("test password-based key derivation", function () { + const tests = loadTests("pbkdf"); + tests.forEach((test) => { + it(`computes pbkdf2: ${test.name}`, function () { + const password = Buffer.from(test.password.substring(2), "hex"); + const salt = Buffer.from(test.salt.substring(2), "hex"); + const { iterations, algorithm, key } = test.pbkdf2; + const result = pbkdf2(password, salt, iterations, test.dkLen, algorithm); + assert.equal(result, key); + }); + }); + tests.forEach((test) => { + it(`computes scrypt (sync): ${test.name}`, function () { + this.timeout(1000); + const password = Buffer.from(test.password.substring(2), "hex"); + const salt = Buffer.from(test.salt.substring(2), "hex"); + const { N, r, p, key } = test.scrypt; + const result = scryptSync(password, salt, N, r, p, test.dkLen); + assert.equal(result, key); + }); + }); + tests.forEach((test) => { + it(`computes scrypt (async): ${test.name}`, async function () { + this.timeout(1000); + const password = Buffer.from(test.password.substring(2), "hex"); + const salt = Buffer.from(test.salt.substring(2), "hex"); + const { N, r, p, key } = test.scrypt; + let progressCount = 0, progressOk = true, lastProgress = -1; + const result = await scrypt(password, salt, N, r, p, test.dkLen, (progress) => { + if (progress < lastProgress) { + progressOk = false; + } + lastProgress = progress; + progressCount++; + }); + assert.ok(progressOk, "progress was not monotonically increasing"); + assert.ok(progressCount > 100, "progress callback was called at leat 100 times"); + assert.equal(result, key); + }); + }); +}); +describe("test hmac", function () { + const tests = loadTests("hmac"); + tests.forEach((test) => { + it(`computes hmac: ${test.name}`, async function () { + const { algorithm, key, data } = test; + assert.equal(computeHmac(algorithm, key, data), test.hmac); + }); + }); +}); +/* +describe("test registration", function() { + let hijack = ""; + function getHijack(algo: string) { + return function(...args: Array) { + hijack = `hijacked ${ algo }: ${ JSON.stringify(args) }`; + return "0x42"; + } + } + + it("hijacks keccak256", function() { + const initial = keccak256("0x"); + + keccak256.register(getHijack("kecak256")); + assert.equal(keccak256("0x"), "0x42"); + assert.equal(hijack, 'hijacked kecak256: [{}]'); + + keccak256.register(keccak256._); + assert.equal(keccak256("0x"), initial); + + keccak256.lock(); + + assert.throws(function() { + keccak256.register(getHijack("test")); + }, function(error) { + return (error.message === "keccak256 is locked"); + }); + }); + + it("hijacks sha256", function() { + const initial = sha256("0x"); + + sha256.register(getHijack("sha256")); + assert.equal(sha256("0x"), "0x42"); + assert.equal(hijack, 'hijacked sha256: [{}]'); + + sha256.register(sha256._); + assert.equal(sha256("0x"), initial); + + sha256.lock(); + + assert.throws(function() { + sha256.register(getHijack("test")); + }, function(error) { + return (error.message === "sha256 is locked"); + }); + }); + + it("hijacks sha512", function() { + const initial = sha512("0x"); + + sha512.register(getHijack("sha512")); + assert.equal(sha512("0x"), "0x42"); + assert.equal(hijack, 'hijacked sha512: [{}]'); + + sha512.register(sha512._); + assert.equal(sha512("0x"), initial); + + sha512.lock(); + + assert.throws(function() { + sha512.register(getHijack("test")); + }, function(error) { + return (error.message === "sha512 is locked"); + }); + }); + + it("hijacks pbkdf2", function() { + const initial = pbkdf2("0x", "0x", 1024, 32, "sha256"); + + pbkdf2.register(getHijack("pbkdf2")); + assert.equal(pbkdf2("0x", "0x", 1024, 32, "sha256"), "0x42"); + assert.equal(hijack, 'hijacked pbkdf2: [{},{},1024,32,"sha256"]'); + + pbkdf2.register(pbkdf2._); + assert.equal(pbkdf2("0x", "0x", 1024, 32, "sha256"), initial); + + pbkdf2.lock(); + + assert.throws(function() { + pbkdf2.register(getHijack("test")); + }, function(error) { + return (error.message === "pbkdf2 is locked"); + }); + }); + + it("hijacks scryptSync", function() { + + function getHijack(...args: Array) { + hijack = `hijacked scryptSync: ${ JSON.stringify(args) }`; + return new Uint8Array([ 0x42 ]); + } + + const initial = scryptSync("0x", "0x", 1024, 8, 1, 32); + + scryptSync.register(getHijack); + assert.equal(scryptSync("0x", "0x", 1024, 8, 1, 32), "0x42"); + assert.equal(hijack, 'hijacked scryptSync: [{},{},1024,8,1,32]'); + + scryptSync.register(scryptSync._); + assert.equal(scryptSync("0x", "0x", 1024, 8, 1, 32), initial); + + scryptSync.lock(); + + assert.throws(function() { + scryptSync.register(getHijack); + }, function(error) { + return (error.message === "scryptSync is locked"); + }); + }); + + it("hijacks scrypt", async function() { + function getHijack(...args: Array) { + hijack = `hijacked scrypt: ${ JSON.stringify(args) }`; + return Promise.resolve(new Uint8Array([ 0x42 ])); + } + + const initial = await scrypt("0x", "0x", 1024, 8, 1, 32); + + scrypt.register(getHijack); + assert.equal(await scrypt("0x", "0x", 1024, 8, 1, 32), "0x42"); + assert.equal(hijack, 'hijacked scrypt: [{},{},1024,8,1,32,null]'); + + scrypt.register(scrypt._); + assert.equal(await scrypt("0x", "0x", 1024, 8, 1, 32), initial); + + scrypt.lock(); + + assert.throws(function() { + scrypt.register(getHijack); + }, function(error) { + return (error.message === "scrypt is locked"); + }); + }); + +}); +*/ +//# sourceMappingURL=test-crypto.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-crypto.js.map b/lib.esm/_tests/test-crypto.js.map new file mode 100644 index 000000000..99225886e --- /dev/null +++ b/lib.esm/_tests/test-crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-crypto.js","sourceRoot":"","sources":["../../src.ts/_tests/test-crypto.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,OAAO,EACH,WAAW,EACX,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EACpC,MAAM,EAAE,MAAM,EAAE,UAAU,EAC7B,MAAM,aAAa,CAAC;AAGrB,QAAQ,CAAC,cAAc,EAAE;IACrB,MAAM,KAAK,GAAG,SAAS,CAAe,QAAQ,CAAC,CAAC;IAEhD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,EAAE,CAAC,sBAAuB,IAAI,CAAC,IAAK,EAAE,EAAE;YACpC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACjD,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I,EAAE,EAAE,KAAK;YACpC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;YACtC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwIE"} \ No newline at end of file diff --git a/lib.esm/_tests/test-hash-typeddata.js b/lib.esm/_tests/test-hash-typeddata.js new file mode 100644 index 000000000..a590b0dd5 --- /dev/null +++ b/lib.esm/_tests/test-hash-typeddata.js @@ -0,0 +1,16 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { TypedDataEncoder } from "../index.js"; +describe("Tests Typed Data (EIP-712)", function () { + const tests = loadTests("typed-data"); + for (const test of tests) { + it(`tests encoding typed-data: ${test.name}`, function () { + const encoder = TypedDataEncoder.from(test.types); + assert.equal(encoder.primaryType, test.primaryType, "primaryType"); + assert.equal(encoder.encode(test.data), test.encoded, "encoded"); + assert.equal(TypedDataEncoder.getPrimaryType(test.types), test.primaryType, "primaryType"); + assert.equal(TypedDataEncoder.hash(test.domain, test.types, test.data), test.digest, "digest"); + }); + } +}); +//# sourceMappingURL=test-hash-typeddata.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-hash-typeddata.js.map b/lib.esm/_tests/test-hash-typeddata.js.map new file mode 100644 index 000000000..0e7cd1f55 --- /dev/null +++ b/lib.esm/_tests/test-hash-typeddata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-hash-typeddata.js","sourceRoot":"","sources":["../../src.ts/_tests/test-hash-typeddata.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,QAAQ,CAAC,4BAA4B,EAAE;IACnC,MAAM,KAAK,GAAG,SAAS,CAAoB,YAAY,CAAC,CAAC;IACzD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,EAAE,CAAC,8BAA+B,IAAI,CAAC,IAAK,EAAE,EAAE;YAC5C,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAClD,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;YACnE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;YAEjE,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;YAC3F,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACnG,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-hash.js b/lib.esm/_tests/test-hash.js new file mode 100644 index 000000000..fb88da02e --- /dev/null +++ b/lib.esm/_tests/test-hash.js @@ -0,0 +1,112 @@ +"use strict"; +/* +import assert from "assert"; +import { loadTests } from "./utils.js" +import type { TestCaseNamehash } from "./types.js"; + +import { dnsEncode, isValidName, namehash } from "../index.js"; + +describe("Tests Namehash", function() { + const tests = loadTests("namehash"); + for (const test of tests) { + it(`hashes ENS names: ${ JSON.stringify(test.ensName) }`, function() { + const actual = namehash(test.ensName); + + assert.equal(actual, test.namehash, "namehash"); + + // The empty string is not a valid ENS name + if (test.ensName) { + assert.ok(isValidName(test.ensName), "isValidName"); + } + }); + } +}); + +describe("Tests Bad ENS Names", function() { + const badTests: Array<{ ensName: any, prefix: string }> = [ + { ensName: ".", prefix: "missing component" }, + { ensName:"..", prefix: "missing component" }, + { ensName:"ricmoo..eth", prefix: "missing component" }, + { ensName:"ricmoo...eth", prefix: "missing component" }, + { ensName:".foo", prefix: "missing component" }, + { ensName:"foo.", prefix: "missing component" }, + { ensName: 1234, prefix: "not a string" }, + { ensName: true, prefix: "not a string" }, + ]; + + // The empty string is not a valid name, but has a valid namehash + // (the zero hash) as it is the base case for recursion + it("empty ENS name", function() { + assert.ok(!isValidName(""), "!isValidName"); + }); + + for (const { ensName, prefix } of badTests) { + it(`fails on bad ENS name: ${ JSON.stringify(ensName) }`, function() { + assert.ok(!isValidName(ensName), "!isValidName"); + assert.throws(() => { + const result = namehash(ensName); + console.log(result); + }, (error) => { + const errorPrefix = `invalid ENS name; ${ prefix }`; + return (error.code === "INVALID_ARGUMENT" && + error.argument === "name" && error.value === ensName && + error.message.substring(0, errorPrefix.length) === errorPrefix); + }); + }); + } +}); + +describe("Tests DNS Encoding", function() { + const tests: Array<{ ensName: string, dnsEncoded: string}> = [ + { ensName: "", dnsEncoded: "0x00" }, + { ensName: "ricmoo.eth", dnsEncoded: "0x067269636d6f6f0365746800" }, + ]; + + for (const { ensName, dnsEncoded } of tests) { + it(`computes the DNS Encoding: ${ JSON.stringify(ensName) }`, function() { + assert.equal(dnsEncode(ensName), dnsEncoded, "dnsEncoded"); + }); + } +}); + +describe("Tests DNS Names", function() { + const badTests: Array<{ ensName: any, prefix: string}> = [ + { ensName: ".", prefix: "invalid DNS name; missing component" }, + { ensName: "foo..bar", prefix: "invalid DNS name; missing component" }, + { ensName: ".foo", prefix: "invalid DNS name; missing component" }, + { ensName: "foo.", prefix: "invalid DNS name; missing component" }, + { ensName: 1234, prefix: "invalid DNS name; not a string" }, + { ensName: true, prefix: "invalid DNS name; not a string" }, + ]; + + for (const { ensName, prefix } of badTests) { + it(`fails on bad DNS name: ${ JSON.stringify(ensName) }`, function() { + assert.throws(() => { + const result = dnsEncode(ensName); + console.log(result); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "name" && error.value === ensName && + error.message.substring(0, prefix.length) === prefix); + }); + }); + } + + { + const ensName = "foobar012345678901234567890123456789012345678901234567890123456789"; + const prefix = "too long"; + it(`fails on bad DNS name: ${ JSON.stringify(ensName) }`, function() { + assert.throws(() => { + const result = dnsEncode(ensName); + console.log(result); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "value" && error.value === ensName && + error.message.substring(0, prefix.length) === prefix); + }); + }); + } + +}); +*/ +//# sourceMappingURL=test-hash.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-hash.js.map b/lib.esm/_tests/test-hash.js.map new file mode 100644 index 000000000..54c88f89b --- /dev/null +++ b/lib.esm/_tests/test-hash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-hash.js","sourceRoot":"","sources":["../../src.ts/_tests/test-hash.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6GE"} \ No newline at end of file diff --git a/lib.esm/_tests/test-rlp.js b/lib.esm/_tests/test-rlp.js new file mode 100644 index 000000000..dc382897e --- /dev/null +++ b/lib.esm/_tests/test-rlp.js @@ -0,0 +1,88 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { decodeRlp, encodeRlp } from "../index.js"; +describe("Test RLP Coder", function () { + const tests = loadTests("rlp"); + tests.forEach(({ name, encoded, decoded }) => { + it(`encodes RLP: ${name}`, function () { + assert.equal(encodeRlp(decoded), encoded); + }); + }); + tests.forEach(({ name, encoded, decoded }) => { + it(`decodes RLP: ${name}`, function () { + assert.deepStrictEqual(decodeRlp(encoded), decoded); + }); + }); +}); +describe("Test bad RLP Data", function () { + it("fails encoding data with invalid values", function () { + assert.throws(() => { + encodeRlp(["0x1234", 1234]); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.argument === "object" && + error.value === 1234); + }); + }); + it("fails decoding data with trailing junk", function () { + assert.throws(() => { + // Zeros_1 + decodeRlp("0x0042"); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^unexpected junk after rlp payload/) && + error.argument === "data" && + error.value === "0x0042"); + }); + }); + it("fails decoding short data", function () { + assert.throws(() => { + decodeRlp("0x"); + }, (error) => { + return (error.code === "BUFFER_OVERRUN" && + error.message.match(/^data too short/) && + Buffer.from(error.buffer).toString("hex") === "" && + error.offset === 1 && + error.length === 0); + }); + }); + it("fails decoding short data in child", function () { + assert.throws(() => { + decodeRlp("0xc8880102030405060708"); + }, (error) => { + return (error.code === "BUFFER_OVERRUN" && + error.message.match(/^child data too short/) && + Buffer.from(error.buffer).toString("hex") === "c8880102030405060708" && + error.offset === 0 && + error.length === 8); + }); + }); + it("fails decoding short segment data", function () { + assert.throws(() => { + // [["0x4243"], ["0x3145"]] = 0xc8 c3 82 4243 c3 82 3145 + // XXXX + decodeRlp("0xc8c382c3823145"); + }, (error) => { + return (error.code === "BUFFER_OVERRUN" && + error.message.match(/^data short segment too short/) && + Buffer.from(error.buffer).toString("hex") === "c8c382c3823145" && + error.offset === 9 && + error.length === 7); + }); + }); +}); +/* + utils.RLP.encode([["0x4243"], ["0x3145"]]) + + 0xc8 c3 82 4243 c3 82 3145 + + { + "name": "arrayShort2", + "decoded": [ + "0x48656c6c6f20576f726c64", + "0x48656c6c6f20576f726c64" + ], + "encoded": "0xd8 8b 48656c6c6f20576f726c64 8b 48656c6c6f20576f726c64" + }, +*/ +//# sourceMappingURL=test-rlp.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-rlp.js.map b/lib.esm/_tests/test-rlp.js.map new file mode 100644 index 000000000..f43d17d03 --- /dev/null +++ b/lib.esm/_tests/test-rlp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-rlp.js","sourceRoot":"","sources":["../../src.ts/_tests/test-rlp.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAInD,QAAQ,CAAC,gBAAgB,EAAE;IAEvB,MAAM,KAAK,GAAG,SAAS,CAAc,KAAK,CAAC,CAAC;IAE5C,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE;QACzC,EAAE,CAAC,gBAAiB,IAAK,EAAE,EAAE;YACzB,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE;QACzC,EAAE,CAAC,gBAAiB,IAAK,EAAE,EAAE;YACzB,MAAM,CAAC,eAAe,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;QACxD,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC;AAEH,QAAQ,CAAC,mBAAmB,EAAE;IAC1B,EAAE,CAAC,yCAAyC,EAAE;QAC1C,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE;YACf,SAAS,CAAC,CAAE,QAAQ,EAAmB,IAAI,CAAE,CAAC,CAAC;Q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C,CAAC;QACxC,CAAC,EAAE,CAAC,KAAU,EAAE,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,gBAAgB;gBACnC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC;gBAC5C,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,sBAAsB;gBACpE,KAAK,CAAC,MAAM,KAAK,CAAC;gBAClB,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAA;QAC3B,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,EAAE,CAAE,mCAAmC,EAAE;QACrC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE;YACf,wDAAwD;YACxD,6CAA6C;YAC7C,SAAS,CAAC,kBAAkB,CAAC,CAAC;QAClC,CAAC,EAAE,CAAC,KAAU,EAAE,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,gBAAgB;gBACnC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,+BAA+B,CAAC;gBACpD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,gBAAgB;gBAC9D,KAAK,CAAC,MAAM,KAAK,CAAC;gBAClB,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAA;QAC3B,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC;AAEH;;;;;;;;;;;;;EAaE"} \ No newline at end of file diff --git a/lib.esm/_tests/test-transaction.js b/lib.esm/_tests/test-transaction.js new file mode 100644 index 000000000..ffee957dd --- /dev/null +++ b/lib.esm/_tests/test-transaction.js @@ -0,0 +1,258 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { Transaction } from "../index.js"; +const BN_0 = BigInt(0); +describe("Tests Unsigned Transaction Serializing", function () { + const tests = loadTests("transactions"); + for (const test of tests) { + it(`serialized unsigned legacy transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }); + // Use the testcase sans the chainId for a legacy test + if (txData.chainId != null && parseInt(txData.chainId) != 0) { + txData.chainId = "0x00"; + } + const tx = Transaction.from(txData); + assert.equal(tx.unsignedSerialized, test.unsignedLegacy, "unsignedLegacy"); + }); + } + for (const test of tests) { + // Unsupported parameters for EIP-155; i.e. unspecified chain ID + if (!test.unsignedEip155) { + continue; + } + it(`serialized unsigned EIP-155 transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }); + const tx = Transaction.from(txData); + assert.equal(tx.unsignedSerialized, test.unsignedEip155, "unsignedEip155"); + }); + } + for (const test of tests) { + it(`serialized unsigned Berlin transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 1, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }); + const tx = Transaction.from(txData); + assert.equal(tx.unsignedSerialized, test.unsignedBerlin, "unsignedBerlin"); + }); + } + for (const test of tests) { + it(`serialized unsigned London transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { type: 2 }); + const tx = Transaction.from(txData); + assert.equal(tx.unsignedSerialized, test.unsignedLondon, "unsignedLondon"); + }); + } +}); +describe("Tests Signed Transaction Serializing", function () { + const tests = loadTests("transactions"); + for (const test of tests) { + it(`serialized signed legacy transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined, + signature: test.signatureLegacy + }); + // Use the testcase sans the chainId for a legacy test + if (txData.chainId != null && parseInt(txData.chainId) != 0) { + txData.chainId = "0x00"; + } + const tx = Transaction.from(txData); + assert.equal(tx.serialized, test.signedLegacy, "signedLegacy"); + }); + } + for (const test of tests) { + if (!test.unsignedEip155) { + continue; + } + it(`serialized signed EIP-155 transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 0, + accessList: undefined, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined, + signature: test.signatureEip155 + }); + const tx = Transaction.from(txData); + assert.equal(tx.serialized, test.signedEip155, "signedEip155"); + }); + } + for (const test of tests) { + it(`serialized signed Berlin transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 1, + maxFeePerGas: undefined, + maxPriorityFeePerGas: undefined + }, { signature: test.signatureBerlin }); + const tx = Transaction.from(txData); + assert.equal(tx.serialized, test.signedBerlin, "signedBerlin"); + }); + } + for (const test of tests) { + it(`serialized signed London transaction: ${test.name}`, function () { + const txData = Object.assign({}, test.transaction, { + type: 2, + signature: test.signatureLondon + }); + const tx = Transaction.from(txData); + assert.equal(tx.serialized, test.signedLondon, "signedLondon"); + }); + } +}); +function assertTxUint(actual, _expected, name) { + const expected = (_expected != null ? BigInt(_expected) : null); + assert.equal(actual, expected, name); +} +function assertTxEqual(actual, expected) { + assert.equal(actual.to, expected.to, "to"); + assert.equal(actual.nonce, expected.nonce, "nonce"); + assertTxUint(actual.gasLimit, expected.gasLimit, "gasLimit"); + assertTxUint(actual.gasPrice, expected.gasPrice, "gasPrice"); + assertTxUint(actual.maxFeePerGas, expected.maxFeePerGas, "maxFeePerGas"); + assertTxUint(actual.maxPriorityFeePerGas, expected.maxPriorityFeePerGas, "maxPriorityFeePerGas"); + assert.equal(actual.data, expected.data, "data"); + assertTxUint(actual.value, expected.value, "value"); + if (expected.accessList) { + assert.equal(JSON.stringify(actual.accessList), JSON.stringify(expected.accessList), "accessList"); + } + else { + assert.equal(actual.accessList, null, "accessList:!null"); + } + assertTxUint(actual.chainId, expected.chainId, "chainId"); +} +function addDefault(tx, key, defaultValue) { + if (tx[key] == null) { + tx[key] = defaultValue; + } +} +function addDefaults(tx) { + tx = Object.assign({}, tx); + addDefault(tx, "nonce", 0); + addDefault(tx, "gasLimit", BN_0); + addDefault(tx, "gasPrice", BN_0); + addDefault(tx, "maxFeePerGas", BN_0); + addDefault(tx, "maxPriorityFeePerGas", BN_0); + addDefault(tx, "value", BN_0); + addDefault(tx, "data", "0x"); + addDefault(tx, "accessList", []); + addDefault(tx, "chainId", BN_0); + return tx; +} +describe("Tests Unsigned Transaction Parsing", function () { + const tests = loadTests("transactions"); + for (const test of tests) { + it(`parses unsigned legacy transaction: ${test.name}`, function () { + const tx = Transaction.from(test.unsignedLegacy); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + expected.chainId = BN_0; + assertTxEqual(tx, expected); + }); + } + for (const test of tests) { + if (!test.unsignedEip155) { + continue; + } + it(`parses unsigned EIP-155 transaction: ${test.name}`, function () { + const tx = Transaction.from(test.unsignedEip155); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + assertTxEqual(tx, expected); + }); + } + for (const test of tests) { + it(`parses unsigned Berlin transaction: ${test.name}`, function () { + const tx = Transaction.from(test.unsignedBerlin); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + assertTxEqual(tx, expected); + }); + } + for (const test of tests) { + it(`parses unsigned London transaction: ${test.name}`, function () { + const tx = Transaction.from(test.unsignedLondon); + const expected = addDefaults(test.transaction); + expected.gasPrice = null; + assertTxEqual(tx, expected); + }); + } +}); +describe("Tests Signed Transaction Parsing", function () { + const tests = loadTests("transactions"); + for (const test of tests) { + it(`parses signed legacy transaction: ${test.name}`, function () { + const tx = Transaction.from(test.signedLegacy); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + expected.chainId = BN_0; + assertTxEqual(tx, expected); + assert.ok(!!tx.signature, "signature:!null"); + assert.equal(tx.signature.r, test.signatureLegacy.r, "signature.r"); + assert.equal(tx.signature.s, test.signatureLegacy.s, "signature.s"); + assert.equal(BigInt(tx.signature.v), BigInt(test.signatureLegacy.v), "signature.v"); + }); + } + for (const test of tests) { + if (!test.unsignedEip155) { + continue; + } + it(`parses signed EIP-155 transaction: ${test.name}`, function () { + const tx = Transaction.from(test.signedEip155); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + expected.accessList = null; + assertTxEqual(tx, expected); + assert.ok(!!tx.signature, "signature:!null"); + assert.equal(tx.signature.r, test.signatureEip155.r, "signature.r"); + assert.equal(tx.signature.s, test.signatureEip155.s, "signature.s"); + assert.equal(tx.signature.networkV, BigInt(test.signatureEip155.v), "signature.v"); + }); + } + for (const test of tests) { + it(`parses signed Berlin transaction: ${test.name}`, function () { + const tx = Transaction.from(test.signedBerlin); + const expected = addDefaults(test.transaction); + expected.maxFeePerGas = null; + expected.maxPriorityFeePerGas = null; + assertTxEqual(tx, expected); + assert.ok(!!tx.signature, "signature:!null"); + assert.equal(tx.signature.r, test.signatureBerlin.r, "signature.r"); + assert.equal(tx.signature.s, test.signatureBerlin.s, "signature.s"); + assert.equal(tx.signature.yParity, parseInt(test.signatureBerlin.v), "signature.v"); + }); + } + for (const test of tests) { + it(`parses signed London transaction: ${test.name}`, function () { + const tx = Transaction.from(test.signedLondon); + const expected = addDefaults(test.transaction); + expected.gasPrice = null; + assertTxEqual(tx, expected); + assert.ok(!!tx.signature, "signature:!null"); + assert.equal(tx.signature.r, test.signatureLondon.r, "signature.r"); + assert.equal(tx.signature.s, test.signatureLondon.s, "signature.s"); + assert.equal(tx.signature.yParity, parseInt(test.signatureLondon.v), "signature.v"); + }); + } +}); +//# sourceMappingURL=test-transaction.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-transaction.js.map b/lib.esm/_tests/test-transaction.js.map new file mode 100644 index 000000000..278c138c5 --- /dev/null +++ b/lib.esm/_tests/test-transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-transaction.js","sourceRoot":"","sources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IAAI,CAAC;YAEzB,aAAa,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;YAE5B,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAA;YAC5C,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;YACpE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;YACpE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;QACxF,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet-hd.js b/lib.esm/_tests/test-wallet-hd.js new file mode 100644 index 000000000..1b42585b3 --- /dev/null +++ b/lib.esm/_tests/test-wallet-hd.js @@ -0,0 +1,120 @@ +import assert from "assert"; +import { wordlists } from "../wordlists/wordlists.js"; +import { loadTests } from "./utils.js"; +import { HDNodeWallet, HDNodeVoidWallet, Mnemonic } from "../index.js"; +const decoder = new TextDecoder(); +function fromHex(hex) { + const data = Buffer.from(hex.substring(2), "hex"); + return decoder.decode(data); +} +describe("Test HDWallets", function () { + function checkWallet(wallet, test) { + assert.equal(wallet.chainCode, test.chainCode, "chainCode"); + assert.equal(wallet.depth, test.depth, "depth"); + assert.equal(wallet.index, test.index, "index"); + assert.equal(wallet.fingerprint, test.fingerprint, "fingerprint"); + assert.equal(wallet.parentFingerprint, test.parentFingerprint, "parentFingerprint"); + assert.equal(wallet.publicKey, test.publicKey, "publicKey"); + if (wallet instanceof HDNodeWallet) { + assert.equal(wallet.extendedKey, test.xpriv, "xpriv"); + assert.equal(wallet.privateKey, test.privateKey, "privateKey"); + assert.equal(wallet.neuter().extendedKey, test.xpub, "xpub"); + } + else if (wallet instanceof HDNodeVoidWallet) { + assert.equal(wallet.extendedKey, test.xpub, "xpub"); + } + } + const tests = loadTests("mnemonics"); + const checks = []; + tests.forEach((test) => { + // The phrase and password are stored in the test as hex so they + // are safe as ascii7 values for viewing, printing, etc. + const phrase = fromHex(test.phrase); + const password = fromHex(test.password); + const wordlist = wordlists[test.locale]; + if (wordlist == null) { + it(`tests ${test.name}`, function () { + this.skip(); + }); + return; + } + const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); + function checkMnemonic(actual) { + assert.equal(actual.phrase, phrase, "phrase"); + assert.equal(actual.password, password, "password"); + assert.equal(actual.wordlist.locale, test.locale, "locale"); + assert.equal(actual.entropy, mnemonic.entropy, "entropy"); + assert.equal(actual.computeSeed(), mnemonic.computeSeed(), "seed"); + } + checks.push({ + phrase, password, wordlist, mnemonic, checkMnemonic, test + }); + }); + for (const { test, checkMnemonic, phrase, password, wordlist } of checks) { + it(`computes the HD keys by mnemonic: ${test.name}`, function () { + for (const subtest of test.nodes) { + const w = HDNodeWallet.fromPhrase(phrase, password, subtest.path, wordlist); + assert.ok(w instanceof HDNodeWallet, "instanceof HDNodeWallet"); + assert.equal(w.path, subtest.path, "path"); + checkWallet(w, subtest); + assert.ok(!!w.mnemonic, "has mnemonic"); + checkMnemonic(w.mnemonic); + } + }); + } + for (const { test } of checks) { + it(`computes the HD keys by entropy: ${test.name}`, function () { + const seedRoot = HDNodeWallet.fromSeed(test.seed); + for (const subtest of test.nodes) { + const w = seedRoot.derivePath(subtest.path); + assert.ok(w instanceof HDNodeWallet, "instanceof HDNodeWallet"); + assert.equal(w.path, subtest.path, "path"); + checkWallet(w, subtest); + assert.equal(w.mnemonic, null); + } + }); + } + for (const { test } of checks) { + it(`computes the HD keys by enxtended private key: ${test.name}`, function () { + for (const subtest of test.nodes) { + const w = HDNodeWallet.fromExtendedKey(subtest.xpriv); + assert.ok(w instanceof HDNodeWallet, "instanceof HDNodeWallet"); + checkWallet(w, subtest); + assert.equal(w.mnemonic, null); + } + }); + } + for (const { test, phrase, password, wordlist } of checks) { + it(`computes the neutered HD keys by paths: ${test.name}`, function () { + const root = HDNodeWallet.fromPhrase(phrase, password, "m", wordlist).neuter(); + for (const subtest of test.nodes) { + if (subtest.path.indexOf("'") >= 0) { + assert.throws(() => { + const w = root.derivePath(subtest.path); + console.log(w); + }, (error) => { + return (error.code === "UNSUPPORTED_OPERATION" && + error.message.match(/^cannot derive child of neutered node/) && + error.operation === "deriveChild"); + }); + } + else { + const w = root.derivePath(subtest.path); + assert.ok(w instanceof HDNodeVoidWallet, "instanceof HDNodeVoidWallet"); + assert.equal(w.path, subtest.path, "path"); + checkWallet(w, subtest); + } + } + }); + } + for (const { test } of checks) { + it(`computes the neutered HD keys by enxtended public key: ${test.name}`, function () { + for (const subtest of test.nodes) { + const w = HDNodeWallet.fromExtendedKey(subtest.xpub); + assert.ok(w instanceof HDNodeVoidWallet, "instanceof HDNodeVoidWallet"); + checkWallet(w, subtest); + } + }); + } +}); +//# sourceMappingURL=test-wallet-hd.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet-hd.js.map b/lib.esm/_tests/test-wallet-hd.js.map new file mode 100644 index 000000000..35626b278 --- /dev/null +++ b/lib.esm/_tests/test-wallet-hd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet-hd.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet-hd.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAEtD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAcvE,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,S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No newline at end of file diff --git a/lib.esm/_tests/test-wallet-json.js b/lib.esm/_tests/test-wallet-json.js new file mode 100644 index 000000000..e42ea4152 --- /dev/null +++ b/lib.esm/_tests/test-wallet-json.js @@ -0,0 +1,59 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { decryptCrowdsaleJson, decryptKeystoreJson, decryptKeystoreJsonSync, Wallet } from "../index.js"; +describe("Tests JSON Wallet Formats", function () { + const tests = loadTests("wallets"); + tests.forEach((test) => { + if (test.type !== "crowdsale") { + return; + } + it(`tests decrypting Crowdsale JSON: ${test.name}`, async function () { + const password = Buffer.from(test.password.substring(2), "hex"); + const account = decryptCrowdsaleJson(test.content, password); + assert.equal(account.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + if (test.type !== "keystore") { + return; + } + it(`tests decrypting Keystore JSON (sync): ${test.name}`, function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const account = decryptKeystoreJsonSync(test.content, password); + //console.log(account); + assert.equal(account.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + if (test.type !== "keystore") { + return; + } + it(`tests decrypting Keystore JSON (async): ${test.name}`, async function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const account = await decryptKeystoreJson(test.content, password); + //console.log(account); + assert.equal(account.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + it(`tests decrypting JSON (sync): ${test.name}`, function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const wallet = Wallet.fromEncryptedJsonSync(test.content, password); + //console.log(wallet); + assert.equal(wallet.address, test.address, "address"); + }); + }); + tests.forEach((test) => { + it(`tests decrypting JSON (async): ${test.name}`, async function () { + this.timeout(20000); + const password = Buffer.from(test.password.substring(2), "hex"); + const wallet = await Wallet.fromEncryptedJson(test.content, password); + //console.log(wallet); + assert.equal(wallet.address, test.address, "address"); + }); + }); +}); +//# sourceMappingURL=test-wallet-json.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet-json.js.map b/lib.esm/_tests/test-wallet-json.js.map new file mode 100644 index 000000000..363e13960 --- /dev/null +++ b/lib.esm/_tests/test-wallet-json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet-json.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet-json.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,OAAO,EACH,oBAAoB,EACpB,mBAAmB,EAAE,uBAAuB,EAC5C,MAAM,EACT,MAAM,aAAa,CAAC;AAErB,QAAQ,CAAC,2BAA2B,EAAE;IACjC,MAAM,KAAK,GAAG,SAAS,CAAiB,SAAS,CAAC,CAAC;IACnD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,EAAE;YAAE,OAAO;SAAE;QAC1C,EAAE,CAAC,oCAAqC,IAAI,CAAC,IAAK,EAAE,EAAE,KAAK;YACvD,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAChE,MAAM,OAAO,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC7D,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,IAAI,IAAI,CAAC,IAAI,KAAK,UAAU,EAAE;YAAE,OAAO;SAAE;QACzC,EAAE,CAAC,0CAA2C,IAAI,CAAC,IAAK,EAAE,EAAE;YACxD,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,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AC;YAChE,MAAM,MAAM,GAAG,MAAM,CAAC,qBAAqB,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACpE,sBAAsB;YACtB,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC1D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACnB,EAAE,CAAC,kCAAmC,IAAI,CAAC,IAAK,EAAE,EAAE,KAAK;YACrD,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAChE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACtE,sBAAsB;YACtB,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC1D,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACR,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet-mnemonic.js b/lib.esm/_tests/test-wallet-mnemonic.js new file mode 100644 index 000000000..53796f421 --- /dev/null +++ b/lib.esm/_tests/test-wallet-mnemonic.js @@ -0,0 +1,121 @@ +import assert from "assert"; +import { sha256 } from "../crypto/index.js"; +import { toUtf8Bytes } from "../utils/utf8.js"; +import { wordlists } from "../wordlists/wordlists.js"; +import { Mnemonic } from "../index.js"; +import { loadTests } from "./utils.js"; +const decoder = new TextDecoder(); +function fromHex(hex) { + const data = Buffer.from(hex.substring(2), "hex"); + return decoder.decode(data); +} +function repeat(text, length) { + const result = []; + while (result.length < length) { + result.push(text); + } + return result; +} +describe("Tests Mnemonics", function () { + const tests = loadTests("mnemonics"); + function runTest(phrase, mnemonic, test) { + assert.ok(Mnemonic.isValidMnemonic(phrase, mnemonic.wordlist), "isValidMnemonic"); + if (test.locale === "en") { + assert.ok(Mnemonic.isValidMnemonic(phrase), "isValidMnemonic (default)"); + } + assert.equal(mnemonic.wordlist.locale, test.locale, "locale"); + assert.equal(mnemonic.entropy, test.entropy, "entropy"); + assert.equal(mnemonic.computeSeed(), test.seed, "seed"); + assert.equal(sha256(toUtf8Bytes(phrase)), test.phraseHash, "phraseHash"); + } + for (const test of tests) { + const wordlist = wordlists[test.locale]; + it(`computes mnemonic from phrase: ${test.name}`, function () { + if (wordlist == null) { + this.skip(); + return; + } + const phrase = fromHex(test.phrase); + const password = fromHex(test.password); + const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); + runTest(phrase, mnemonic, test); + }); + } + for (const test of tests) { + const wordlist = wordlists[test.locale]; + it(`computes mnemonic from entropy: ${test.name}`, function () { + if (wordlist == null) { + this.skip(); + return; + } + const phrase = fromHex(test.phrase); + const password = fromHex(test.password); + const mnemonic = Mnemonic.fromEntropy(test.entropy, password, wordlist); + runTest(phrase, mnemonic, test); + }); + } +}); +describe("Tests Bad Mnemonics Fail", function () { + const badLengths = [ + repeat("abandon", 9), + repeat("abandon", 16), + repeat("abandon", 27), // 27 words; too long + ]; + for (const _phrase of badLengths) { + const phrase = _phrase.join(" "); + it(`fails on invalid mnemonic length: ${_phrase.length}`, function () { + assert.ok(!Mnemonic.isValidMnemonic(phrase)); + assert.throws(function () { + Mnemonic.fromPhrase(phrase); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid mnemonic length/) && + error.argument === "mnemonic" && + error.value === "[ REDACTED ]"); + }); + }); + } + it("fails on invalid mnemonic word", function () { + const phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon wagmi"; + assert.ok(!Mnemonic.isValidMnemonic(phrase)); + assert.throws(function () { + Mnemonic.fromPhrase(phrase); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid mnemonic word at index 11/) && + error.argument === "mnemonic" && + error.value === "[ REDACTED ]"); + }); + }); + it("fails on invalid mnemonic checksum", function () { + const phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"; + assert.ok(!Mnemonic.isValidMnemonic(phrase)); + assert.throws(function () { + Mnemonic.fromPhrase(phrase); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid mnemonic checksum/) && + error.argument === "mnemonic" && + error.value === "[ REDACTED ]"); + }); + }); + const badEntropyLengths = [ + repeat("42", 12), + repeat("42", 15), + repeat("42", 36), // 36 bytes; too long + ]; + for (const _entropy of badEntropyLengths) { + const entropy = "0x" + _entropy.join(""); + it(`fails on invalid entropy length: ${_entropy.length}`, function () { + assert.throws(function () { + Mnemonic.fromEntropy(entropy); + }, function (error) { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid entropy size/) && + error.argument === "entropy" && + error.value === "[ REDACTED ]"); + }); + }); + } +}); +//# sourceMappingURL=test-wallet-mnemonic.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet-mnemonic.js.map b/lib.esm/_tests/test-wallet-mnemonic.js.map new file mode 100644 index 000000000..87ae0f2e6 --- /dev/null +++ b/lib.esm/_tests/test-wallet-mnemonic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet-mnemonic.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet-mnemonic.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAEtD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE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AkB;oBACrC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC;oBAC5C,KAAK,CAAC,QAAQ,KAAK,SAAS;oBAC5B,KAAK,CAAC,KAAK,KAAK,cAAc,CAAC,CAAC;YACxC,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet.js b/lib.esm/_tests/test-wallet.js new file mode 100644 index 000000000..95b693fb5 --- /dev/null +++ b/lib.esm/_tests/test-wallet.js @@ -0,0 +1,72 @@ +import assert from "assert"; +import { loadTests } from "./utils.js"; +import { Wallet } from "../index.js"; +describe("Test Private Key Wallet", function () { + const tests = loadTests("accounts"); + tests.forEach(({ name, privateKey, address }) => { + it(`creates wallet: ${name}`, function () { + const wallet = new Wallet(privateKey); + assert.equal(wallet.privateKey, privateKey); + assert.equal(wallet.address, address); + }); + }); +}); +describe("Test Transaction Signing", function () { + const tests = loadTests("transactions"); + for (const test of tests) { + it(`tests signing a legacy transaction: ${test.name}`, async function () { + const wallet = new Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 0, accessList: undefined, maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }); + // Use the testcase sans the chainId for a legacy test + if (txData.chainId != null && parseInt(txData.chainId) != 0) { + txData.chainId = "0x00"; + } + const signed = await wallet.signTransaction(txData); + assert.equal(signed, test.signedLegacy, "signedLegacy"); + }); + } + for (const test of tests) { + if (!test.signedEip155) { + continue; + } + it(`tests signing an EIP-155 transaction: ${test.name}`, async function () { + const wallet = new Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 0, accessList: undefined, maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }); + const signed = await wallet.signTransaction(txData); + assert.equal(signed, test.signedEip155, "signedEip155"); + }); + } + for (const test of tests) { + it(`tests signing a Berlin transaction: ${test.name}`, async function () { + const wallet = new Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 1, maxFeePerGas: undefined, maxPriorityFeePerGas: undefined }); + const signed = await wallet.signTransaction(txData); + assert.equal(signed, test.signedBerlin, "signedBerlin"); + }); + } + for (const test of tests) { + it(`tests signing a London transaction: ${test.name}`, async function () { + const wallet = new Wallet(test.privateKey); + const txData = Object.assign({}, test.transaction, { type: 2 }); + const signed = await wallet.signTransaction(txData); + assert.equal(signed, test.signedLondon, "signedLondon"); + }); + } +}); +describe("Test Message Signing (EIP-191)", function () { +}); +describe("Test Typed-Data Signing (EIP-712)", function () { + const tests = loadTests("typed-data"); + for (const test of tests) { + const { privateKey, signature } = test; + if (privateKey == null || signature == null) { + continue; + } + it(`tests signing typed-data: ${test.name}`, async function () { + const wallet = new Wallet(privateKey); + const sig = await wallet.signTypedData(test.domain, test.types, test.data); + assert.equal(sig, signature, "signature"); + }); + } +}); +//# sourceMappingURL=test-wallet.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-wallet.js.map b/lib.esm/_tests/test-wallet.js.map new file mode 100644 index 000000000..33cd73f4c --- /dev/null +++ b/lib.esm/_tests/test-wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wallet.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wallet.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAOvC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAGrC,QAAQ,CAAC,yBAAyB,EAAE;IAChC,MAAM,KAAK,GAAG,SAAS,CAAkB,UAAU,CAAC,CAAC;IAErD,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,EAAE,EAAE;QAC5C,EAAE,CAAC,mBAAoB,IAAK,EAAE,EAAE;YAC5B,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,UAAU,CAAC,CAAC;YACtC,MAAM,CAAC,KAAK,CAAC,MAAM,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AAE,CAAC,CAAC;YACjE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;YACpD,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC;AAEH,QAAQ,CAAC,gCAAgC,EAAE;AAC3C,CAAC,CAAC,CAAC;AAEH,QAAQ,CAAC,mCAAmC,EAAE;IAC1C,MAAM,KAAK,GAAG,SAAS,CAAoB,YAAY,CAAC,CAAC;IACzD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACtB,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACvC,IAAI,UAAU,IAAI,IAAI,IAAI,SAAS,IAAI,IAAI,EAAE;YAAE,SAAS;SAAE;QAC1D,EAAE,CAAC,6BAA8B,IAAI,CAAC,IAAK,EAAE,EAAE,KAAK;YAChD,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,UAAU,CAAC,CAAC;YACtC,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;YAC3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;KACN;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-wordlists.js b/lib.esm/_tests/test-wordlists.js new file mode 100644 index 000000000..e54628a99 --- /dev/null +++ b/lib.esm/_tests/test-wordlists.js @@ -0,0 +1,66 @@ +import assert from 'assert'; +import { wordlists } from "../index.js"; +import { loadTests } from "./utils.js"; +describe('Check Wordlists', function () { + const tests = loadTests("wordlists"); + tests.forEach((test) => { + let wordlist = wordlists[test.locale]; + if (wordlist == null) { + return; + } + it(`matches wordlists: ${test.locale}`, function () { + const words = test.content.split('\n'); + let check = ""; + for (let i = 0; i < 2048; i++) { + let word = wordlist.getWord(i); + check += (word + "\n"); + assert.equal(word, words[i]); + assert.equal(wordlist.getWordIndex(word), i); + } + assert.equal(check, test.content); + }); + }); + tests.forEach((test) => { + let wordlist = wordlists[test.locale]; + if (wordlist == null) { + return; + } + it(`splitting and joining are equivalent: ${test.locale}`, function () { + const words = []; + for (let i = 0; i < 12; i++) { + words.push(wordlist.getWord(i)); + } + const phrase = wordlist.join(words); + const words2 = wordlist.split(phrase); + const phrase2 = wordlist.join(words2); + assert.deepStrictEqual(words2, words, "split words"); + assert.deepStrictEqual(phrase2, phrase, "re-joined words"); + }); + }); + tests.forEach((test) => { + let wordlist = wordlists[test.locale]; + if (wordlist == null) { + return; + } + it(`handles out-of-range values: ${test.locale}`, function () { + assert.equal(wordlist.getWordIndex("foobar"), -1); + assert.throws(() => { + wordlist.getWord(-1); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid word index/) && + error.argument === "index" && + error.value === -1); + }); + assert.throws(() => { + wordlist.getWord(2048); + }, (error) => { + return (error.code === "INVALID_ARGUMENT" && + error.message.match(/^invalid word index/) && + error.argument === "index" && + error.value === 2048); + }); + }); + }); +}); +//# sourceMappingURL=test-wordlists.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-wordlists.js.map b/lib.esm/_tests/test-wordlists.js.map new file mode 100644 index 000000000..aae395069 --- /dev/null +++ b/lib.esm/_tests/test-wordlists.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-wordlists.js","sourceRoot":"","sources":["../../src.ts/_tests/test-wordlists.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAKvC,QAAQ,CAAC,iBAAiB,EAAE;IACxB,MAAM,KAA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M,CAAC,GAAG,EAAE;gBACf,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YAC3B,CAAC,EAAE,CAAC,KAAU,EAAE,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,kBAAkB;oBACrC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC;oBAC1C,KAAK,CAAC,QAAQ,KAAK,OAAO;oBAC1B,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC;YAC9B,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IAEP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/types.js b/lib.esm/_tests/types.js new file mode 100644 index 000000000..4f418f717 --- /dev/null +++ b/lib.esm/_tests/types.js @@ -0,0 +1,3 @@ +; +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/lib.esm/_tests/types.js.map b/lib.esm/_tests/types.js.map new file mode 100644 index 000000000..fc90723d9 --- /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":"AAiOC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/utils.js b/lib.esm/_tests/utils.js new file mode 100644 index 000000000..510c6d356 --- /dev/null +++ b/lib.esm/_tests/utils.js @@ -0,0 +1,32 @@ +import fs from "fs"; +import path from "path"; +import zlib from 'zlib'; +// Find the package root (based on the nyc output/ folder) +const root = (function () { + let root = process.cwd(); + while (true) { + if (fs.existsSync(path.join(root, "output"))) { + return root; + } + const parent = path.join(root, ".."); + if (parent === root) { + break; + } + root = parent; + } + throw new Error("could not find root"); +})(); +// Load the tests +export function loadTests(tag) { + const filename = path.resolve(root, "testcases", tag + ".json.gz"); + return JSON.parse(zlib.gunzipSync(fs.readFileSync(filename)).toString()); +} +export function log(context, text) { + if (context && context.test && typeof (context.test._ethersLog) === "function") { + context.test._ethersLog(text); + } + else { + console.log(text); + } +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib.esm/_tests/utils.js.map b/lib.esm/_tests/utils.js.map new file mode 100644 index 000000000..ec003918e --- /dev/null +++ b/lib.esm/_tests/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src.ts/_tests/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,0DAA0D;AAC1D,MAAM,IAAI,GAAG,CAAC;IACV,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAEzB,OAAO,IAAI,EAAE;QACT,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QAC9D,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACrC,IAAI,MAAM,KAAK,IAAI,EAAE;YAAE,MAAM;SAAE;QAC/B,IAAI,GAAG,MAAM,CAAC;KACjB;IAED,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC3C,CAAC,CAAC,EAAE,CAAC;AAEL,iBAAiB;AACjB,MAAM,UAAU,SAAS,CAAI,GAAW;IACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,GAAG,UAAU,CAAC,CAAC;IACnE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,GAAG,CAAC,OAAY,EAAE,IAAY;IAC1C,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,IAAI,OAAM,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,UAAU,EAAE;QAC3E,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;KACjC;SAAM;QACH,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;KACrB;AACL,CAAC"} \ No newline at end of file diff --git a/lib.esm/_version.js b/lib.esm/_version.js new file mode 100644 index 000000000..ed49b38cc --- /dev/null +++ b/lib.esm/_version.js @@ -0,0 +1,2 @@ +export const version = "6.0.0-beta-exports.0"; +//# sourceMappingURL=_version.js.map \ No newline at end of file diff --git a/lib.esm/_version.js.map b/lib.esm/_version.js.map new file mode 100644 index 000000000..5c31b8b69 --- /dev/null +++ b/lib.esm/_version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_version.js","sourceRoot":"","sources":["../src.ts/_version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,sBAAsB,CAAC"} \ No newline at end of file diff --git a/lib.esm/abi/abi-coder.js b/lib.esm/abi/abi-coder.js new file mode 100644 index 000000000..0a271acbe --- /dev/null +++ b/lib.esm/abi/abi-coder.js @@ -0,0 +1,76 @@ +// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI +import { logger } from "../utils/logger.js"; +import { Reader, Writer } from "./coders/abstract-coder.js"; +import { AddressCoder } from "./coders/address.js"; +import { ArrayCoder } from "./coders/array.js"; +import { BooleanCoder } from "./coders/boolean.js"; +import { BytesCoder } from "./coders/bytes.js"; +import { FixedBytesCoder } from "./coders/fixed-bytes.js"; +import { NullCoder } from "./coders/null.js"; +import { NumberCoder } from "./coders/number.js"; +import { StringCoder } from "./coders/string.js"; +import { TupleCoder } from "./coders/tuple.js"; +import { ParamType } from "./fragments.js"; +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +export class AbiCoder { + #getCoder(param) { + if (param.isArray()) { + return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); + } + if (param.isTuple()) { + return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name); + } + switch (param.baseType) { + case "address": + return new AddressCoder(param.name); + case "bool": + return new BooleanCoder(param.name); + case "string": + return new StringCoder(param.name); + case "bytes": + return new BytesCoder(param.name); + case "": + return new NullCoder(param.name); + } + // u?int[0-9]* + let match = param.type.match(paramTypeNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if (size === 0 || size > 256 || (size % 8) !== 0) { + logger.throwArgumentError("invalid " + match[1] + " bit length", "param", param); + } + return new NumberCoder(size / 8, (match[1] === "int"), param.name); + } + // bytes[0-9]+ + match = param.type.match(paramTypeBytes); + if (match) { + let size = parseInt(match[1]); + if (size === 0 || size > 32) { + logger.throwArgumentError("invalid bytes length", "param", param); + } + return new FixedBytesCoder(size, param.name); + } + return logger.throwArgumentError("invalid type", "type", param.type); + } + getDefaultValue(types) { + const coders = types.map((type) => this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.defaultValue(); + } + encode(types, values) { + logger.assertArgumentCount(values.length, types.length, "types/values length mismatch"); + const coders = types.map((type) => this.#getCoder(ParamType.from(type))); + const coder = (new TupleCoder(coders, "_")); + const writer = new Writer(); + coder.encode(writer, values); + return writer.data; + } + decode(types, data, loose) { + const coders = types.map((type) => this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.decode(new Reader(data, loose)); + } +} +export const defaultAbiCoder = new AbiCoder(); +//# sourceMappingURL=abi-coder.js.map \ No newline at end of file diff --git a/lib.esm/abi/abi-coder.js.map b/lib.esm/abi/abi-coder.js.map new file mode 100644 index 000000000..a3c80e085 --- /dev/null +++ b/lib.esm/abi/abi-coder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abi-coder.js","sourceRoot":"","sources":["../../src.ts/abi/abi-coder.ts"],"names":[],"mappings":"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IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvF,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC1C,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;IACjD,CAAC;CACJ;AAGD,MAAM,CAAC,MAAM,eAAe,GAAa,IAAI,QAAQ,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/abi/bytes32.js b/lib.esm/abi/bytes32.js new file mode 100644 index 000000000..350251db7 --- /dev/null +++ b/lib.esm/abi/bytes32.js @@ -0,0 +1,31 @@ +import { zeroPadBytes } from "../utils/data.js"; +import { logger } from "../utils/logger.js"; +import { toUtf8Bytes, toUtf8String } from "../utils/utf8.js"; +export function formatBytes32String(text) { + // Get the bytes + const bytes = toUtf8Bytes(text); + // Check we have room for null-termination + if (bytes.length > 31) { + throw new Error("bytes32 string must be less than 32 bytes"); + } + // Zero-pad (implicitly null-terminates) + return zeroPadBytes(bytes, 32); +} +export function parseBytes32String(_bytes) { + const data = logger.getBytes(_bytes, "bytes"); + // Must be 32 bytes with a null-termination + if (data.length !== 32) { + throw new Error("invalid bytes32 - not 32 bytes long"); + } + if (data[31] !== 0) { + throw new Error("invalid bytes32 string - no null terminator"); + } + // Find the null termination + let length = 31; + while (data[length - 1] === 0) { + length--; + } + // Determine the string value + return toUtf8String(data.slice(0, length)); +} +//# sourceMappingURL=bytes32.js.map \ No newline at end of file diff --git a/lib.esm/abi/bytes32.js.map b/lib.esm/abi/bytes32.js.map new file mode 100644 index 000000000..bb6a93334 --- /dev/null +++ b/lib.esm/abi/bytes32.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes32.js","sourceRoot":"","sources":["../../src.ts/abi/bytes32.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEhD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAK7D,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAE5C,gBAAgB;IAChB,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;IAEhC,0CAA0C;IAC1C,IAAI,KAAK,CAAC,MAAM,GAAG,EAAE,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAAE;IAExF,wCAAwC;IACxC,OAAO,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,MAAiB;IAChD,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE9C,2CAA2C;IAC3C,IAAI,IAAI,CAAC,MAAM,KAAK,EAAE,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;KAAE;IACnF,IAAI,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAAE;IAEvF,4BAA4B;IAC5B,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE;QAAE,MAAM,EAAE,CAAC;KAAE;IAE5C,6BAA6B;IAC7B,OAAO,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AAC/C,CAAC"} \ No newline at end of file diff --git a/lib.esm/abi/coders/abstract-coder.js b/lib.esm/abi/coders/abstract-coder.js new file mode 100644 index 000000000..da0c8c54c --- /dev/null +++ b/lib.esm/abi/coders/abstract-coder.js @@ -0,0 +1,265 @@ +import { toArray, toBigInt, toNumber } from "../../utils/maths.js"; +import { concat, hexlify } from "../../utils/data.js"; +import { defineProperties } from "../../utils/properties.js"; +import { logger } from "../../utils/logger.js"; +export const WordSize = 32; +const Padding = new Uint8Array(WordSize); +// Properties used to immediate pass through to the underlying object +// - `then` is used to detect if an object is a Promise for await +const passProperties = ["then"]; +const _guard = {}; +export class Result extends Array { + #indices; + constructor(guard, items, keys) { + logger.assertPrivate(guard, _guard, "Result"); + super(...items); + // Name lookup table + this.#indices = new Map(); + if (keys) { + keys.forEach((key, index) => { + if (key == null) { + return; + } + if (this.#indices.has(key)) { + (this.#indices.get(key)).push(index); + } + else { + this.#indices.set(key, [index]); + } + }); + } + Object.freeze(this); + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "string") { + if (prop.match(/^[0-9]+$/)) { + const index = logger.getNumber(prop, "%index"); + if (index < 0 || index >= this.length) { + throw new RangeError("out of result range"); + } + const item = target[index]; + if (item instanceof Error) { + this.#throwError(`index ${index}`, item); + } + return item; + } + // Pass important checks (like `then` for Promise) through + if (prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + // Something that could be a result keyword value + if (!(prop in target)) { + return target.getValue(prop); + } + } + return Reflect.get(target, prop, receiver); + } + }); + } + /* + toJSON(): any { + if (this.#indices.length === this.length) { + const result: Record = { }; + for (const key of this.#indices.keys()) { + result[key] = ths.getValue(key); + } + return result; + } + return this; + } + */ + slice(start, end) { + if (start == null) { + start = 0; + } + if (end == null) { + end = this.length; + } + const result = []; + for (let i = start; i < end; i++) { + let value; + try { + value = this[i]; + } + catch (error) { + value = error.error; + } + result.push(value); + } + return result; + } + #throwError(name, error) { + const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); + wrapped.error = error; + throw wrapped; + } + getValue(name) { + const index = this.#indices.get(name); + if (index != null && index.length === 1) { + const item = this[index[0]]; + if (item instanceof Error) { + this.#throwError(`property ${JSON.stringify(name)}`, item); + } + return item; + } + throw new Error(`no named parameter: ${JSON.stringify(name)}`); + } + static fromItems(items, keys) { + return new Result(_guard, items, keys); + } +} +export function checkResultErrors(result) { + // Find the first error (if any) + const errors = []; + const checkErrors = function (path, object) { + if (!Array.isArray(object)) { + return; + } + for (let key in object) { + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object[key]); + } + catch (error) { + errors.push({ path: childPath, error: error }); + } + } + }; + checkErrors([], result); + return errors; +} +function getValue(value) { + let bytes = toArray(value); + if (bytes.length > WordSize) { + logger.throwError("value out-of-bounds", "BUFFER_OVERRUN", { + buffer: bytes, + length: WordSize, + offset: bytes.length + }); + } + if (bytes.length !== WordSize) { + bytes = logger.getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes])); + } + return bytes; +} +export class Coder { + // The coder name: + // - address, uint256, tuple, array, etc. + name; + // The fully expanded type, including composite types: + // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. + type; + // The localName bound in the signature, in this example it is "baz": + // - tuple(address foo, uint bar) baz + localName; + // Whether this type is dynamic: + // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. + // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) + dynamic; + constructor(name, type, localName, dynamic) { + defineProperties(this, { name, type, localName, dynamic }, { + name: "string", type: "string", localName: "string", dynamic: "boolean" + }); + } + _throwError(message, value) { + return logger.throwArgumentError(message, this.localName, value); + } +} +export class Writer { + // An array of WordSize lengthed objects to concatenation + #data; + #dataLength; + constructor() { + this.#data = []; + this.#dataLength = 0; + } + get data() { + return concat(this.#data); + } + get length() { return this.#dataLength; } + #writeData(data) { + this.#data.push(data); + this.#dataLength += data.length; + return data.length; + } + appendWriter(writer) { + return this.#writeData(logger.getBytesCopy(writer.data)); + } + // Arrayish item; pad on the right to *nearest* WordSize + writeBytes(value) { + let bytes = logger.getBytesCopy(value); + const paddingOffset = bytes.length % WordSize; + if (paddingOffset) { + bytes = logger.getBytesCopy(concat([bytes, Padding.slice(paddingOffset)])); + } + return this.#writeData(bytes); + } + // Numeric item; pad on the left *to* WordSize + writeValue(value) { + return this.#writeData(getValue(value)); + } + // Inserts a numeric place-holder, returning a callback that can + // be used to asjust the value later + writeUpdatableValue() { + const offset = this.#data.length; + this.#data.push(Padding); + this.#dataLength += WordSize; + return (value) => { + this.#data[offset] = getValue(value); + }; + } +} +export class Reader { + // Allows incomplete unpadded data to be read; otherwise an error + // is raised if attempting to overrun the buffer. This is required + // to deal with an old Solidity bug, in which event data for + // external (not public thoguh) was tightly packed. + allowLoose; + #data; + #offset; + constructor(data, allowLoose) { + defineProperties(this, { allowLoose: !!allowLoose }); + this.#data = logger.getBytesCopy(data); + this.#offset = 0; + } + get data() { return hexlify(this.#data); } + get dataLength() { return this.#data.length; } + get consumed() { return this.#offset; } + get bytes() { return new Uint8Array(this.#data); } + #peekBytes(offset, length, loose) { + let alignedLength = Math.ceil(length / WordSize) * WordSize; + if (this.#offset + alignedLength > this.#data.length) { + if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { + alignedLength = length; + } + else { + logger.throwError("data out-of-bounds", "BUFFER_OVERRUN", { + buffer: logger.getBytesCopy(this.#data), + length: this.#data.length, + offset: this.#offset + alignedLength + }); + } + } + return this.#data.slice(this.#offset, this.#offset + alignedLength); + } + // Create a sub-reader with the same underlying data, but offset + subReader(offset) { + return new Reader(this.#data.slice(this.#offset + offset), this.allowLoose); + } + // Read bytes + readBytes(length, loose) { + let bytes = this.#peekBytes(0, length, !!loose); + this.#offset += bytes.length; + // @TODO: Make sure the length..end bytes are all 0? + return bytes.slice(0, length); + } + // Read a numeric values + readValue() { + return toBigInt(this.readBytes(WordSize)); + } + readIndex() { + return toNumber(this.readBytes(WordSize)); + } +} +//# sourceMappingURL=abstract-coder.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/abstract-coder.js.map b/lib.esm/abi/coders/abstract-coder.js.map new file mode 100644 index 000000000..ebc553be6 --- /dev/null +++ b/lib.esm/abi/coders/abstract-coder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-co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GAAG,aAAa;iBACvC,CAAC,CAAC;aACN;SACJ;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,CAAA;IACvE,CAAC;IAED,gEAAgE;IAChE,SAAS,CAAC,MAAc;QACpB,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAChF,CAAC;IAED,aAAa;IACb,SAAS,CAAC,MAAc,EAAE,KAAe;QACrC,IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC;QAChD,IAAI,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC;QAC7B,oDAAoD;QACpD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IAClC,CAAC;IAED,wBAAwB;IACxB,SAAS;QACL,OAAO,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC9C,CAAC;IAED,SAAS;QACL,OAAO,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC9C,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/address.js b/lib.esm/abi/coders/address.js new file mode 100644 index 000000000..289ce8f5b --- /dev/null +++ b/lib.esm/abi/coders/address.js @@ -0,0 +1,26 @@ +import { getAddress } from "../../address/index.js"; +import { toHex } from "../../utils/maths.js"; +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +export class AddressCoder extends Coder { + constructor(localName) { + super("address", "address", localName, false); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, _value) { + let value = Typed.dereference(_value, "string"); + try { + value = getAddress(value); + } + catch (error) { + return this._throwError(error.message, _value); + } + return writer.writeValue(value); + } + decode(reader) { + return getAddress(toHex(reader.readValue(), 20)); + } +} +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/address.js.map b/lib.esm/abi/coders/address.js.map new file mode 100644 index 000000000..d752756a0 --- /dev/null +++ b/lib.esm/abi/coders/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/address.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAE7C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAK5C,MAAM,OAAO,YAAa,SAAQ,KAAK;IAEnC,YAAY,SAAiB;QACzB,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAClD,CAAC;IAED,YAAY;QACR,OAAO,4CAA4C,CAAC;IACxD,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAsB;QACzC,IAAI,KAAK,GAAG,KAAK,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChD,IAAI;YACA,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;SAC7B;QAAC,OAAO,KAAU,EAAE;YACjB,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;SAClD;QACD,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;IACrD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/anonymous.js b/lib.esm/abi/coders/anonymous.js new file mode 100644 index 000000000..af3229ab3 --- /dev/null +++ b/lib.esm/abi/coders/anonymous.js @@ -0,0 +1,19 @@ +import { Coder } from "./abstract-coder.js"; +// Clones the functionality of an existing Coder, but without a localName +export class AnonymousCoder extends Coder { + coder; + constructor(coder) { + super(coder.name, coder.type, "_", coder.dynamic); + this.coder = coder; + } + defaultValue() { + return this.coder.defaultValue(); + } + encode(writer, value) { + return this.coder.encode(writer, value); + } + decode(reader) { + return this.coder.decode(reader); + } +} +//# sourceMappingURL=anonymous.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/anonymous.js.map b/lib.esm/abi/coders/anonymous.js.map new file mode 100644 index 000000000..b233e85a6 --- /dev/null +++ b/lib.esm/abi/coders/anonymous.js.map @@ -0,0 +1 @@ +{"version":3,"file":"anonymous.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/anonymous.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAI5C,yEAAyE;AACzE,MAAM,OAAO,cAAe,SAAQ,KAAK;IAC7B,KAAK,CAAQ;IAErB,YAAY,KAAY;QACpB,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,YAAY;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;IACrC,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,KAAU;QAC7B,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/array.js b/lib.esm/abi/coders/array.js new file mode 100644 index 000000000..1812b34b7 --- /dev/null +++ b/lib.esm/abi/coders/array.js @@ -0,0 +1,172 @@ +import { defineProperties } from "../../utils/properties.js"; +import { isError } from "../../utils/errors.js"; +import { logger } from "../../utils/logger.js"; +import { Typed } from "../typed.js"; +import { Coder, Result, WordSize, Writer } from "./abstract-coder.js"; +import { AnonymousCoder } from "./anonymous.js"; +export function pack(writer, coders, values) { + let arrayValues = []; + if (Array.isArray(values)) { + arrayValues = values; + } + else if (values && typeof (values) === "object") { + let unique = {}; + arrayValues = coders.map((coder) => { + const name = coder.localName; + if (!name) { + logger.throwError("cannot encode object for signature with missing names", "INVALID_ARGUMENT", { + argument: "values", + info: { coder }, + value: values + }); + } + if (unique[name]) { + logger.throwError("cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { + argument: "values", + info: { coder }, + value: values + }); + } + unique[name] = true; + return values[name]; + }); + } + else { + logger.throwArgumentError("invalid tuple value", "tuple", values); + } + if (coders.length !== arrayValues.length) { + logger.throwArgumentError("types/value length mismatch", "tuple", values); + } + let staticWriter = new Writer(); + let dynamicWriter = new Writer(); + let updateFuncs = []; + coders.forEach((coder, index) => { + let value = arrayValues[index]; + if (coder.dynamic) { + // Get current dynamic offset (for the future pointer) + let dynamicOffset = dynamicWriter.length; + // Encode the dynamic value into the dynamicWriter + coder.encode(dynamicWriter, value); + // Prepare to populate the correct offset once we are done + let updateFunc = staticWriter.writeUpdatableValue(); + updateFuncs.push((baseOffset) => { + updateFunc(baseOffset + dynamicOffset); + }); + } + else { + coder.encode(staticWriter, value); + } + }); + // Backfill all the dynamic offsets, now that we know the static length + updateFuncs.forEach((func) => { func(staticWriter.length); }); + let length = writer.appendWriter(staticWriter); + length += writer.appendWriter(dynamicWriter); + return length; +} +export function unpack(reader, coders) { + let values = []; + let keys = []; + // A reader anchored to this base + let baseReader = reader.subReader(0); + coders.forEach((coder) => { + let value = null; + if (coder.dynamic) { + let offset = reader.readIndex(); + let offsetReader = baseReader.subReader(offset); + try { + value = coder.decode(offsetReader); + } + catch (error) { + // Cannot recover from this + if (isError(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + else { + try { + value = coder.decode(reader); + } + catch (error) { + // Cannot recover from this + if (isError(error, "BUFFER_OVERRUN")) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + if (value == undefined) { + throw new Error("investigate"); + } + values.push(value); + keys.push(coder.localName || null); + }); + return Result.fromItems(values, keys); +} +export class ArrayCoder extends Coder { + coder; + length; + constructor(coder, length, localName) { + const type = (coder.type + "[" + (length >= 0 ? length : "") + "]"); + const dynamic = (length === -1 || coder.dynamic); + super("array", type, localName, dynamic); + defineProperties(this, { coder, length }); + } + defaultValue() { + // Verifies the child coder is valid (even if the array is dynamic or 0-length) + const defaultChild = this.coder.defaultValue(); + const result = []; + for (let i = 0; i < this.length; i++) { + result.push(defaultChild); + } + return result; + } + encode(writer, _value) { + const value = Typed.dereference(_value, "array"); + if (!Array.isArray(value)) { + this._throwError("expected array value", value); + } + let count = this.length; + if (count === -1) { + count = value.length; + writer.writeValue(value.length); + } + logger.assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : "")); + let coders = []; + for (let i = 0; i < value.length; i++) { + coders.push(this.coder); + } + return pack(writer, coders, value); + } + decode(reader) { + let count = this.length; + if (count === -1) { + count = reader.readIndex(); + // Check that there is *roughly* enough data to ensure + // stray random data is not being read as a length. Each + // slot requires at least 32 bytes for their value (or 32 + // bytes as a link to the data). This could use a much + // tighter bound, but we are erroring on the side of safety. + if (count * WordSize > reader.dataLength) { + logger.throwError("insufficient data length", "BUFFER_OVERRUN", { + buffer: reader.bytes, + offset: count * WordSize, + length: reader.dataLength + }); + } + } + let coders = []; + for (let i = 0; i < count; i++) { + coders.push(new AnonymousCoder(this.coder)); + } + return unpack(reader, coders); + } +} +//# sourceMappingURL=array.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/array.js.map b/lib.esm/abi/coders/array.js.map new file mode 100644 index 000000000..82583453d --- /dev/null +++ b/lib.esm/abi/coders/array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"array.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/array.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE/C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAKhD,MAAM,UAAU,IAAI,CAAC,MAAc,EAAE,MAA4B,EAAE,MAA8C;IAC7G,IAAI,WAAW,GAAe,EAAG,CAAC;IAElC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACxB,WAAW,GAAG,MAAM,CAAC;KAEvB;SAAM,IAAI,MAAM,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,EAAE;QAC9C,IAAI,MAAM,GAAkC,EAAG,CAAC;QAEhD,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;YAC/B,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC;YAC7B,IAAI,CAAC,IAAI,EAAE;gBACP,MAAM,CAAC,UAAU,CAAC,uDAAuD,EAAE,kBAAkB,EAAE;oBAC3F,QAAQ,EAAE,QAAQ;oBAClB,IAAI,EAAE,EAAE,KAAK,EAAE;oBACf,KAAK,EAAE,MAAM;iBAChB,CAAC,CAAC;aACN;YAED,IAAI,MAAM,CAAC,IAAI,CAAC,EAAE;gBACd,MAAM,CAAC,UAAU,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;IAED,MAAM,CAAC,MAAc;QACjB,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC;QACxB,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;YACd,KAAK,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;YAE3B,sDAAsD;YACtD,wDAAwD;YACxD,yDAAyD;YACzD,sDAAsD;YACtD,4DAA4D;YAC5D,IAAI,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC,UAAU,EAAE;gBACtC,MAAM,CAAC,UAAU,CAAC,0BAA0B,EAAE,gBAAgB,EAAE;oBAC5D,MAAM,EAAE,MAAM,CAAC,KAAK;oBACpB,MAAM,EAAE,KAAK,GAAG,QAAQ;oBACxB,MAAM,EAAE,MAAM,CAAC,UAAU;iBAC5B,CAAC,CAAC;aACN;SACJ;QACD,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YAAE,MAAM,CAAC,IAAI,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;SAAE;QAEhF,OAAO,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/boolean.js b/lib.esm/abi/coders/boolean.js new file mode 100644 index 000000000..081489ef4 --- /dev/null +++ b/lib.esm/abi/coders/boolean.js @@ -0,0 +1,18 @@ +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +export class BooleanCoder extends Coder { + constructor(localName) { + super("bool", "bool", localName, false); + } + defaultValue() { + return false; + } + encode(writer, _value) { + const value = Typed.dereference(_value, "bool"); + return writer.writeValue(value ? 1 : 0); + } + decode(reader) { + return !!reader.readValue(); + } +} +//# sourceMappingURL=boolean.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/boolean.js.map b/lib.esm/abi/coders/boolean.js.map new file mode 100644 index 000000000..02a7b25e2 --- /dev/null +++ b/lib.esm/abi/coders/boolean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/boolean.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAK5C,MAAM,OAAO,YAAa,SAAQ,KAAK;IAEnC,YAAY,SAAiB;QACzB,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED,YAAY;QACR,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAuB;QAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAChC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/bytes.js b/lib.esm/abi/coders/bytes.js new file mode 100644 index 000000000..a1965b17f --- /dev/null +++ b/lib.esm/abi/coders/bytes.js @@ -0,0 +1,29 @@ +import { logger } from "../../utils/logger.js"; +import { hexlify } from "../../utils/data.js"; +import { Coder } from "./abstract-coder.js"; +export class DynamicBytesCoder extends Coder { + constructor(type, localName) { + super(type, type, localName, true); + } + defaultValue() { + return "0x"; + } + encode(writer, value) { + value = logger.getBytesCopy(value); + let length = writer.writeValue(value.length); + length += writer.writeBytes(value); + return length; + } + decode(reader) { + return reader.readBytes(reader.readIndex(), true); + } +} +export class BytesCoder extends DynamicBytesCoder { + constructor(localName) { + super("bytes", localName); + } + decode(reader) { + return hexlify(super.decode(reader)); + } +} +//# sourceMappingURL=bytes.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/bytes.js.map b/lib.esm/abi/coders/bytes.js.map new file mode 100644 index 000000000..04c3a5db1 --- /dev/null +++ b/lib.esm/abi/coders/bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/bytes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAK5C,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IACxC,YAAY,IAAY,EAAE,SAAiB;QACxC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;IAED,YAAY;QACR,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,KAAU;QAC7B,KAAK,GAAG,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,MAAM,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,EAAE,EAAE,IAAI,CAAC,CAAC;IACtD,CAAC;CACJ;AAED,MAAM,OAAO,UAAW,SAAQ,iBAAiB;IAC7C,YAAY,SAAiB;QACzB,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IACzC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/fixed-bytes.js b/lib.esm/abi/coders/fixed-bytes.js new file mode 100644 index 000000000..f3aea7623 --- /dev/null +++ b/lib.esm/abi/coders/fixed-bytes.js @@ -0,0 +1,27 @@ +import { logger } from "../../utils/logger.js"; +import { hexlify } from "../../utils/data.js"; +import { defineProperties } from "../../utils/properties.js"; +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +export class FixedBytesCoder extends Coder { + size; + constructor(size, localName) { + let name = "bytes" + String(size); + super(name, name, localName, false); + defineProperties(this, { size }, { size: "number" }); + } + defaultValue() { + return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2); + } + encode(writer, _value) { + let data = logger.getBytesCopy(Typed.dereference(_value, this.type)); + if (data.length !== this.size) { + this._throwError("incorrect data length", _value); + } + return writer.writeBytes(data); + } + decode(reader) { + return hexlify(reader.readBytes(this.size)); + } +} +//# sourceMappingURL=fixed-bytes.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/fixed-bytes.js.map b/lib.esm/abi/coders/fixed-bytes.js.map new file mode 100644 index 000000000..d16a1c229 --- /dev/null +++ b/lib.esm/abi/coders/fixed-bytes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fixed-bytes.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/fixed-bytes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAO5C,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAC7B,IAAI,CAAU;IAEvB,YAAY,IAAY,EAAE,SAAiB;QACvC,IAAI,IAAI,GAAG,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAClC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QACpC,gBAAgB,CAAkB,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC1E,CAAC;IAED,YAAY;QACR,OAAO,CAAC,oEAAoE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;IAClH,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAyB;QAC5C,IAAI,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACrE,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE;YAAE,IAAI,CAAC,WAAW,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;SAAE;QACrF,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/null.js b/lib.esm/abi/coders/null.js new file mode 100644 index 000000000..893538917 --- /dev/null +++ b/lib.esm/abi/coders/null.js @@ -0,0 +1,21 @@ +import { Coder } from "./abstract-coder.js"; +const Empty = new Uint8Array([]); +export class NullCoder extends Coder { + constructor(localName) { + super("null", "", localName, false); + } + defaultValue() { + return null; + } + encode(writer, value) { + if (value != null) { + this._throwError("not null", value); + } + return writer.writeBytes(Empty); + } + decode(reader) { + reader.readBytes(0); + return null; + } +} +//# sourceMappingURL=null.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/null.js.map b/lib.esm/abi/coders/null.js.map new file mode 100644 index 000000000..b62fad710 --- /dev/null +++ b/lib.esm/abi/coders/null.js.map @@ -0,0 +1 @@ +{"version":3,"file":"null.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/null.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAG5C,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,EAAG,CAAC,CAAC;AAElC,MAAM,OAAO,SAAU,SAAQ,KAAK;IAEhC,YAAY,SAAiB;QACzB,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IACxC,CAAC;IAED,YAAY;QACR,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,KAAU;QAC7B,IAAI,KAAK,IAAI,IAAI,EAAE;YAAE,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;SAAE;QAC3D,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/number.js b/lib.esm/abi/coders/number.js new file mode 100644 index 000000000..74926cddf --- /dev/null +++ b/lib.esm/abi/coders/number.js @@ -0,0 +1,47 @@ +import { fromTwos, mask, toTwos } from "../../utils/maths.js"; +import { defineProperties } from "../../utils/properties.js"; +import { logger } from "../../utils/logger.js"; +import { Typed } from "../typed.js"; +import { Coder, WordSize } from "./abstract-coder.js"; +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +export class NumberCoder extends Coder { + size; + signed; + constructor(size, signed, localName) { + const name = ((signed ? "int" : "uint") + (size * 8)); + super(name, name, localName, false); + defineProperties(this, { size, signed }, { size: "number", signed: "boolean" }); + } + defaultValue() { + return 0; + } + encode(writer, _value) { + let value = logger.getBigInt(Typed.dereference(_value, this.type)); + // Check bounds are safe for encoding + let maxUintValue = mask(BN_MAX_UINT256, WordSize * 8); + if (this.signed) { + let bounds = mask(maxUintValue, (this.size * 8) - 1); + if (value > bounds || value < -(bounds + BN_1)) { + this._throwError("value out-of-bounds", _value); + } + } + else if (value < BN_0 || value > mask(maxUintValue, this.size * 8)) { + this._throwError("value out-of-bounds", _value); + } + value = mask(toTwos(value, this.size * 8), this.size * 8); + if (this.signed) { + value = toTwos(fromTwos(value, this.size * 8), 8 * WordSize); + } + return writer.writeValue(value); + } + decode(reader) { + let value = mask(reader.readValue(), this.size * 8); + if (this.signed) { + value = fromTwos(value, this.size * 8); + } + return value; + } +} +//# sourceMappingURL=number.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/number.js.map b/lib.esm/abi/coders/number.js.map new file mode 100644 index 000000000..85456cabd --- /dev/null +++ b/lib.esm/abi/coders/number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"number.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/number.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAOtD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,cAAc,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAEpG,MAAM,O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qB,EAAE,MAAM,CAAC,CAAC;SACnD;QAED,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;QAE1D,IAAI,IAAI,CAAC,MAAM,EAAE;YACb,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC;SAChE;QAED,OAAO,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;QAEpD,IAAI,IAAI,CAAC,MAAM,EAAE;YACb,KAAK,GAAG,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;SAC1C;QAED,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/string.js b/lib.esm/abi/coders/string.js new file mode 100644 index 000000000..f31125caa --- /dev/null +++ b/lib.esm/abi/coders/string.js @@ -0,0 +1,18 @@ +import { toUtf8Bytes, toUtf8String } from "../../utils/utf8.js"; +import { Typed } from "../typed.js"; +import { DynamicBytesCoder } from "./bytes.js"; +export class StringCoder extends DynamicBytesCoder { + constructor(localName) { + super("string", localName); + } + defaultValue() { + return ""; + } + encode(writer, _value) { + return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string"))); + } + decode(reader) { + return toUtf8String(super.decode(reader)); + } +} +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/string.js.map b/lib.esm/abi/coders/string.js.map new file mode 100644 index 000000000..0d935aacf --- /dev/null +++ b/lib.esm/abi/coders/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/string.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEhE,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAK/C,MAAM,OAAO,WAAY,SAAQ,iBAAiB;IAE9C,YAAY,SAAiB;QACzB,KAAK,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC/B,CAAC;IAED,YAAY;QACR,OAAO,EAAE,CAAC;IACd,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAsB;QACzC,OAAO,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,YAAY,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAC9C,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/coders/tuple.js b/lib.esm/abi/coders/tuple.js new file mode 100644 index 000000000..ade551cd5 --- /dev/null +++ b/lib.esm/abi/coders/tuple.js @@ -0,0 +1,60 @@ +import { defineProperties } from "../../utils/properties.js"; +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +import { pack, unpack } from "./array.js"; +export class TupleCoder extends Coder { + coders; + constructor(coders, localName) { + let dynamic = false; + const types = []; + coders.forEach((coder) => { + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + const type = ("tuple(" + types.join(",") + ")"); + super("tuple", type, localName, dynamic); + defineProperties(this, { coders: Object.freeze(coders.slice()) }); + } + defaultValue() { + const values = []; + this.coders.forEach((coder) => { + values.push(coder.defaultValue()); + }); + // We only output named properties for uniquely named coders + const uniqueNames = this.coders.reduce((accum, coder) => { + const name = coder.localName; + if (name) { + if (!accum[name]) { + accum[name] = 0; + } + accum[name]++; + } + return accum; + }, {}); + // Add named values + this.coders.forEach((coder, index) => { + let name = coder.localName; + if (!name || uniqueNames[name] !== 1) { + return; + } + if (name === "length") { + name = "_length"; + } + if (values[name] != null) { + return; + } + values[name] = values[index]; + }); + return Object.freeze(values); + } + encode(writer, _value) { + const value = Typed.dereference(_value, "tuple"); + return pack(writer, this.coders, value); + } + decode(reader) { + return unpack(reader, this.coders); + } +} +//# sourceMappingURL=tuple.js.map \ No newline at end of file diff --git a/lib.esm/abi/coders/tuple.js.map b/lib.esm/abi/coders/tuple.js.map new file mode 100644 index 000000000..c02d82b68 --- /dev/null +++ b/lib.esm/abi/coders/tuple.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.js","sourceRoot":"","sources":["../../../src.ts/abi/coders/tuple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAI1C,MAAM,OAAO,UAAW,SAAQ,KAAK;IACxB,MAAM,CAAwB;IAEvC,YAAY,MAAoB,EAAE,SAAiB;QAC/C,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,KAAK,GAAkB,EAAE,CAAC;QAChC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;YACrB,IAAI,KAAK,CAAC,OAAO,EAAE;gBAAE,OAAO,GAAG,IAAI,CAAC;aAAE;YACtC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;QACH,MAAM,IAAI,GAAG,CAAC,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,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,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,MAAsD;QACzE,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACjD,OAAO,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED,MAAM,CAAC,MAAc;QACjB,OAAO,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/fragments.js b/lib.esm/abi/fragments.js new file mode 100644 index 000000000..cfcbdbdc7 --- /dev/null +++ b/lib.esm/abi/fragments.js @@ -0,0 +1,920 @@ +import { logger } from "../utils/logger.js"; +import { defineProperties } from "../utils/index.js"; +; +export var FormatType; +(function (FormatType) { + // Bare formatting, as is needed for computing a sighash of an event or function + FormatType["sighash"] = "sighash"; + // Human-Readable with Minimal spacing and without names (compact human-readable) + FormatType["minimal"] = "minimal"; + // Human-Readable with nice spacing, including all names + FormatType["full"] = "full"; + // JSON-format a la Solidity + FormatType["json"] = "json"; +})(FormatType || (FormatType = {})); +; +// [ "a", "b" ] => { "a": 1, "b": 1 } +function setify(items) { + const result = new Set(); + items.forEach((k) => result.add(k)); + return Object.freeze(result); +} +// Visibility Keywords +const _kwVisib = "constant external internal payable private public pure view"; +const KwVisib = setify(_kwVisib.split(" ")); +const _kwTypes = "constructor error event function struct"; +const KwTypes = setify(_kwTypes.split(" ")); +const _kwModifiers = "calldata memory storage payable indexed"; +const KwModifiers = setify(_kwModifiers.split(" ")); +const _kwOther = "tuple returns"; +// All Keywords +const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" "); +const Keywords = setify(_keywords.split(" ")); +// Single character tokens +const SimpleTokens = { + "(": "OPEN_PAREN", ")": "CLOSE_PAREN", + "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET", + ",": "COMMA", "@": "AT" +}; +// Parser regexes to consume the next token +const regexWhitespace = new RegExp("^(\\s*)"); +const regexNumber = new RegExp("^([0-9]+)"); +const regexIdentifier = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); +const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))"); +export class TokenString { + #offset; + #tokens; + get offset() { return this.#offset; } + get length() { return this.#tokens.length - this.#offset; } + constructor(tokens) { + this.#offset = 0; + this.#tokens = tokens.slice(); + } + clone() { return new TokenString(this.#tokens); } + reset() { this.#offset = 0; } + #subTokenString(from = 0, to = 0) { + return new TokenString(this.#tokens.slice(from, to).map((t) => { + return Object.freeze(Object.assign({}, t, { + match: (t.match - from), + linkBack: (t.linkBack - from), + linkNext: (t.linkNext - from), + })); + return t; + })); + } + // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens + popKeyword(allowed) { + const top = this.peek(); + if (top.type !== "KEYWORD" || !allowed.has(top.text)) { + throw new Error(`expected keyword ${top.text}`); + } + return this.pop().text; + } + // Pops and returns the value of the next token if it is `type`; throws if out of tokens + popType(type) { + if (this.peek().type !== type) { + throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`); + } + return this.pop().text; + } + // Pops and returns a "(" TOKENS ")" + popParen() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = this.#subTokenString(this.#offset + 1, top.match + 1); + this.#offset = top.match + 1; + return result; + } + // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" + popParams() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = []; + while (this.#offset < top.match - 1) { + const link = this.peek().linkNext; + result.push(this.#subTokenString(this.#offset + 1, link)); + this.#offset = link; + } + this.#offset = top.match + 1; + return result; + } + // Returns the top Token, throwing if out of tokens + peek() { + if (this.#offset >= this.#tokens.length) { + throw new Error("out-of-bounds"); + } + return this.#tokens[this.#offset]; + } + // Returns the next value, if it is a keyword in `allowed` + peekKeyword(allowed) { + const top = this.peekType("KEYWORD"); + return (top != null && allowed.has(top)) ? top : null; + } + // Returns the value of the next token if it is `type` + peekType(type) { + if (this.length === 0) { + return null; + } + const top = this.peek(); + return (top.type === type) ? top.text : null; + } + // Returns the next token; throws if out of tokens + pop() { + const result = this.peek(); + this.#offset++; + return result; + } + toString() { + const tokens = []; + for (let i = this.#offset; i < this.#tokens.length; i++) { + const token = this.#tokens[i]; + tokens.push(`${token.type}:${token.text}`); + } + return ``; + } +} +export function lex(text) { + const tokens = []; + const throwError = (message) => { + const token = (offset < text.length) ? JSON.stringify(text[offset]) : "$EOI"; + throw new Error(`invalid token ${token} at ${offset}: ${message}`); + }; + let brackets = []; + let commas = []; + let offset = 0; + while (offset < text.length) { + // Strip off any leading whitespace + let cur = text.substring(offset); + let match = cur.match(regexWhitespace); + if (match) { + offset += match[1].length; + cur = text.substring(offset); + } + const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 }; + tokens.push(token); + let type = (SimpleTokens[cur[0]] || ""); + if (type) { + token.type = type; + token.text = cur[0]; + offset++; + if (type === "OPEN_PAREN") { + brackets.push(tokens.length - 1); + commas.push(tokens.length - 1); + } + else if (type == "CLOSE_PAREN") { + if (brackets.length === 0) { + throwError("no matching open bracket"); + } + token.match = brackets.pop(); + (tokens[token.match]).match = tokens.length - 1; + token.depth--; + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + } + else if (type === "COMMA") { + token.linkBack = commas.pop(); + (tokens[token.linkBack]).linkNext = tokens.length - 1; + commas.push(tokens.length - 1); + } + else if (type === "OPEN_BRACKET") { + token.type = "BRACKET"; + } + else if (type === "CLOSE_BRACKET") { + // Remove the CLOSE_BRACKET + let suffix = tokens.pop().text; + if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { + const value = tokens.pop().text; + suffix = value + suffix; + (tokens[tokens.length - 1]).value = logger.getNumber(value); + } + if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { + throw new Error("missing opening bracket"); + } + (tokens[tokens.length - 1]).text += suffix; + } + continue; + } + match = cur.match(regexIdentifier); + if (match) { + token.text = match[1]; + offset += token.text.length; + if (Keywords.has(token.text)) { + token.type = "KEYWORD"; + continue; + } + if (token.text.match(regexType)) { + token.type = "TYPE"; + continue; + } + token.type = "ID"; + continue; + } + match = cur.match(regexNumber); + if (match) { + token.text = match[1]; + token.type = "NUMBER"; + offset += token.text.length; + continue; + } + throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); + } + return new TokenString(tokens.map((t) => Object.freeze(t))); +} +// Check only one of `allowed` is in `set` +function allowSingle(set, allowed) { + let included = []; + for (const key in allowed.keys()) { + if (set.has(key)) { + included.push(key); + } + } + if (included.length > 1) { + throw new Error(`conflicting types: ${included.join(", ")}`); + } +} +// Functions to process a Solidity Signature TokenString from left-to-right for... +// ...the name with an optional type, returning the name +function consumeName(type, tokens) { + if (tokens.peekKeyword(KwTypes)) { + const keyword = tokens.pop().text; + if (keyword !== type) { + throw new Error(`expected ${type}, got ${keyword}`); + } + } + return tokens.popType("ID"); +} +// ...all keywords matching allowed, returning the keywords +function consumeKeywords(tokens, allowed) { + const keywords = new Set(); + while (true) { + const keyword = tokens.peekType("KEYWORD"); + if (keyword == null || (allowed && !allowed.has(keyword))) { + break; + } + tokens.pop(); + if (keywords.has(keyword)) { + throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); + } + keywords.add(keyword); + } + return Object.freeze(keywords); +} +// ...all visibility keywords, returning the coalesced mutability +function consumeMutability(tokens) { + let modifiers = consumeKeywords(tokens, KwVisib); + // Detect conflicting modifiers + allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); + allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); + // Process mutability states + if (modifiers.has("view")) { + return "view"; + } + if (modifiers.has("pure")) { + return "pure"; + } + if (modifiers.has("payable")) { + return "payable"; + } + if (modifiers.has("nonpayable")) { + return "nonpayable"; + } + // Process legacy `constant` last + if (modifiers.has("constant")) { + return "view"; + } + return "nonpayable"; +} +// ...a parameter list, returning the ParamType list +function consumeParams(tokens, allowIndexed) { + return tokens.popParams().map((t) => ParamType.fromTokens(t, allowIndexed)); +} +// ...a gas limit, returning a BigNumber or null if none +function consumeGas(tokens) { + if (tokens.peekType("AT")) { + tokens.pop(); + if (tokens.peekType("NUMBER")) { + return logger.getBigInt(tokens.pop().text); + } + throw new Error("invalid gas"); + } + return null; +} +function consumeEoi(tokens) { + if (tokens.length) { + throw new Error(`unexpected tokens: ${tokens.toString()}`); + } +} +const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); +function verifyBasicType(type) { + const match = type.match(regexType); + if (!match) { + return logger.throwArgumentError("invalid type", "type", type); + } + if (type === "uint") { + return "uint256"; + } + if (type === "int") { + return "int256"; + } + if (match[2]) { + // bytesXX + const length = parseInt(match[2]); + if (length === 0 || length > 32) { + logger.throwArgumentError("invalid bytes length", "type", type); + } + } + else if (match[3]) { + // intXX or uintXX + const size = parseInt(match[3]); + if (size === 0 || size > 256 || size % 8) { + logger.throwArgumentError("invalid numeric width", "type", type); + } + } + return type; +} +// Make the Fragment constructors effectively private +const _guard = {}; +const internal = Symbol.for("_ethers_internal"); +const ParamTypeInternal = "_ParamTypeInternal"; +export class ParamType { + // The local name of the parameter (of "" if unbound) + name; + // The fully qualified type (e.g. "address", "tuple(address)", "uint256[3][]" + type; + // The base type (e.g. "address", "tuple", "array") + baseType; + // Indexable Paramters ONLY (otherwise null) + indexed; + // Tuples ONLY: (otherwise null) + // - sub-components + components; + // Arrays ONLY: (otherwise null) + // - length of the array (-1 for dynamic length) + // - child type + arrayLength; + arrayChildren; + constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) { + logger.assertPrivate(guard, _guard, "ParamType"); + Object.defineProperty(this, internal, { value: ParamTypeInternal }); + if (components) { + components = Object.freeze(components.slice()); + } + if (baseType === "array") { + if (arrayLength == null || arrayChildren == null) { + throw new Error(""); + } + } + else if (arrayLength != null || arrayChildren != null) { + throw new Error(""); + } + if (baseType === "tuple") { + if (components == null) { + throw new Error(""); + } + } + else if (components != null) { + throw new Error(""); + } + defineProperties(this, { + name, type, baseType, indexed, components, arrayLength, arrayChildren + }); + } + // Format the parameter fragment + // - sighash: "(uint256,address)" + // - minimal: "tuple(uint256,address) indexed" + // - full: "tuple(uint256 foo, address bar) indexed baz" + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + let result = { + type: ((this.baseType === "tuple") ? "tuple" : this.type), + name: (this.name || undefined) + }; + if (typeof (this.indexed) === "boolean") { + result.indexed = this.indexed; + } + if (this.isTuple()) { + result.components = this.components.map((c) => JSON.parse(c.format(format))); + } + return JSON.stringify(result); + } + let result = ""; + // Array + if (this.isArray()) { + result += this.arrayChildren.format(format); + result += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`; + } + else { + if (this.isTuple()) { + if (format !== FormatType.sighash) { + result += this.type; + } + result += "(" + this.components.map((comp) => comp.format(format)).join((format === FormatType.full) ? ", " : ",") + ")"; + } + else { + result += this.type; + } + } + if (format !== FormatType.sighash) { + if (this.indexed === true) { + result += " indexed"; + } + if (format === FormatType.full && this.name) { + result += " " + this.name; + } + } + return result; + } + static isArray(value) { + return value && (value.baseType === "array"); + } + isArray() { + return (this.baseType === "array"); + } + isTuple() { + return (this.baseType === "tuple"); + } + isIndexable() { + return (this.indexed != null); + } + walk(value, process) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invlaid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + return value.map((v) => (this.arrayChildren.walk(v, process))); + } + if (this.isTuple()) { + if (!Array.isArray(value)) { + throw new Error("invlaid tuple value"); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + return value.map((v, i) => (this.components[i].walk(v, process))); + } + return process(this.type, value); + } + #walkAsync(promises, value, process, setValue) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invlaid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const childType = this.arrayChildren; + const result = value.slice(); + result.forEach((value, index) => { + childType.#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + if (this.isTuple()) { + const components = this.components; + // Convert the object into an array + let result; + if (Array.isArray(value)) { + result = value.slice(); + } + else { + if (value == null || typeof (value) !== "object") { + throw new Error("invlaid tuple value"); + } + result = components.map((param) => { + if (!param.name) { + throw new Error("cannot use object value with unnamed components"); + } + if (!(param.name in value)) { + throw new Error(`missing value for component ${param.name}`); + } + return value[param.name]; + }); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + result.forEach((value, index) => { + components[index].#walkAsync(promises, value, process, (value) => { + result[index] = value; + }); + }); + setValue(result); + return; + } + const result = process(this.type, value); + if (result.then) { + promises.push((async function () { setValue(await result); })()); + } + else { + setValue(result); + } + } + async walkAsync(value, process) { + const promises = []; + const result = [value]; + this.#walkAsync(promises, value, process, (value) => { + result[0] = value; + }); + if (promises.length) { + await Promise.all(promises); + } + return result[0]; + } + static from(obj, allowIndexed) { + if (ParamType.isParamType(obj)) { + return obj; + } + if (typeof (obj) === "string") { + return ParamType.fromTokens(lex(obj), allowIndexed); + } + if (obj instanceof TokenString) { + return ParamType.fromTokens(obj, allowIndexed); + } + const name = obj.name; + if (name && (typeof (name) !== "string" || !name.match(regexIdentifier))) { + logger.throwArgumentError("invalid name", "obj.name", name); + } + let indexed = obj.indexed; + if (indexed != null) { + if (!allowIndexed) { + logger.throwArgumentError("parameter cannot be indexed", "obj.indexed", obj.indexed); + } + indexed = !!indexed; + } + let type = obj.type; + let arrayMatch = type.match(regexArrayType); + if (arrayMatch) { + const arrayLength = arrayMatch[2]; + const arrayChildren = ParamType.from({ + type: arrayMatch[1], + components: obj.components + }); + return new ParamType(_guard, name, type, "array", indexed, null, arrayLength, arrayChildren); + } + if (type.substring(0, 5) === "tuple(" || type[0] === "(") { + const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null; + const tuple = new ParamType(_guard, name, type, "tuple", indexed, comps, null, null); + // @TODO: use lexer to validate and normalize type + return tuple; + } + type = verifyBasicType(obj.type); + return new ParamType(_guard, name, type, type, indexed, null, null, null); + } + static fromObject(obj, allowIndexed) { + throw new Error("@TODO"); + } + static fromTokens(tokens, allowIndexed) { + let type = "", baseType = ""; + let comps = null; + if (consumeKeywords(tokens, setify(["tuple"])).has("tuple") || tokens.peekType("OPEN_PAREN")) { + // Tuple + baseType = "tuple"; + comps = tokens.popParams().map((t) => ParamType.from(t)); + type = `tuple(${comps.map((c) => c.format()).join(",")})`; + } + else { + // Normal + type = verifyBasicType(tokens.popType("TYPE")); + baseType = type; + } + // Check for Array + let arrayChildren = null; + let arrayLength = null; + while (tokens.length && tokens.peekType("BRACKET")) { + const bracket = tokens.pop(); //arrays[i]; + arrayChildren = new ParamType(_guard, "", type, baseType, null, comps, arrayLength, arrayChildren); + arrayLength = bracket.value; + type += bracket.text; + baseType = "array"; + comps = null; + } + let indexed = null; + const keywords = consumeKeywords(tokens, KwModifiers); + if (keywords.has("indexed")) { + if (!allowIndexed) { + throw new Error(""); + } + indexed = true; + } + const name = (tokens.peekType("ID") ? tokens.pop().text : ""); + if (tokens.length) { + throw new Error("leftover tokens"); + } + return new ParamType(_guard, name, type, baseType, indexed, comps, arrayLength, arrayChildren); + } + static isParamType(value) { + return (value && value[internal] === ParamTypeInternal); + } +} +export var FragmentType; +(function (FragmentType) { + FragmentType["constructor"] = "constructor"; + FragmentType["error"] = "error"; + FragmentType["event"] = "event"; + FragmentType["function"] = "function"; + FragmentType["struct"] = "struct"; +})(FragmentType || (FragmentType = {})); +; +export class Fragment { + type; + inputs; + constructor(guard, type, inputs) { + logger.assertPrivate(guard, _guard, "Fragment"); + inputs = Object.freeze(inputs.slice()); + defineProperties(this, { type, inputs }); + } + static from(obj) { + if (typeof (obj) === "string") { + return this.fromString(obj); + } + if (obj instanceof TokenString) { + return this.fromTokens(obj); + } + if (typeof (obj) === "object") { + return this.fromObject(obj); + } + throw new Error(`unsupported type: ${obj}`); + } + static fromObject(obj) { + switch (obj.type) { + case "constructor": return ConstructorFragment.fromObject(obj); + case "error": return ErrorFragment.fromObject(obj); + case "event": return EventFragment.fromObject(obj); + case "function": return FunctionFragment.fromObject(obj); + case "struct": return StructFragment.fromObject(obj); + } + throw new Error("not implemented yet"); + } + static fromString(text) { + try { + Fragment.from(JSON.parse(text)); + } + catch (e) { } + return Fragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const type = tokens.popKeyword(KwTypes); + switch (type) { + case "constructor": return ConstructorFragment.fromTokens(tokens); + case "error": return ErrorFragment.fromTokens(tokens); + case "event": return EventFragment.fromTokens(tokens); + case "function": return FunctionFragment.fromTokens(tokens); + case "struct": return StructFragment.fromTokens(tokens); + } + throw new Error(`unsupported type: ${type}`); + } + /* + static fromTokens(tokens: TokenString): Fragment { + const assertDone = () => { + if (tokens.length) { throw new Error(`unexpected tokens: ${ tokens.toString() }`); } + }); + + const type = (tokens.length && tokens.peek().type === "KEYWORD") ? tokens.peek().text: "unknown"; + + const name = consumeName("error", tokens); + const inputs = consumeParams(tokens, type === "event"); + + switch (type) { + case "event": case "struct": + assertDone(); + } + + } + */ + static isConstructor(value) { + return (value && value.type === "constructor"); + } + static isError(value) { + return (value && value.type === "error"); + } + static isEvent(value) { + return (value && value.type === "event"); + } + static isFunction(value) { + return (value && value.type === "function"); + } + static isStruct(value) { + return (value && value.type === "struct"); + } +} +export class NamedFragment extends Fragment { + name; + constructor(guard, type, name, inputs) { + super(guard, type, inputs); + inputs = Object.freeze(inputs.slice()); + defineProperties(this, { name }); + } +} +function joinParams(format, params) { + return "(" + params.map((p) => p.format(format)).join((format === FormatType.full) ? ", " : ",") + ")"; +} +export class ErrorFragment extends NamedFragment { + constructor(guard, name, inputs) { + super(guard, FragmentType.error, name, inputs); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input) => JSON.parse(input.format(format))), + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("error"); + } + result.push(this.name + joinParams(format, this.inputs)); + return result.join(" "); + } + static fromString(text) { + return ErrorFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("error", tokens); + const inputs = consumeParams(tokens); + consumeEoi(tokens); + return new ErrorFragment(_guard, name, inputs); + } +} +export class EventFragment extends NamedFragment { + anonymous; + constructor(guard, name, inputs, anonymous) { + super(guard, FragmentType.event, name, inputs); + defineProperties(this, { anonymous }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("event"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== FormatType.sighash && this.anonymous) { + result.push("anonymous"); + } + return result.join(" "); + } + static fromString(text) { + return EventFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("event", tokens); + const inputs = consumeParams(tokens, true); + const anonymous = !!consumeKeywords(tokens, setify(["anonymous"])).has("anonymous"); + consumeEoi(tokens); + return new EventFragment(_guard, name, inputs, anonymous); + } +} +export class ConstructorFragment extends Fragment { + payable; + gas; + constructor(guard, type, inputs, payable, gas) { + super(guard, type, inputs); + defineProperties(this, { payable, gas }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.sighash) { + logger.throwError("cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { + operation: "format(sighash)" + }); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "constructor", + stateMutability: (this.payable ? "payable" : "undefined"), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))) + }); + } + const result = [`constructor${joinParams(format, this.inputs)}`]; + result.push((this.payable) ? "payable" : "nonpayable"); + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + return result.join(" "); + } + static fromString(text) { + return ConstructorFragment.fromTokens(lex(text)); + } + static fromObject(obj) { + throw new Error("TODO"); + } + static fromTokens(tokens) { + consumeKeywords(tokens, setify(["constructor"])); + const inputs = consumeParams(tokens); + const payable = !!consumeKeywords(tokens, setify(["payable"])).has("payable"); + const gas = consumeGas(tokens); + consumeEoi(tokens); + return new ConstructorFragment(_guard, FragmentType.constructor, inputs, payable, gas); + } +} +export class FunctionFragment extends NamedFragment { + constant; + outputs; + stateMutability; + payable; + gas; + constructor(guard, name, stateMutability, inputs, outputs, gas) { + super(guard, FragmentType.function, name, inputs); + outputs = Object.freeze(outputs.slice()); + const constant = (stateMutability === "view" || stateMutability === "pure"); + const payable = (stateMutability === "payable"); + defineProperties(this, { constant, gas, outputs, payable, stateMutability }); + } + format(format = FormatType.sighash) { + if (!FormatType[format]) { + logger.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatType.json) { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined), + payable: this.payable, + gas: ((this.gas != null) ? this.gas : undefined), + inputs: this.inputs.map((i) => JSON.parse(i.format(format))), + outputs: this.outputs.map((o) => JSON.parse(o.format(format))), + }); + } + const result = []; + if (format !== FormatType.sighash) { + result.push("function"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== FormatType.sighash) { + if (this.stateMutability !== "nonpayable") { + result.push(this.stateMutability); + } + if (this.outputs && this.outputs.length) { + result.push("returns"); + result.push(joinParams(format, this.outputs)); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + } + return result.join(" "); + } + static fromString(text) { + return FunctionFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("function", tokens); + const inputs = consumeParams(tokens); + const mutability = consumeMutability(tokens); + let outputs = []; + if (consumeKeywords(tokens, setify(["returns"])).has("returns")) { + outputs = consumeParams(tokens); + } + const gas = consumeGas(tokens); + consumeEoi(tokens); + return new FunctionFragment(_guard, name, mutability, inputs, outputs, gas); + } +} +export class StructFragment extends NamedFragment { + format() { + throw new Error("@TODO"); + } + static fromString(text) { + return StructFragment.fromTokens(lex(text)); + } + static fromTokens(tokens) { + const name = consumeName("struct", tokens); + const inputs = consumeParams(tokens); + consumeEoi(tokens); + return new StructFragment(_guard, FragmentType.struct, name, inputs); + } +} +//# sourceMappingURL=fragments.js.map \ No newline at end of file diff --git a/lib.esm/abi/fragments.js.map b/lib.esm/abi/fragments.js.map new file mode 100644 index 000000000..ec3e6a4a6 --- /dev/null +++ b/lib.esm/abi/fragments.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fragments.js","sourceRoot":"","sources":["../../src.ts/abi/fragments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAyBpD,CAAC;AAEF,MAAM,CAAN,IAAY,UAYX;AAZD,WAAY,UAAU;IAClB,gFAAgF;IAChF,iCAAmB,CAAA;IAEnB,iFAAiF;IACjF,iCAAmB,CAAA;IAEnB,wDAAwD;IACxD,2BAAa,CAAA;IAEb,4BAA4B;IAC5B,2BAAa,CAAA;AACjB,CAAC,EAZW,UAAU,KAAV,UAAU,QAYrB;AAAA,CAAC;AAEF,qCAAqC;AACrC,SAAS,MAAM,CAAC,KAAoB;IAChC,MAAM,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e,CAAC,MAAM,EAAE,MAAM,CAAC,CAAE,SAAS,CAAE,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YAC/D,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;SACnC;QAED,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAE/B,UAAU,CAAC,MAAM,CAAC,CAAC;QAEnB,OAAO,IAAI,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAChF,CAAC;CACJ;AAED,MAAM,OAAO,cAAe,SAAQ,aAAa;IAC7C,MAAM;QACF,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,IAAY;QAC1B,OAAO,cAAc,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAmB;QACjC,MAAM,IAAI,GAAG,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC3C,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QACrC,UAAU,CAAC,MAAM,CAAC,CAAC;QAEnB,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACzE,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/index.js b/lib.esm/abi/index.js new file mode 100644 index 000000000..c6076d31b --- /dev/null +++ b/lib.esm/abi/index.js @@ -0,0 +1,6 @@ +export { AbiCoder, defaultAbiCoder } from "./abi-coder.js"; +export { formatBytes32String, parseBytes32String } from "./bytes32.js"; +export { ConstructorFragment, ErrorFragment, EventFragment, Fragment, FunctionFragment, ParamType } from "./fragments.js"; +export { checkResultErrors, Indexed, Interface, LogDescription, Result, TransactionDescription } from "./interface.js"; +export { Typed } from "./typed.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/abi/index.js.map b/lib.esm/abi/index.js.map new file mode 100644 index 000000000..27775419a --- /dev/null +++ b/lib.esm/abi/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/abi/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,QAAQ,EACR,eAAe,EAClB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvE,OAAO,EACH,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,QAAQ,EACR,gBAAgB,EAChB,SAAS,EACZ,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACH,iBAAiB,EACjB,OAAO,EACP,SAAS,EACT,cAAc,EACd,MAAM,EACN,sBAAsB,EACzB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/lib.esm/abi/interface.js b/lib.esm/abi/interface.js new file mode 100644 index 000000000..3f0807151 --- /dev/null +++ b/lib.esm/abi/interface.js @@ -0,0 +1,808 @@ +import { concat, dataSlice, hexlify, zeroPadValue, isHexString } from "../utils/data.js"; +import { keccak256 } from "../crypto/index.js"; +import { id } from "../hash/index.js"; +import { logger } from "../utils/logger.js"; +import { defineProperties } from "../utils/properties.js"; +import { toHex } from "../utils/maths.js"; +import { defaultAbiCoder } from "./abi-coder.js"; +import { checkResultErrors, Result } from "./coders/abstract-coder.js"; +import { ConstructorFragment, ErrorFragment, EventFragment, FormatType, Fragment, FunctionFragment, ParamType } from "./fragments.js"; +import { Typed } from "./typed.js"; +export { checkResultErrors, Result }; +export class LogDescription { + fragment; + name; + signature; + topic; + args; + constructor(fragment, topic, args) { + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment, name, signature, topic, args + }); + } +} +export class TransactionDescription { + fragment; + name; + args; + signature; + selector; + value; + constructor(fragment, selector, args, value) { + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment, name, args, signature, selector, value + }); + } +} +export class ErrorDescription { + fragment; + name; + args; + signature; + selector; + constructor(fragment, selector, args) { + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment, name, args, signature, selector + }); + } +} +export class Indexed { + hash; + _isIndexed; + static isIndexed(value) { + return !!(value && value._isIndexed); + } + constructor(hash) { + defineProperties(this, { hash, _isIndexed: true }); + } +} +// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require +const PanicReasons = { + "0": "generic panic", + "1": "assert(false)", + "17": "arithmetic overflow", + "18": "division or modulo by zero", + "33": "enum overflow", + "34": "invalid encoded storage byte array accessed", + "49": "out-of-bounds array access; popping on an empty array", + "50": "out-of-bounds access of an array or bytesN", + "65": "out of memory", + "81": "uninitialized function", +}; +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: ["string"], + reason: (message) => { + return `reverted with reason string ${JSON.stringify(message)}`; + } + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: ["uint256"], + reason: (code) => { + let reason = "unknown panic code"; + if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) { + reason = PanicReasons[code.toString()]; + } + return `reverted with panic code 0x${code.toString(16)} (${reason})`; + } + } +}; +export class Interface { + fragments; + deploy; + #errors; + #events; + #functions; + // #structs: Map; + #abiCoder; + constructor(fragments) { + let abi = []; + if (typeof (fragments) === "string") { + abi = JSON.parse(fragments); + } + else { + abi = fragments; + } + this.#functions = new Map(); + this.#errors = new Map(); + this.#events = new Map(); + // this.#structs = new Map(); + defineProperties(this, { + fragments: Object.freeze(abi.map((f) => Fragment.from(f)).filter((f) => (f != null))), + }); + this.#abiCoder = this.getAbiCoder(); + // Add all fragments by their signature + this.fragments.forEach((fragment) => { + let bucket; + switch (fragment.type) { + case "constructor": + if (this.deploy) { + logger.warn("duplicate definition - constructor"); + return; + } + //checkNames(fragment, "input", fragment.inputs); + defineProperties(this, { deploy: fragment }); + return; + case "function": + //checkNames(fragment, "input", fragment.inputs); + //checkNames(fragment, "output", (fragment).outputs); + bucket = this.#functions; + break; + case "event": + //checkNames(fragment, "input", fragment.inputs); + bucket = this.#events; + break; + case "error": + bucket = this.#errors; + break; + default: + return; + } + const signature = fragment.format(); + if (bucket.has(signature)) { + logger.warn("duplicate definition - " + signature); + return; + } + bucket.set(signature, fragment); + }); + // If we do not have a constructor add a default + if (!this.deploy) { + defineProperties(this, { + deploy: ConstructorFragment.fromString("constructor()") + }); + } + } + // @TODO: multi sig? + format(format) { + if (!format) { + format = FormatType.full; + } + if (format === FormatType.sighash) { + logger.throwArgumentError("interface does not support formatting sighash", "format", format); + } + const abi = this.fragments.map((f) => f.format(format)); + // We need to re-bundle the JSON fragments a bit + if (format === FormatType.json) { + return JSON.stringify(abi.map((j) => JSON.parse(j))); + } + return abi; + } + getAbiCoder() { + return defaultAbiCoder; + } + //static getAddress(address: string): string { + // return getAddress(address); + //} + //static getSelector(fragment: ErrorFragment | FunctionFragment): string { + // return dataSlice(id(fragment.format()), 0, 4); + //} + //static getEventTopic(eventFragment: EventFragment): string { + // return id(eventFragment.format()); + //} + // Find a function definition by any means necessary (unless it is ambiguous) + #getFunction(key, values, forceUnique) { + // Selector + if (isHexString(key)) { + const selector = key.toLowerCase(); + for (const fragment of this.#functions.values()) { + if (selector === this.getSelector(fragment)) { + return fragment; + } + } + logger.throwArgumentError("no matching function", "selector", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#functions) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + const lastValue = (values.length > 0) ? values[values.length - 1] : null; + let valueLength = values.length; + let allowOptions = true; + if (Typed.isTyped(lastValue) && lastValue.type === "overrides") { + allowOptions = false; + valueLength--; + } + // Remove all matches that don't have a compatible length. The args + // may contain an overrides, so the match may have n or n - 1 parameters + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs.length; + if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!Typed.isTyped(values[j])) { + continue; + } + // We are past the inputs + if (j >= inputs.length) { + if (values[j].type === "overrides") { + continue; + } + matching.splice(i, 1); + break; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + // We found a single matching signature with an overrides, but the + // last value is something that cannot possibly be an options + if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { + const lastArg = values[values.length - 1]; + if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== "object") { + matching.splice(0, 1); + } + } + if (matching.length === 0) { + logger.throwArgumentError("no matching function", "name", key); + } + else if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", "); + logger.throwArgumentError(`multiple matching functions (i.e. ${matchStr})`, "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#functions.get(FunctionFragment.fromString(key).format()); + if (result) { + return result; + } + return logger.throwArgumentError("no matching function", "signature", key); + } + getFunctionName(key) { + return (this.#getFunction(key, null, false)).name; + } + getFunction(key, values) { + return this.#getFunction(key, values || null, true); + } + // Find an event definition by any means necessary (unless it is ambiguous) + #getEvent(key, values, forceUnique) { + // EventTopic + if (isHexString(key)) { + const eventTopic = key.toLowerCase(); + for (const fragment of this.#events.values()) { + if (eventTopic === this.getEventTopic(fragment)) { + return fragment; + } + } + logger.throwArgumentError("no matching event", "eventTopic", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#events) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (values) { + // Remove all matches that don't have a compatible length. + for (let i = matching.length - 1; i >= 0; i--) { + if (matching[i].inputs.length < values.length) { + matching.splice(i, 1); + } + } + // Remove all matches that don't match the Typed signature + for (let i = matching.length - 1; i >= 0; i--) { + const inputs = matching[i].inputs; + for (let j = 0; j < values.length; j++) { + // Not a typed value + if (!Typed.isTyped(values[j])) { + continue; + } + // Make sure the value type matches the input type + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 0) { + logger.throwArgumentError("no matching event", "name", key); + } + else if (matching.length > 1 && forceUnique) { + // @TODO: refine by Typed + logger.throwArgumentError("multiple matching events", "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + const result = this.#events.get(EventFragment.fromString(key).format()); + if (result) { + return result; + } + return logger.throwArgumentError("no matching event", "signature", key); + } + getEventName(key) { + return (this.#getEvent(key, null, false)).name; + } + getEvent(key, values) { + return this.#getEvent(key, values || null, true); + } + // Find a function definition by any means necessary (unless it is ambiguous) + getError(key, values) { + if (isHexString(key)) { + const selector = key.toLowerCase(); + if (BuiltinErrors[selector]) { + return ErrorFragment.fromString(BuiltinErrors[selector].signature); + } + for (const fragment of this.#errors.values()) { + if (selector === this.getSelector(fragment)) { + return fragment; + } + } + logger.throwArgumentError("no matching error", "selector", key); + } + // It is a bare name, look up the function (will return null if ambiguous) + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#errors) { + if (name.split("(" /* fix:) */)[0] === key) { + matching.push(fragment); + } + } + if (matching.length === 0) { + if (key === "Error") { + return ErrorFragment.fromString("error Error(string)"); + } + if (key === "Panic") { + return ErrorFragment.fromString("error Panic(uint256)"); + } + logger.throwArgumentError("no matching error", "name", key); + } + else if (matching.length > 1) { + // @TODO: refine by Typed + logger.throwArgumentError("multiple matching errors", "name", key); + } + return matching[0]; + } + // Normalize the signature and lookup the function + key = ErrorFragment.fromString(key).format(); + if (key === "Error(string)") { + return ErrorFragment.fromString("error Error(string)"); + } + if (key === "Panic(uint256)") { + return ErrorFragment.fromString("error Panic(uint256)"); + } + const result = this.#errors.get(key); + if (result) { + return result; + } + return logger.throwArgumentError("no matching error", "signature", key); + } + // Get the 4-byte selector used by Solidity to identify a function + getSelector(fragment) { + /* + if (typeof(fragment) === "string") { + const matches: Array = [ ]; + + try { matches.push(this.getFunction(fragment)); } catch (error) { } + try { matches.push(this.getError(fragment)); } catch (_) { } + + if (matches.length === 0) { + logger.throwArgumentError("unknown fragment", "key", fragment); + } else if (matches.length > 1) { + logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment); + } + + fragment = matches[0]; + } + */ + return dataSlice(id(fragment.format()), 0, 4); + } + // Get the 32-byte topic hash used by Solidity to identify an event + getEventTopic(fragment) { + //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); } + return id(fragment.format()); + } + _decodeParams(params, data) { + return this.#abiCoder.decode(params, data); + } + _encodeParams(params, values) { + return this.#abiCoder.encode(params, values); + } + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); + } + decodeErrorResult(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getError(fragment); + } + if (dataSlice(data, 0, 4) !== this.getSelector(fragment)) { + logger.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", data); + } + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + } + encodeErrorResult(fragment, values) { + if (typeof (fragment) === "string") { + fragment = this.getError(fragment); + } + return concat([ + this.getSelector(fragment), + this._encodeParams(fragment.inputs, values || []) + ]); + } + // Decode the data for a function call (e.g. tx.data) + decodeFunctionData(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + if (dataSlice(data, 0, 4) !== this.getSelector(fragment)) { + logger.throwArgumentError(`data signature does not match function ${fragment.name}.`, "data", data); + } + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + } + // Encode the data for a function call (e.g. tx.data) + encodeFunctionData(fragment, values) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + return concat([ + this.getSelector(fragment), + this._encodeParams(fragment.inputs, values || []) + ]); + } + // Decode the result from a function call (e.g. from eth_call) + decodeFunctionResult(fragment, data) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + let message = "invalid length for result data"; + const bytes = logger.getBytesCopy(data); + if ((bytes.length % 32) === 0) { + try { + return this.#abiCoder.decode(fragment.outputs, bytes); + } + catch (error) { + message = "could not decode result data"; + } + } + // Call returned data with no error, but the data is junk + return logger.throwError(message, "BAD_DATA", { + value: hexlify(bytes), + info: { method: fragment.name, signature: fragment.format() } + }); + } + makeError(fragment, _data, tx) { + if (typeof (fragment) === "string") { + fragment = this.getFunction(fragment); + } + const data = logger.getBytes(_data); + let args = undefined; + if (tx) { + try { + args = this.#abiCoder.decode(fragment.inputs, tx.data || "0x"); + } + catch (error) { + console.log(error); + } + } + let errorArgs = undefined; + let errorName = undefined; + let errorSignature = undefined; + let reason = "unknown reason"; + if (data.length === 0) { + reason = "missing error reason"; + } + else if ((data.length % 32) === 4) { + const selector = hexlify(data.slice(0, 4)); + const builtin = BuiltinErrors[selector]; + if (builtin) { + try { + errorName = builtin.name; + errorSignature = builtin.signature; + errorArgs = this.#abiCoder.decode(builtin.inputs, data.slice(4)); + reason = builtin.reason(...errorArgs); + } + catch (error) { + console.log(error); // @TODO: remove + } + } + else { + reason = "unknown custom error"; + try { + const error = this.getError(selector); + errorName = error.name; + errorSignature = error.format(); + reason = `custom error: ${errorSignature}`; + try { + errorArgs = this.#abiCoder.decode(error.inputs, data.slice(4)); + } + catch (error) { + reason = `custom error: ${errorSignature} (coult not decode error data)`; + } + } + catch (error) { + console.log(error); // @TODO: remove + } + } + } + return logger.makeError("call revert exception", "CALL_EXCEPTION", { + data: hexlify(data), transaction: null, + method: fragment.name, signature: fragment.format(), args, + errorArgs, errorName, errorSignature, reason + }); + } + // Encode the result for a function call (e.g. for eth_call) + encodeFunctionResult(functionFragment, values) { + if (typeof (functionFragment) === "string") { + functionFragment = this.getFunction(functionFragment); + } + return hexlify(this.#abiCoder.encode(functionFragment.outputs, values || [])); + } + /* + spelunk(inputs: Array, values: ReadonlyArray, processfunc: (type: string, value: any) => Promise): Promise> { + const promises: Array> = [ ]; + const process = function(type: ParamType, value: any): any { + if (type.baseType === "array") { + return descend(type.child + } + if (type. === "address") { + } + }; + + const descend = function (inputs: Array, values: ReadonlyArray) { + if (inputs.length !== values.length) { throw new Error("length mismatch"); } + + }; + + const result: Array = [ ]; + values.forEach((value, index) => { + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + } + */ + // Create the filter for the event with search criteria (e.g. for eth_filterLog) + encodeFilterTopics(eventFragment, values) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (values.length > eventFragment.inputs.length) { + logger.throwError("too many arguments for " + eventFragment.format(), "UNEXPECTED_ARGUMENT", { + count: values.length, + expectedCount: eventFragment.inputs.length + }); + } + const topics = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + // @TODO: Use the coders for this; to properly support tuples, etc. + const encodeTopic = (param, value) => { + if (param.type === "string") { + return id(value); + } + else if (param.type === "bytes") { + return keccak256(hexlify(value)); + } + if (param.type === "bool" && typeof (value) === "boolean") { + value = (value ? "0x01" : "0x00"); + } + if (param.type.match(/^u?int/)) { + value = toHex(value); + } + // Check addresses are valid + if (param.type === "address") { + this.#abiCoder.encode(["address"], [value]); + } + return zeroPadValue(hexlify(value), 32); + //@TOOD should probably be return toHex(value, 32) + }; + values.forEach((value, index) => { + const param = eventFragment.inputs[index]; + if (!param.indexed) { + if (value != null) { + logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value); + } + return; + } + if (value == null) { + topics.push(null); + } + else if (param.baseType === "array" || param.baseType === "tuple") { + logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); + } + else if (Array.isArray(value)) { + topics.push(value.map((value) => encodeTopic(param, value))); + } + else { + topics.push(encodeTopic(param, value)); + } + }); + // Trim off trailing nulls + while (topics.length && topics[topics.length - 1] === null) { + topics.pop(); + } + return topics; + } + encodeEventLog(eventFragment, values) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + if (values.length !== eventFragment.inputs.length) { + logger.throwArgumentError("event arguments/values mismatch", "values", values); + } + eventFragment.inputs.forEach((param, index) => { + const value = values[index]; + if (param.indexed) { + if (param.type === "string") { + topics.push(id(value)); + } + else if (param.type === "bytes") { + topics.push(keccak256(value)); + } + else if (param.baseType === "tuple" || param.baseType === "array") { + // @TODO + throw new Error("not implemented"); + } + else { + topics.push(this.#abiCoder.encode([param.type], [value])); + } + } + else { + dataTypes.push(param); + dataValues.push(value); + } + }); + return { + data: this.#abiCoder.encode(dataTypes, dataValues), + topics: topics + }; + } + // Decode a filter for the event and the search criteria + decodeEventLog(eventFragment, data, topics) { + if (typeof (eventFragment) === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (topics != null && !eventFragment.anonymous) { + const eventTopic = this.getEventTopic(eventFragment); + if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== eventTopic) { + logger.throwArgumentError("fragment/topic mismatch", "topics[0]", topics[0]); + } + topics = topics.slice(1); + } + const indexed = []; + const nonIndexed = []; + const dynamic = []; + eventFragment.inputs.forEach((param, index) => { + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(ParamType.fromObject({ type: "bytes32", name: param.name })); + dynamic.push(true); + } + else { + indexed.push(param); + dynamic.push(false); + } + } + else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)) : null; + const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); + //const result: (Array & { [ key: string ]: any }) = [ ]; + const values = []; + const keys = []; + let nonIndexedIndex = 0, indexedIndex = 0; + eventFragment.inputs.forEach((param, index) => { + let value = null; + if (param.indexed) { + if (resultIndexed == null) { + value = new Indexed(null); + } + else if (dynamic[index]) { + value = new Indexed(resultIndexed[indexedIndex++]); + } + else { + try { + value = resultIndexed[indexedIndex++]; + } + catch (error) { + value = error; + } + } + } + else { + try { + value = resultNonIndexed[nonIndexedIndex++]; + } + catch (error) { + value = error; + } + } + values.push(value); + keys.push(param.name || null); + }); + return Result.fromItems(values, keys); + } + // Given a transaction, find the matching function fragment (if any) and + // determine all its properties and call parameters + parseTransaction(tx) { + const data = logger.getBytes(tx.data, "tx.data"); + const value = logger.getBigInt((tx.value != null) ? tx.value : 0, "tx.value"); + const fragment = this.getFunction(hexlify(data.slice(0, 4))); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); + return new TransactionDescription(fragment, this.getSelector(fragment), args, value); + } + // @TODO + //parseCallResult(data: BytesLike): ?? + // Given an event log, find the matching event fragment (if any) and + // determine all its properties and values + parseLog(log) { + const fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; + } + // @TODO: If anonymous, and the only method, and the input count matches, should we parse? + // Probably not, because just because it is the only event in the ABI does + // not mean we have the full ABI; maybe just a fragment? + return new LogDescription(fragment, this.getEventTopic(fragment), this.decodeEventLog(fragment, log.data, log.topics)); + } + parseError(data) { + const hexData = hexlify(data); + const fragment = this.getError(dataSlice(hexData, 0, 4)); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4)); + return new ErrorDescription(fragment, this.getSelector(fragment), args); + } + static from(value) { + // Already an Interface, which is immutable + if (value instanceof Interface) { + return value; + } + // JSON + if (typeof (value) === "string") { + return new Interface(JSON.parse(value)); + } + // Maybe an interface from an older version, or from a symlinked copy + if (typeof (value.format) === "function") { + return new Interface(value.format(FormatType.json)); + } + // Array of fragments + return new Interface(value); + } +} +//# sourceMappingURL=interface.js.map \ No newline at end of file diff --git a/lib.esm/abi/interface.js.map b/lib.esm/abi/interface.js.map new file mode 100644 index 000000000..1ea9e952c --- /dev/null +++ b/lib.esm/abi/interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interface.js","sourceRoot":"","sources":["../../src.ts/abi/interface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAA;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,EAAY,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,UAAU,EAAE,QAAQ,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACtI,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAOnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC;AAErC,MAAM,OAAO,cAAc;IACd,QAAQ,CAAiB;IACzB,IAAI,CAAU;IACd,SAAS,CAAU;IACnB,KAAK,CAAU;IACf,IAAI,CAAS;IAEtB,YAAY,QAAuB,EAAE,KAAa,EAAE,IAAY;QAC5D,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI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AAQ,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QAE/B,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;QAC3E,OAAO,IAAI,gBAAgB,CAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5E,CAAC;IAGD,MAAM,CAAC,IAAI,CAAC,KAA2E;QACnF,2CAA2C;QAC3C,IAAI,KAAK,YAAY,SAAS,EAAE;YAAE,OAAO,KAAK,CAAC;SAAE;QAEjD,OAAO;QACP,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;YAAE,OAAO,IAAI,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAAE;QAE5E,qEAAqE;QACrE,IAAI,OAAM,CAAO,KAAM,CAAC,MAAM,CAAC,KAAK,UAAU,EAAE;YAC5C,OAAO,IAAI,SAAS,CAAO,KAAM,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;SAC9D;QAED,qBAAqB;QACrB,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/abi/typed.js b/lib.esm/abi/typed.js new file mode 100644 index 000000000..ab5c7e826 --- /dev/null +++ b/lib.esm/abi/typed.js @@ -0,0 +1,212 @@ +import { defineProperties } from "../utils/properties.js"; +const _gaurd = {}; +function n(value, width) { + let signed = false; + if (width < 0) { + signed = true; + width *= -1; + } + // @TODO: Check range is valid for value + return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { signed, width }); +} +function b(value, size) { + // @TODO: Check range is valid for value + return new Typed(_gaurd, `bytes${(size) ? size : ""}`, value, { size }); +} +const _typedSymbol = Symbol.for("_ethers_typed"); +export class Typed { + type; + value; + #options; + _typedSymbol; + constructor(gaurd, type, value, options = null) { + if (gaurd !== _gaurd) { + throw new Error("private constructor"); + } + defineProperties(this, { _typedSymbol, type, value }); + this.#options = options; + // Check the value is valid + this.format(); + } + format() { + if (this.type === "array") { + throw new Error(""); + } + else if (this.type === "dynamicArray") { + throw new Error(""); + } + else if (this.type === "tuple") { + return `tuple(${this.value.map((v) => v.format()).join(",")})`; + } + return this.type; + } + defaultValue() { + return 0; + } + minValue() { + return 0; + } + maxValue() { + return 0; + } + isBigInt() { + return !!(this.type.match(/^u?int[0-9]+$/)); + } + isData() { + return (this.type.substring(0, 5) === "bytes"); + } + isString() { + return (this.type === "string"); + } + get tupleName() { + if (this.type !== "tuple") { + throw TypeError("not a tuple"); + } + return this.#options; + } + // Returns the length of this type as an array + // - `null` indicates the length is unforced, it could be dynamic + // - `-1` indicates the length is dynamic + // - any other value indicates it is a static array and is its length + get arrayLength() { + if (this.type !== "array") { + throw TypeError("not an array"); + } + if (this.#options === true) { + return -1; + } + if (this.#options === false) { + return (this.value).length; + } + return null; + } + static from(type, value) { + return new Typed(_gaurd, type, value); + } + static uint8(v) { return n(v, 8); } + static uint16(v) { return n(v, 16); } + static uint24(v) { return n(v, 24); } + static uint32(v) { return n(v, 32); } + static uint40(v) { return n(v, 40); } + static uint48(v) { return n(v, 46); } + static uint56(v) { return n(v, 56); } + static uint64(v) { return n(v, 64); } + static uint72(v) { return n(v, 72); } + static uint80(v) { return n(v, 80); } + static uint88(v) { return n(v, 88); } + static uint96(v) { return n(v, 96); } + static uint104(v) { return n(v, 104); } + static uint112(v) { return n(v, 112); } + static uint120(v) { return n(v, 120); } + static uint128(v) { return n(v, 128); } + static uint136(v) { return n(v, 136); } + static uint144(v) { return n(v, 144); } + static uint152(v) { return n(v, 152); } + static uint160(v) { return n(v, 160); } + static uint168(v) { return n(v, 168); } + static uint176(v) { return n(v, 176); } + static uint184(v) { return n(v, 184); } + static uint192(v) { return n(v, 192); } + static uint200(v) { return n(v, 200); } + static uint208(v) { return n(v, 208); } + static uint216(v) { return n(v, 216); } + static uint224(v) { return n(v, 224); } + static uint232(v) { return n(v, 232); } + static uint240(v) { return n(v, 240); } + static uint248(v) { return n(v, 248); } + static uint256(v) { return n(v, 256); } + static uint(v) { return n(v, 256); } + static int8(v) { return n(v, -8); } + static int16(v) { return n(v, -16); } + static int24(v) { return n(v, -24); } + static int32(v) { return n(v, -32); } + static int40(v) { return n(v, -40); } + static int48(v) { return n(v, -46); } + static int56(v) { return n(v, -56); } + static int64(v) { return n(v, -64); } + static int72(v) { return n(v, -72); } + static int80(v) { return n(v, -80); } + static int88(v) { return n(v, -88); } + static int96(v) { return n(v, -96); } + static int104(v) { return n(v, -104); } + static int112(v) { return n(v, -112); } + static int120(v) { return n(v, -120); } + static int128(v) { return n(v, -128); } + static int136(v) { return n(v, -136); } + static int144(v) { return n(v, -144); } + static int152(v) { return n(v, -152); } + static int160(v) { return n(v, -160); } + static int168(v) { return n(v, -168); } + static int176(v) { return n(v, -176); } + static int184(v) { return n(v, -184); } + static int192(v) { return n(v, -192); } + static int200(v) { return n(v, -200); } + static int208(v) { return n(v, -208); } + static int216(v) { return n(v, -216); } + static int224(v) { return n(v, -224); } + static int232(v) { return n(v, -232); } + static int240(v) { return n(v, -240); } + static int248(v) { return n(v, -248); } + static int256(v) { return n(v, -256); } + static int(v) { return n(v, -256); } + static bytes(v) { return b(v); } + static bytes1(v) { return b(v, 1); } + static bytes2(v) { return b(v, 2); } + static bytes3(v) { return b(v, 3); } + static bytes4(v) { return b(v, 4); } + static bytes5(v) { return b(v, 5); } + static bytes6(v) { return b(v, 6); } + static bytes7(v) { return b(v, 7); } + static bytes8(v) { return b(v, 8); } + static bytes9(v) { return b(v, 9); } + static bytes10(v) { return b(v, 10); } + static bytes11(v) { return b(v, 11); } + static bytes12(v) { return b(v, 12); } + static bytes13(v) { return b(v, 13); } + static bytes14(v) { return b(v, 14); } + static bytes15(v) { return b(v, 15); } + static bytes16(v) { return b(v, 16); } + static bytes17(v) { return b(v, 17); } + static bytes18(v) { return b(v, 18); } + static bytes19(v) { return b(v, 19); } + static bytes20(v) { return b(v, 20); } + static bytes21(v) { return b(v, 21); } + static bytes22(v) { return b(v, 22); } + static bytes23(v) { return b(v, 23); } + static bytes24(v) { return b(v, 24); } + static bytes25(v) { return b(v, 25); } + static bytes26(v) { return b(v, 26); } + static bytes27(v) { return b(v, 27); } + static bytes28(v) { return b(v, 28); } + static bytes29(v) { return b(v, 29); } + static bytes30(v) { return b(v, 30); } + static bytes31(v) { return b(v, 31); } + static bytes32(v) { return b(v, 32); } + static address(v) { return new Typed(_gaurd, "address", v); } + static bool(v) { return new Typed(_gaurd, "bool", !!v); } + static string(v) { return new Typed(_gaurd, "string", v); } + static array(v, dynamic) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "array", v, dynamic); + } + static tuple(v, name) { + throw new Error("not implemented yet"); + return new Typed(_gaurd, "tuple", v, name); + } + static overrides(v) { + return new Typed(_gaurd, "overrides", Object.assign({}, v)); + } + static isTyped(value) { + return (value && value._typedSymbol === _typedSymbol); + } + static dereference(value, type) { + if (Typed.isTyped(value)) { + if (value.type !== type) { + throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); + } + return value.value; + } + return value; + } +} +//# sourceMappingURL=typed.js.map \ No newline at end of file diff --git a/lib.esm/abi/typed.js.map b/lib.esm/abi/typed.js.map new file mode 100644 index 000000000..cde3951d2 --- /dev/null +++ b/lib.esm/abi/typed.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typed.js","sourceRoot":"","sources":["../../src.ts/abi/typed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAO1D,MAAM,MAAM,GAAG,EAAG,CAAC;AAEnB,SAAS,CAAC,CAAC,KAAmB,EAAE,KAAa;IACzC,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,KAAK,GAAG,CAAC,EAAE;QACX,MAAM,GAAG,IAAI,CAAC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,OAAO,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,CAAmD,EAAE,IAAa;QAC3E,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;QACvC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,CAAC,SAAS,CAAC,CAAsB;QACnC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,EAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IACjE,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,KAAU;QACrB,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,YAAY,KAAK,YAAY,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,CAAC,WAAW,CAAI,KAAgB,EAAE,IAAY;QAChD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACtB,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,EAAE;gBACrB,MAAM,IAAI,KAAK,CAAC,0BAA2B,IAAK,SAAU,KAAK,CAAC,IAAK,EAAE,CAAC,CAAC;aAC5E;YACD,OAAO,KAAK,CAAC,KAAK,CAAC;SACtB;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/address/address.js b/lib.esm/address/address.js new file mode 100644 index 000000000..03125a231 --- /dev/null +++ b/lib.esm/address/address.js @@ -0,0 +1,109 @@ +import { keccak256 } from "../crypto/keccak.js"; +import { logger } from "../utils/logger.js"; +const BN_0 = BigInt(0); +const BN_36 = BigInt(36); +function getChecksumAddress(address) { + // if (!isHexString(address, 20)) { + // logger.throwArgumentError("invalid address", "address", address); + // } + address = address.toLowerCase(); + const chars = address.substring(2).split(""); + const expanded = new Uint8Array(40); + for (let i = 0; i < 40; i++) { + expanded[i] = chars[i].charCodeAt(0); + } + const hashed = logger.getBytes(keccak256(expanded)); + for (let i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return "0x" + chars.join(""); +} +// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number +// Create lookup table +const ibanLookup = {}; +for (let i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); +} +for (let i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +} +// How many decimal digits can we process? (for 64-bit float, this is 15) +// i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER)); +const safeDigits = 15; +function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + "00"; + let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join(""); + // Javascript can handle integers safely up to 15 (decimal) digits + while (expanded.length >= safeDigits) { + let block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + let checksum = String(98 - (parseInt(expanded, 10) % 97)); + while (checksum.length < 2) { + checksum = "0" + checksum; + } + return checksum; +} +; +const Base36 = (function () { + ; + const result = {}; + for (let i = 0; i < 36; i++) { + const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; + result[key] = BigInt(i); + } + return result; +})(); +function fromBase36(value) { + value = value.toLowerCase(); + let result = BN_0; + for (let i = 0; i < value.length; i++) { + result = result * BN_36 + Base36[value[i]]; + } + return result; +} +export function getAddress(address) { + if (typeof (address) !== "string") { + logger.throwArgumentError("invalid address", "address", address); + } + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + // Missing the 0x prefix + if (address.substring(0, 2) !== "0x") { + address = "0x" + address; + } + const result = getChecksumAddress(address); + // It is a checksummed address with a bad checksum + if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { + logger.throwArgumentError("bad address checksum", "address", address); + } + return result; + } + // Maybe ICAP? (we only support direct mode) + if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + // It is an ICAP address with a bad checksum + if (address.substring(2, 4) !== ibanChecksum(address)) { + logger.throwArgumentError("bad icap checksum", "address", address); + } + let result = fromBase36(address.substring(4)).toString(16); + while (result.length < 40) { + result = "0" + result; + } + return getChecksumAddress("0x" + result); + } + return logger.throwArgumentError("invalid address", "address", address); +} +export function getIcapAddress(address) { + //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase(); + let base36 = BigInt(getAddress(address)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = "0" + base36; + } + return "XE" + ibanChecksum("XE00" + base36) + base36; +} +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/lib.esm/address/address.js.map b/lib.esm/address/address.js.map new file mode 100644 index 000000000..2e4df420b --- /dev/null +++ b/lib.esm/address/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../src.ts/address/address.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG5C,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzB,SAAS,kBAAkB,CAAC,OAAe;IAC3C,sCAAsC;IACtC,2EAA2E;IAC3E,OAAO;IAEH,OAAO,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAEhC,MAAM,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAE7C,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACpC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE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AAE,CAAC,CAAC,KAAK,YAAY,CAAC,OAAO,CAAC,EAAE;YACnD,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;SACtE;QAED,IAAI,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC3D,OAAO,MAAM,CAAC,MAAM,GAAG,EAAE,EAAE;YAAE,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC;SAAE;QACrD,OAAQ,kBAAkB,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;KAC7C;IAED,OAAO,MAAM,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,OAAe;IAC1C,2EAA2E;IAC3E,IAAI,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACpE,OAAO,MAAM,CAAC,MAAM,GAAG,EAAE,EAAE;QAAE,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC;KAAE;IACrD,OAAO,IAAI,GAAG,YAAY,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC;AACzD,CAAC"} \ No newline at end of file diff --git a/lib.esm/address/checks.js b/lib.esm/address/checks.js new file mode 100644 index 000000000..0ecfc9a8b --- /dev/null +++ b/lib.esm/address/checks.js @@ -0,0 +1,46 @@ +import { logger } from "../utils/logger.js"; +import { getAddress } from "./address.js"; +export function isAddressable(value) { + return (value && typeof (value.getAddress) === "function"); +} +export function isAddress(value) { + try { + getAddress(value); + return true; + } + catch (error) { } + return false; +} +async function checkAddress(target, promise) { + const result = await promise; + if (result == null || result === "0x0000000000000000000000000000000000000000") { + if (typeof (target) === "string") { + return logger.throwError("unconfigured name", "UNCONFIGURED_NAME", { value: target }); + } + return logger.throwArgumentError("invalid AddressLike value; did not resolve to a value address", "target", target); + } + return getAddress(result); +} +// Resolves an Ethereum address, ENS name or Addressable object, +// throwing if the result is null. +export function resolveAddress(target, resolver) { + if (typeof (target) === "string") { + if (target.match(/^0x[0-9a-f]{40}$/i)) { + return getAddress(target); + } + if (resolver == null) { + return logger.throwError("ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + }); + } + return checkAddress(target, resolver.resolveName(target)); + } + else if (isAddressable(target)) { + return checkAddress(target, target.getAddress()); + } + else if (typeof (target.then) === "function") { + return checkAddress(target, target); + } + return logger.throwArgumentError("unsupported addressable value", "target", target); +} +//# sourceMappingURL=checks.js.map \ No newline at end of file diff --git a/lib.esm/address/checks.js.map b/lib.esm/address/checks.js.map new file mode 100644 index 000000000..c089f89ef --- /dev/null +++ b/lib.esm/address/checks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"checks.js","sourceRoot":"","sources":["../../src.ts/address/checks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAK1C,MAAM,UAAU,aAAa,CAAC,KAAU;IACpC,OAAO,CAAC,KAAK,IAAI,OAAM,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,UAAU,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,KAAU;IAChC,IAAI;QACA,UAAU,CAAC,KAAK,CAAC,CAAC;QAClB,OAAO,IAAI,CAAC;KACf;IAAC,OAAO,KAAK,EAAE,GAAG;IACnB,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,KAAK,UAAU,YAAY,CAAC,MAAW,EAAE,OAA+B;IACpE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC;IAC7B,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,KAAK,4CAA4C,EAAE;QAC3E,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,EAAE;YAC7B,OAAO,MAAM,CAAC,UAAU,CAAC,mBAAmB,EAAE,mBAAmB,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;SACzF;QACD,OAAO,MAAM,CAAC,kBAAkB,CAAC,+DAA+D,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;KACvH;IACD,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED,gEAAgE;AAChE,kCAAkC;AAClC,MAAM,UAAU,cAAc,CAAC,MAAmB,EAAE,QAA8B;IAE9E,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,EAAE;QAC7B,IAAI,MAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC,EAAE;YAAE,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC;SAAE;QAErE,IAAI,QAAQ,IAAI,IAAI,EAAE;YAClB,OAAO,MAAM,CAAC,UAAU,CAAC,oCAAoC,EAAE,uBAAuB,EAAE;gBACpF,SAAS,EAAE,aAAa;aAC3B,CAAC,CAAC;SACN;QAED,OAAO,YAAY,CAAC,MAAM,EAAE,QAAQ,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;KAE7D;SAAM,IAAI,aAAa,CAAC,MAAM,CAAC,EAAE;QAC9B,OAAO,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;KAEpD;SAAM,IAAI,OAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,UAAU,EAAE;QAC3C,OAAO,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KACvC;IAED,OAAO,MAAM,CAAC,kBAAkB,CAAC,+BAA+B,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACxF,CAAC"} \ No newline at end of file diff --git a/lib.esm/address/contract-address.js b/lib.esm/address/contract-address.js new file mode 100644 index 000000000..a464deab6 --- /dev/null +++ b/lib.esm/address/contract-address.js @@ -0,0 +1,32 @@ +import { keccak256 } from "../crypto/keccak.js"; +import { concat, dataSlice, encodeRlp, logger } from "../utils/index.js"; +import { getAddress } from "./address.js"; +// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed +export function getCreateAddress(tx) { + const from = getAddress(tx.from); + const nonce = logger.getBigInt(tx.nonce, "tx.nonce"); + let nonceHex = nonce.toString(16); + if (nonceHex === "0") { + nonceHex = "0x"; + } + else if (nonceHex.length % 2) { + nonceHex = "0x0" + nonceHex; + } + else { + nonceHex = "0x" + nonceHex; + } + return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12)); +} +export function getCreate2Address(_from, _salt, _initCodeHash) { + const from = getAddress(_from); + const salt = logger.getBytes(_salt, "salt"); + const initCodeHash = logger.getBytes(_initCodeHash, "initCodeHash"); + if (salt.length !== 32) { + logger.throwArgumentError("salt must be 32 bytes", "salt", _salt); + } + if (initCodeHash.length !== 32) { + logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); + } + return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12)); +} +//# sourceMappingURL=contract-address.js.map \ No newline at end of file diff --git a/lib.esm/address/contract-address.js.map b/lib.esm/address/contract-address.js.map new file mode 100644 index 000000000..956d46eb5 --- /dev/null +++ b/lib.esm/address/contract-address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract-address.js","sourceRoot":"","sources":["../../src.ts/address/contract-address.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAK1C,sGAAsG;AACtG,MAAM,UAAU,gBAAgB,CAAC,EAAyC;IACtE,MAAM,IAAI,GAAG,UAAU,CAAC,EAAE,CAAC,IAA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,CAAC,CAAC,CAAA;AAC7F,CAAC"} \ No newline at end of file diff --git a/lib.esm/address/index.js b/lib.esm/address/index.js new file mode 100644 index 000000000..7320061e6 --- /dev/null +++ b/lib.esm/address/index.js @@ -0,0 +1,4 @@ +export { getAddress, getIcapAddress } from "./address.js"; +export { getCreateAddress, getCreate2Address } from "./contract-address.js"; +export { isAddressable, isAddress, resolveAddress } from "./checks.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/address/index.js.map b/lib.esm/address/index.js.map new file mode 100644 index 000000000..c3ecc8e2e --- /dev/null +++ b/lib.esm/address/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/address/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE1D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG5E,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/addresses.js b/lib.esm/constants/addresses.js new file mode 100644 index 000000000..1cecec5d6 --- /dev/null +++ b/lib.esm/constants/addresses.js @@ -0,0 +1,5 @@ +/** + * A constant for the zero address. + */ +export const ZeroAddress = "0x0000000000000000000000000000000000000000"; +//# sourceMappingURL=addresses.js.map \ No newline at end of file diff --git a/lib.esm/constants/addresses.js.map b/lib.esm/constants/addresses.js.map new file mode 100644 index 000000000..4e3fbca4f --- /dev/null +++ b/lib.esm/constants/addresses.js.map @@ -0,0 +1 @@ +{"version":3,"file":"addresses.js","sourceRoot":"","sources":["../../src.ts/constants/addresses.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,4CAA4C,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/hashes.js b/lib.esm/constants/hashes.js new file mode 100644 index 000000000..da7b88b7f --- /dev/null +++ b/lib.esm/constants/hashes.js @@ -0,0 +1,5 @@ +/** + * A constant for the zero hash. + */ +export const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; +//# sourceMappingURL=hashes.js.map \ No newline at end of file diff --git a/lib.esm/constants/hashes.js.map b/lib.esm/constants/hashes.js.map new file mode 100644 index 000000000..bda460ccb --- /dev/null +++ b/lib.esm/constants/hashes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hashes.js","sourceRoot":"","sources":["../../src.ts/constants/hashes.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,oEAAoE,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/index.js b/lib.esm/constants/index.js new file mode 100644 index 000000000..ada7ac454 --- /dev/null +++ b/lib.esm/constants/index.js @@ -0,0 +1,5 @@ +export { ZeroAddress } from "./addresses.js"; +export { ZeroHash } from "./hashes.js"; +export { NegativeOne, Zero, One, Two, N, WeiPerEther, MaxUint256, MinInt256, MaxInt256 } from "./numbers.js"; +export { EtherSymbol, MessagePrefix } from "./strings.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/constants/index.js.map b/lib.esm/constants/index.js.map new file mode 100644 index 000000000..b8b1edc65 --- /dev/null +++ b/lib.esm/constants/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/constants/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EACH,WAAW,EACX,IAAI,EACJ,GAAG,EACH,GAAG,EACH,CAAC,EACD,WAAW,EACX,UAAU,EACV,SAAS,EACT,SAAS,EACZ,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/numbers.js b/lib.esm/constants/numbers.js new file mode 100644 index 000000000..6bf05b12c --- /dev/null +++ b/lib.esm/constants/numbers.js @@ -0,0 +1,38 @@ +/** + * A constant for the BigInt of -1. + */ +const NegativeOne = BigInt(-1); +/** + * A constant for the BigInt of 0. + */ +const Zero = BigInt(0); +/** + * A constant for the BigInt of 1. + */ +const One = BigInt(1); +/** + * A constant for the BigInt of 2. + */ +const Two = BigInt(2); +/** + * A constant for the order N for the secp256k1 curve. + */ +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +/** + * A constant for the number of wei in a single ether. + */ +const WeiPerEther = BigInt("1000000000000000000"); +/** + * A constant for the maximum value for a ``uint256``. + */ +const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +/** + * A constant for the minimum value for an ``int256``. + */ +const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * NegativeOne; +/** + * A constant for the maximum value for an ``int256``. + */ +const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +export { NegativeOne, Zero, One, Two, N, WeiPerEther, MaxUint256, MinInt256, MaxInt256, }; +//# sourceMappingURL=numbers.js.map \ No newline at end of file diff --git a/lib.esm/constants/numbers.js.map b/lib.esm/constants/numbers.js.map new file mode 100644 index 000000000..3fcd67e02 --- /dev/null +++ b/lib.esm/constants/numbers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numbers.js","sourceRoot":"","sources":["../../src.ts/constants/numbers.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAE/B;;GAEG;AACH,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvB;;GAEG;AACH,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEtB;;GAEG;AACH,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEtB;;GAEG;AACH,MAAM,CAAC,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAEvF;;GAEG;AACH,MAAM,WAAW,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAElD;;GAEG;AACH,MAAM,UAAU,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAEhG;;GAEG;AACH,MAAM,SAAS,GAAG,MAAM,CAAC,oEAAoE,CAAC,GAAG,WAAW,CAAC;AAE7G;;GAEG;AACH,MAAM,SAAS,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAE/F,OAAO,EACH,WAAW,EACX,IAAI,EACJ,GAAG,EACH,GAAG,EACH,CAAC,EACD,WAAW,EACX,UAAU,EACV,SAAS,EACT,SAAS,GACZ,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/strings.js b/lib.esm/constants/strings.js new file mode 100644 index 000000000..8d936b7ba --- /dev/null +++ b/lib.esm/constants/strings.js @@ -0,0 +1,7 @@ +// NFKC (composed) // (decomposed) +/** + * A constant for the ether symbol (normalized using NFKC). + */ +export const EtherSymbol = "\u039e"; // "\uD835\uDF63"; +export const MessagePrefix = "\x19Ethereum Signed Message:\n"; +//# sourceMappingURL=strings.js.map \ No newline at end of file diff --git a/lib.esm/constants/strings.js.map b/lib.esm/constants/strings.js.map new file mode 100644 index 000000000..b23ac4192 --- /dev/null +++ b/lib.esm/constants/strings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.js","sourceRoot":"","sources":["../../src.ts/constants/strings.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAE9C;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC,CAAE,kBAAkB;AAGxD,MAAM,CAAC,MAAM,aAAa,GAAG,gCAAgC,CAAC"} \ 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 000000000..7bae36360 --- /dev/null +++ b/lib.esm/contract/contract.js @@ -0,0 +1,642 @@ +import { resolveAddress } from "../address/index.js"; +import { Interface, Typed } from "../abi/index.js"; +import { defineProperties, isCallException, isHexString, resolveProperties, logger } from "../utils/index.js"; +import { copyRequest } from "../providers/index.js"; +import { ContractEventPayload, ContractTransactionResponse, EventLog } from "./wrappers.js"; +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 concisify(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +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) => { + return param.walkAsync(args[index], (type, value) => { + if (type === "address") { + 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 _WrappedMethodBase() { + return Function; +} +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; +} +export async function copyOverrides(arg) { + // Create a shallow copy (we'll deep-ify anything needed during normalizing) + const overrides = copyRequest(Typed.dereference(arg, "overrides")); + // Some sanity checking; these are what these methods adds + //if ((overrides).to) { + if (overrides.to) { + logger.throwArgumentError("cannot override to", "overrides.to", overrides.to); + } + else if (overrides.data) { + logger.throwArgumentError("cannot override data", "overrides.data", overrides.data); + } + // Resolve any from + if (overrides.from) { + overrides.from = await resolveAddress(overrides.from); + } + return overrides; +} +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) => { + if (type === "address") { + return resolveAddress(value, resolver); + } + return value; + }); + })); +} +class WrappedMethod extends _WrappedMethodBase() { + name = ""; // Investigate! + _contract; + _key; + constructor(contract, key) { + super(); + defineProperties(this, { + name: contract.interface.getFunctionName(key), + _contract: contract, _key: key + }); + const proxy = new Proxy(this, { + // Perform the default operation for this fragment type + apply: async (target, thisArg, args) => { + const fragment = target.getFragment(...args); + if (fragment.constant) { + return await target.staticCall(...args); + } + return await target.send(...args); + }, + }); + return proxy; + } + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + get fragment() { + return this._contract.interface.getFunction(this._key); + } + getFragment(...args) { + return this._contract.interface.getFunction(this._key, args); + } + async populateTransaction(...args) { + const fragment = this.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()); + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(this._contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await resolveProperties({ + to: this._contract.getAddress(), + data: this._contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + } + async staticCall(...args) { + const result = await this.staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + } + async send(...args) { + const runner = this._contract.runner; + if (!canSend(runner)) { + return logger.throwError("contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + } + const tx = await runner.sendTransaction(await this.populateTransaction(...args)); + const provider = getProvider(this._contract.runner); + return new ContractTransactionResponse(this._contract.interface, provider, tx); + } + async estimateGas(...args) { + const runner = getRunner(this._contract.runner, "estimateGas"); + if (!canEstimate(runner)) { + return logger.throwError("contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { + operation: "estimateGas" + }); + } + return await runner.estimateGas(await this.populateTransaction(...args)); + } + async staticCallResult(...args) { + const runner = getRunner(this._contract.runner, "call"); + if (!canCall(runner)) { + return logger.throwError("contract runner does not support calling", "UNSUPPORTED_OPERATION", { + operation: "call" + }); + } + const fragment = this.getFragment(...args); + const tx = await this.populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } + catch (error) { + if (isCallException(error)) { + throw this._contract.interface.makeError(fragment, error.data, tx); + } + throw error; + } + return this._contract.interface.decodeFunctionResult(fragment, result); + } +} +function _WrappedEventBase() { + return Function; +} +class WrappedEvent extends _WrappedEventBase() { + name = ""; // @TODO: investigate + _contract; + _key; + constructor(contract, key) { + super(); + defineProperties(this, { + name: contract.interface.getEventName(key), + _contract: contract, _key: key + }); + return new Proxy(this, { + // Perform the default operation for this fragment type + apply: async (target, thisArg, args) => { + return new PreparedTopicFilter(contract, target.getFragment(...args), args); + }, + }); + } + // Only works on non-ambiguous keys + get fragment() { + return this._contract.interface.getEvent(this._key); + } + getFragment(...args) { + return this._contract.interface.getEvent(this._key, args); + } +} +; +// 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("_ethersInternal_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 getSubTag(contract, event) { + let fragment; + let topics; + if (Array.isArray(event)) { + // Topics; e.g. `[ "0x1234...89ab" ]` + fragment = contract.interface.getEvent(event[0]); + topics = event; + } + else if (typeof (event) === "string") { + // Event name (name or signature); `"Transfer"` + fragment = contract.interface.getEvent(event); + topics = [contract.interface.getEventTopic(fragment)]; + } + else if (isDeferred(event)) { + // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` + fragment = event.fragment; + topics = await event.getTopicFilter(); + } + else if ("fragment" in event) { + // ContractEvent; e.g. `contract.filter.Transfer` + fragment = event.fragment; + topics = [contract.interface.getEventTopic(fragment)]; + } + else { + console.log(event); + throw new Error("TODO"); + } + // Normalize topics and sort TopicSets + topics = topics.map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + 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 getSubTag(contract, event)).tag) || null; +} +async function getSub(contract, event) { + // Make sure our runner can actually subscribe to events + const provider = getProvider(contract.runner); + if (!provider) { + return logger.throwError("contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { + operation: "on" + }); + } + const { fragment, tag, topics } = await getSubTag(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) => { + const payload = new ContractEventPayload(contract, null, event, fragment, log); + emit(contract, event, payload.args, payload); + }; + let started = false; + const start = () => { + if (started) { + return; + } + provider.on(filter, listener); + started = true; + }; + const stop = () => { + if (!started) { + return; + } + provider.off(filter, listener); + started = false; + }; + 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, payload) { + 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 = args.slice(); + if (payload) { + passArgs.push(new ContractEventPayload(contract, (once ? null : listener), event, payload.fragment, payload.log)); + } + try { + listener.call(contract, ...passArgs); + } + catch (error) { } + return !once; + }); + return (count > 0); +} +async function emit(contract, event, args, payload) { + try { + await lastEmit; + } + catch (error) { } + const resultPromise = _emit(contract, event, args, payload); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +export class BaseContract { + target; + interface; + runner; + filters; + [internal]; + constructor(target, abi, runner = null, _deployTx) { + 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); + 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 logger.makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr) => { + if (addr == null) { + throw new Error("TODO"); + } + 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 (passProperties.indexOf(_prop) >= 0) { + return Reflect.get(target, _prop, receiver); + } + const prop = String(_prop); + const result = this.getEvent(prop); + if (result) { + return result; + } + throw new Error(`unknown contract event: ${prop}`); + } + }); + defineProperties(this, { filters }); + // Return a Proxy that will respond to functions + return new Proxy(this, { + get: (target, _prop, receiver) => { + if (_prop in target || passProperties.indexOf(_prop) >= 0) { + return Reflect.get(target, _prop, receiver); + } + const prop = String(_prop); + const result = target.getFunction(prop); + if (result) { + return result; + } + throw new Error(`unknown contract method: ${prop}`); + } + }); + } + async getAddress() { return await getInternal(this).addrPromise; } + async getDeployedCode() { + const provider = getProvider(this.runner); + if (!provider) { + return logger.throwError("runner does not support .provider", "UNSUPPORTED_OPERATION", { + operation: "getDeployedCode" + }); + } + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; + } + return code; + } + 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); + if (provider == null) { + return logger.throwError("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(); + }); + } + deploymentTransaction() { + return getInternal(this).deployTx; + } + getFunction(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return (new WrappedMethod(this, key)); + } + getEvent(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return (new WrappedEvent(this, key)); + } + async queryTransaction(hash) { + // Is this useful? + throw new Error("@TODO"); + } + async queryFilter(event, fromBlock = 0, toBlock = "latest") { + const { addr, addrPromise } = getInternal(this); + const address = (addr ? addr : (await addrPromise)); + const { fragment, topics } = await getSubTag(this, event); + const filter = { address, topics, fromBlock, toBlock }; + const provider = getProvider(this.runner); + if (!provider) { + return logger.throwError("contract runner does not have a provider", "UNSUPPORTED_OPERATION", { + operation: "queryFilter" + }); + } + return (await provider.getLogs(filter)).map((log) => { + return new EventLog(log, this.interface, fragment); + }); + } + async on(event, listener) { + const sub = await getSub(this, event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + async once(event, listener) { + const sub = await getSub(this, event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + async emit(event, ...args) { + return await emit(this, event, args, null); + } + 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; + } + 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; + } + 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; + } + 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); + } + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null) { + super(address, abi, runner); + } + } + return CustomContract; + } + ; + static from(target, abi, runner = null) { + const contract = new this(target, abi, runner); + return contract; + } +} +function _ContractBase() { + return BaseContract; +} +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 000000000..97259c284 --- /dev/null +++ b/lib.esm/contract/contract.js.map @@ -0,0 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P,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;aACpB;SACJ;QAED,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,iBAAiB;IACjB,KAAK,CAAC,WAAW,CAAC,KAAwB,EAAE,QAAkB;QAC1D,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED,kBAAkB;IAClB,KAAK,CAAC,cAAc,CAAC,KAAwB,EAAE,QAAkB;QAC7D,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC3C,CAAC;IAED,MAAM,CAAC,UAAU,CAAwB,GAAiB;QACtD,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,MAAM,CAAC,IAAI,CAAwB,MAAc,EAAE,GAAiB,EAAE,SAAgC,IAAI;QACtG,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,QAAe,CAAC;IAC3B,CAAC;CACJ;AAED,SAAS,aAAa;IAClB,OAAO,YAAmB,CAAC;AAC/B,CAAC;AAED,MAAM,OAAO,QAAS,SAAQ,aAAa,EAAE;CAAI"} \ 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 000000000..9b1ad77cd --- /dev/null +++ b/lib.esm/contract/factory.js @@ -0,0 +1,75 @@ +import { Interface } from "../abi/index.js"; +import { getCreateAddress } from "../address/index.js"; +import { concat, defineProperties, hexlify, logger } from "../utils/index.js"; +import { BaseContract, copyOverrides, resolveArgs } from "./contract.js"; +// A = Arguments to the constructor +// I = Interface of deployed contracts +export class ContractFactory { + interface; + bytecode; + runner; + 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(logger.getBytes(bytecode)); + } + else { + if (typeof (bytecode) === "object") { + bytecode = bytecode.object; + } + if (bytecode.substring(0, 2) !== "0x") { + bytecode = "0x" + bytecode; + } + bytecode = hexlify(logger.getBytes(bytecode)); + } + defineProperties(this, { + bytecode, interface: iface, runner: (runner || null) + }); + } + async getDeployTransaction(...args) { + let overrides = {}; + const fragment = this.interface.deploy; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + } + 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({}, overrides, { data }); + } + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + if (!this.runner || typeof (this.runner.sendTransaction) !== "function") { + return logger.throwError("factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + } + const sentTx = await this.runner.sendTransaction(tx); + const address = getCreateAddress(sentTx); + return new BaseContract(address, this.interface, this.runner, sentTx); + } + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); + } + static fromSolidity(output, runner) { + if (output == null) { + logger.throwArgumentError("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 000000000..083d10f0a --- /dev/null +++ b/lib.esm/contract/factory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.js","sourceRoot":"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AAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjF,CAAC;IAED,OAAO,CAAC,MAA6B;QACjC,OAAO,IAAI,eAAe,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACtE,CAAC;IAED,MAAM,CAAC,YAAY,CAA2D,MAAW,EAAE,MAAuB;QAC9G,IAAI,MAAM,IAAI,IAAI,EAAE;YAChB,MAAM,CAAC,kBAAkB,CAAC,qBAAqB,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;SACtE;QAED,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/index.js b/lib.esm/contract/index.js new file mode 100644 index 000000000..e4c5e57c9 --- /dev/null +++ b/lib.esm/contract/index.js @@ -0,0 +1,4 @@ +export { BaseContract, Contract } from "./contract.js"; +export { ContractFactory } from "./factory.js"; +export { ContractEventPayload, ContractTransactionReceipt, ContractTransactionResponse, EventLog } from "./wrappers.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/contract/index.js.map b/lib.esm/contract/index.js.map new file mode 100644 index 000000000..83eef87e7 --- /dev/null +++ b/lib.esm/contract/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/contract/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,YAAY,EAAE,QAAQ,EACzB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACH,eAAe,EAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACH,oBAAoB,EAAE,0BAA0B,EAAE,2BAA2B,EAC7E,QAAQ,EACX,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/lib.esm/contract/types.js b/lib.esm/contract/types.js new file mode 100644 index 000000000..14353c789 --- /dev/null +++ b/lib.esm/contract/types.js @@ -0,0 +1,5 @@ +; +; +; +export {}; +//# sourceMappingURL=types.js.map \ 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 000000000..544405712 --- /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":"AAeC,CAAC;AAiBqE,CAAC;AAkDvE,CAAC"} \ 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 000000000..c5a27e573 --- /dev/null +++ b/lib.esm/contract/wrappers.js @@ -0,0 +1,73 @@ +import { Log, TransactionReceipt, TransactionResponse } from "../providers/index.js"; +import { defineProperties, EventPayload } from "../utils/index.js"; +export class EventLog extends Log { + interface; + fragment; + args; + constructor(log, iface, fragment) { + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + defineProperties(this, { args, fragment, interface: iface }); + } + get eventName() { return this.fragment.name; } + get eventSignature() { return this.fragment.format(); } +} +export class ContractTransactionReceipt extends TransactionReceipt { + #interface; + constructor(iface, provider, tx) { + super(tx, provider); + this.#interface = iface; + } + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? this.#interface.getEvent(log.topics[0]) : null; + if (fragment) { + return new EventLog(log, this.#interface, fragment); + } + else { + return log; + } + }); + } +} +export class ContractTransactionResponse extends TransactionResponse { + #interface; + constructor(iface, provider, tx) { + super(tx, provider); + this.#interface = iface; + } + async wait(confirms) { + const receipt = await super.wait(); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(this.#interface, this.provider, receipt); + } +} +export class ContractEventPayload extends EventPayload { + fragment; + log; + args; + constructor(contract, listener, filter, fragment, _log) { + super(contract, listener, filter); + const log = new EventLog(_log, contract.interface, fragment); + const args = contract.interface.decodeEventLog(fragment, log.data, log.topics); + defineProperties(this, { args, fragment, log }); + } + get eventName() { + return this.fragment.name; + } + get eventSignature() { + return this.fragment.format(); + } + async getBlock() { + return await this.log.getBlock(); + } + async getTransaction() { + return await this.log.getTransaction(); + } + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); + } +} +//# 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 000000000..8bf63ce9c --- /dev/null +++ b/lib.esm/contract/wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wrappers.js","sourceRoot":"","sources":["../../src.ts/contract/wrappers.ts"],"names":[],"mappings":"AAAA,OAAO,EACI,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EACtD,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAYnE,MAAM,OAAO,QAAS,SAAQ,GAAG;IACpB,SAAS,CAAa;IACtB,QAAQ,CAAiB;IACzB,IAAI,CAAU;IAEvB,YAAY,GAAQ,EAAE,KAAgB,EAAE,QAAuB;QAC3D,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QACzB,MAAM,IAAI,GAAG,KAAK,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAA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AAC;IAClD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/crypto/crypto-browser.js b/lib.esm/crypto/crypto-browser.js new file mode 100644 index 000000000..28d82d073 --- /dev/null +++ b/lib.esm/crypto/crypto-browser.js @@ -0,0 +1,56 @@ +/* Browser Crypto Shims */ +import { hmac } from "@noble/hashes/hmac"; +import { pbkdf2 } from "@noble/hashes/pbkdf2"; +import { sha256 } from "@noble/hashes/sha256"; +import { sha512 } from "@noble/hashes/sha512"; +import { logger } from "../utils/logger.js"; +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const anyGlobal = getGlobal(); +const crypto = anyGlobal.crypto || anyGlobal.msCrypto; +export function createHash(algo) { + switch (algo) { + case "sha256": return sha256.create(); + case "sha512": return sha512.create(); + } + return logger.throwArgumentError("invalid hashing algorithm name", "algorithm", algo); +} +export function createHmac(_algo, key) { + const algo = ({ sha256, sha512 }[_algo]); + if (algo == null) { + return logger.throwArgumentError("invalid hmac algorithm", "algorithm", _algo); + } + return hmac.create(algo, key); +} +export function pbkdf2Sync(password, salt, iterations, keylen, _algo) { + const algo = ({ sha256, sha512 }[_algo]); + if (algo == null) { + return logger.throwArgumentError("invalid pbkdf2 algorithm", "algorithm", _algo); + } + return pbkdf2(algo, password, salt, { c: iterations, dkLen: keylen }); +} +export function randomBytes(length) { + if (crypto == null) { + return logger.throwError("platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { + operation: "randomBytes" + }); + } + if (!Number.isInteger(length) || length <= 0 || length > 1024) { + logger.throwArgumentError("invalid length", "length", length); + } + const result = new Uint8Array(length); + crypto.getRandomValues(result); + return result; +} +//# sourceMappingURL=crypto-browser.js.map \ No newline at end of file diff --git a/lib.esm/crypto/crypto-browser.js.map b/lib.esm/crypto/crypto-browser.js.map new file mode 100644 index 000000000..2861ff067 --- /dev/null +++ b/lib.esm/crypto/crypto-brow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mode 100644 index 000000000..05475e30b --- /dev/null +++ b/lib.esm/crypto/crypto.js @@ -0,0 +1,2 @@ +export { createHash, createHmac, pbkdf2Sync, randomBytes } from "crypto"; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/lib.esm/crypto/crypto.js.map b/lib.esm/crypto/crypto.js.map new file mode 100644 index 000000000..1ff179cf9 --- /dev/null +++ b/lib.esm/crypto/crypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src.ts/crypto/crypto.ts"],"names":[],"mappings":"AACA,OAAO,EACH,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAClD,MAAM,QAAQ,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/hmac.js b/lib.esm/crypto/hmac.js new file mode 100644 index 000000000..aa1f58763 --- /dev/null +++ b/lib.esm/crypto/hmac.js @@ -0,0 +1,22 @@ +import { createHmac } from "./crypto.js"; +import { hexlify, logger } from "../utils/index.js"; +let locked = false; +const _computeHmac = function (algorithm, key, data) { + return "0x" + createHmac(algorithm, key).update(data).digest("hex"); +}; +let __computeHmac = _computeHmac; +export function computeHmac(algorithm, _key, _data) { + const key = logger.getBytes(_key, "key"); + const data = logger.getBytes(_data, "data"); + return hexlify(__computeHmac(algorithm, key, data)); +} +computeHmac._ = _computeHmac; +computeHmac.lock = function () { locked = true; }; +computeHmac.register = function (func) { + if (locked) { + throw new Error("computeHmac is locked"); + } + __computeHmac = func; +}; +Object.freeze(computeHmac); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/lib.esm/crypto/hmac.js.map b/lib.esm/crypto/hmac.js.map new file mode 100644 index 000000000..4e54e391e --- /dev/null +++ b/lib.esm/crypto/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["../../src.ts/crypto/hmac.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,YAAY,GAAG,UAAS,SAA8B,EAAE,GAAe,EAAE,IAAgB;IAC3F,OAAO,IAAI,GAAG,UAAU,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACxE,CAAC,CAAA;AAED,IAAI,aAAa,GAAG,YAAY,CAAC;AAEjC,MAAM,UAAU,WAAW,CAAC,SAA8B,EAAE,IAAe,EAAE,KAAgB;IACzF,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACzC,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,OAAO,CAAC,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AACD,WAAW,CAAC,CAAC,GAAG,YAAY,CAAC;AAC7B,WAAW,CAAC,IAAI,GAAI,cAAa,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACjD,WAAW,CAAC,QAAQ,GAAG,UAAS,IAAsF;IAClH,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;KAAE;IACzD,aAAa,GAAG,IAAI,CAAC;AACzB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/index.js b/lib.esm/crypto/index.js new file mode 100644 index 000000000..7a7e3e03c --- /dev/null +++ b/lib.esm/crypto/index.js @@ -0,0 +1,24 @@ +// We import all these so we can export lock() +import { computeHmac } from "./hmac.js"; +import { keccak256 } from "./keccak.js"; +import { ripemd160 } from "./ripemd160.js"; +import { pbkdf2 } from "./pbkdf2.js"; +import { randomBytes } from "./random.js"; +import { scrypt, scryptSync } from "./scrypt.js"; +import { sha256, sha512 } from "./sha2.js"; +export { computeHmac, randomBytes, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync }; +export { SigningKey } from "./signing-key.js"; +export { Signature } from "./signature.js"; +function lock() { + computeHmac.lock(); + keccak256.lock(); + pbkdf2.lock(); + randomBytes.lock(); + ripemd160.lock(); + scrypt.lock(); + scryptSync.lock(); + sha256.lock(); + sha512.lock(); +} +export { lock }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/crypto/index.js.map b/lib.esm/crypto/index.js.map new file mode 100644 index 000000000..ef57cfaf3 --- /dev/null +++ b/lib.esm/crypto/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/crypto/index.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAE3C,OAAO,EACH,WAAW,EAEX,WAAW,EAEX,SAAS,EACT,SAAS,EACT,MAAM,EAAE,MAAM,EAEd,MAAM,EACN,MAAM,EAAE,UAAU,EACrB,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,SAAS,IAAI;IACT,WAAW,CAAC,IAAI,EAAE,CAAC;IACnB,SAAS,CAAC,IAAI,EAAE,CAAC;IACjB,MAAM,CAAC,IAAI,EAAE,CAAC;IACd,WAAW,CAAC,IAAI,EAAE,CAAC;IACnB,SAAS,CAAC,IAAI,EAAE,CAAC;IACjB,MAAM,CAAC,IAAI,EAAE,CAAC;IACd,UAAU,CAAC,IAAI,EAAE,CAAC;IAClB,MAAM,CAAC,IAAI,EAAE,CAAC;IACd,MAAM,CAAC,IAAI,EAAE,CAAC;AAClB,CAAC;AAED,OAAO,EAAE,IAAI,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/keccak.js b/lib.esm/crypto/keccak.js new file mode 100644 index 000000000..c06128639 --- /dev/null +++ b/lib.esm/crypto/keccak.js @@ -0,0 +1,21 @@ +import { keccak_256 } from "@noble/hashes/sha3"; +import { hexlify, logger } from "../utils/index.js"; +let locked = false; +const _keccak256 = function (data) { + return keccak_256(data); +}; +let __keccak256 = _keccak256; +export function keccak256(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__keccak256(data)); +} +keccak256._ = _keccak256; +keccak256.lock = function () { locked = true; }; +keccak256.register = function (func) { + if (locked) { + throw new TypeError("keccak256 is locked"); + } + __keccak256 = func; +}; +Object.freeze(keccak256); +//# sourceMappingURL=keccak.js.map \ No newline at end of file diff --git a/lib.esm/crypto/keccak.js.map b/lib.esm/crypto/keccak.js.map new file mode 100644 index 000000000..1cb095dad --- /dev/null +++ b/lib.esm/crypto/keccak.js.map @@ -0,0 +1 @@ +{"version":3,"file":"keccak.js","sourceRoot":"","sources":["../../src.ts/crypto/keccak.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,UAAU,GAAG,UAAS,IAAgB;IACxC,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC,CAAA;AAED,IAAI,WAAW,GAAoC,UAAU,CAAC;AAE9D,MAAM,UAAU,SAAS,CAAC,KAAgB;IACtC,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AACD,SAAS,CAAC,CAAC,GAAG,UAAU,CAAC;AACzB,SAAS,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,SAAS,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC/D,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;KAAE;IAC3D,WAAW,GAAG,IAAI,CAAC;AACvB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/pbkdf2.js b/lib.esm/crypto/pbkdf2.js new file mode 100644 index 000000000..58b2f523a --- /dev/null +++ b/lib.esm/crypto/pbkdf2.js @@ -0,0 +1,22 @@ +import { pbkdf2Sync } from "./crypto.js"; +import { hexlify, logger } from "../utils/index.js"; +let locked = false; +const _pbkdf2 = function (password, salt, iterations, keylen, algo) { + return pbkdf2Sync(password, salt, iterations, keylen, algo); +}; +let __pbkdf2 = _pbkdf2; +export function pbkdf2(_password, _salt, iterations, keylen, algo) { + const password = logger.getBytes(_password, "password"); + const salt = logger.getBytes(_salt, "salt"); + return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); +} +pbkdf2._ = _pbkdf2; +pbkdf2.lock = function () { locked = true; }; +pbkdf2.register = function (func) { + if (locked) { + throw new Error("pbkdf2 is locked"); + } + __pbkdf2 = func; +}; +Object.freeze(pbkdf2); +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/lib.esm/crypto/pbkdf2.js.map b/lib.esm/crypto/pbkdf2.js.map new file mode 100644 index 000000000..59626268c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CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/random.js b/lib.esm/crypto/random.js new file mode 100644 index 000000000..becb58355 --- /dev/null +++ b/lib.esm/crypto/random.js @@ -0,0 +1,19 @@ +import { randomBytes as crypto_random } from "./crypto.js"; +let locked = false; +const _randomBytes = function (length) { + return new Uint8Array(crypto_random(length)); +}; +let __randomBytes = _randomBytes; +export function randomBytes(length) { + return __randomBytes(length); +} +randomBytes._ = _randomBytes; +randomBytes.lock = function () { locked = true; }; +randomBytes.register = function (func) { + if (locked) { + throw new Error("random is locked"); + } + __randomBytes = func; +}; +Object.freeze(randomBytes); +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/lib.esm/crypto/random.js.map b/lib.esm/crypto/random.js.map new file mode 100644 index 000000000..5e3fd6266 --- /dev/null +++ b/lib.esm/crypto/random.js.map @@ -0,0 +1 @@ +{"version":3,"file":"random.js","sourceRoot":"","sources":["../../src.ts/crypto/random.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,IAAI,aAAa,EAAE,MAAM,aAAa,CAAC;AAE3D,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,YAAY,GAAG,UAAS,MAAc;IACxC,OAAO,IAAI,UAAU,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;AACjD,CAAC,CAAA;AAED,IAAI,aAAa,GAAG,YAAY,CAAC;AAEjC,MAAM,UAAU,WAAW,CAAC,MAAc;IACtC,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC;AACjC,CAAC;AAED,WAAW,CAAC,CAAC,GAAG,YAAY,CAAC;AAC7B,WAAW,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACtD,WAAW,CAAC,QAAQ,GAAG,UAAS,IAAoC;IAChE,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACpD,aAAa,GAAG,IAAI,CAAC;AACzB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/ripemd160.js b/lib.esm/crypto/ripemd160.js new file mode 100644 index 000000000..f8bc34704 --- /dev/null +++ b/lib.esm/crypto/ripemd160.js @@ -0,0 +1,21 @@ +import { ripemd160 as noble_ripemd160 } from "@noble/hashes/ripemd160"; +import { hexlify, logger } from "../utils/index.js"; +let locked = false; +const _ripemd160 = function (data) { + return noble_ripemd160(data); +}; +let __ripemd160 = _ripemd160; +export function ripemd160(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__ripemd160(data)); +} +ripemd160._ = _ripemd160; +ripemd160.lock = function () { locked = true; }; +ripemd160.register = function (func) { + if (locked) { + throw new TypeError("ripemd160 is locked"); + } + __ripemd160 = func; +}; +Object.freeze(ripemd160); +//# sourceMappingURL=ripemd160.js.map \ No newline at end of file diff --git a/lib.esm/crypto/ripemd160.js.map b/lib.esm/crypto/ripemd160.js.map new file mode 100644 index 000000000..23c10c3bd --- /dev/null +++ b/lib.esm/crypto/ripemd160.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.js","sourceRoot":"","sources":["../../src.ts/crypto/ripemd160.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,IAAI,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAEvE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAKpD,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,MAAM,UAAU,GAAG,UAAS,IAAgB;IACxC,OAAO,eAAe,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC,CAAA;AAED,IAAI,WAAW,GAAoC,UAAU,CAAC;AAE9D,MAAM,UAAU,SAAS,CAAC,KAAgB;IACtC,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,OAAO,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AACD,SAAS,CAAC,CAAC,GAAG,UAAU,CAAC;AACzB,SAAS,CAAC,IAAI,GAAG,cAAmB,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,SAAS,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC/D,IAAI,MAAM,EAAE;QAAE,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;KAAE;IAC3D,WAAW,GAAG,IAAI,CAAC;AACvB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/scrypt.js b/lib.esm/crypto/scrypt.js new file mode 100644 index 000000000..816e9043d --- /dev/null +++ b/lib.esm/crypto/scrypt.js @@ -0,0 +1,40 @@ +import { scrypt as _nobleSync, scryptAsync as _nobleAsync } from "@noble/hashes/scrypt"; +import { hexlify as H, logger } from "../utils/index.js"; +let lockedSync = false, lockedAsync = false; +const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) { + return await _nobleAsync(passwd, salt, { N, r, p, dkLen, onProgress }); +}; +const _scryptSync = function (passwd, salt, N, r, p, dkLen) { + return _nobleSync(passwd, salt, { N, r, p, dkLen }); +}; +let __scryptAsync = _scryptAsync; +let __scryptSync = _scryptSync; +export async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) { + const passwd = logger.getBytes(_passwd, "passwd"); + const salt = logger.getBytes(_salt, "salt"); + return H(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); +} +scrypt._ = _scryptAsync; +scrypt.lock = function () { lockedAsync = true; }; +scrypt.register = function (func) { + if (lockedAsync) { + throw new Error("scrypt is locked"); + } + __scryptAsync = func; +}; +Object.freeze(scrypt); +export function scryptSync(_passwd, _salt, N, r, p, dkLen) { + const passwd = logger.getBytes(_passwd, "passwd"); + const salt = logger.getBytes(_salt, "salt"); + return H(__scryptSync(passwd, salt, N, r, p, dkLen)); +} +scryptSync._ = _scryptSync; +scryptSync.lock = function () { lockedSync = true; }; +scryptSync.register = function (func) { + if (lockedSync) { + throw new Error("scryptSync is locked"); + } + __scryptSync = func; +}; +Object.freeze(scryptSync); +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/lib.esm/crypto/scrypt.js.map b/lib.esm/crypto/scrypt.js.map new file mode 100644 index 000000000..9941ce012 --- /dev/null +++ b/lib.esm/crypto/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["../../src.ts/crypto/scrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,WAAW,IAAI,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExF,OAAO,EAAE,OAAO,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQzD,IAAI,UAAU,GAAG,KAAK,EAAE,WAAW,GAAG,KAAK,CAAC;AAE5C,MAAM,YAAY,GAAG,KAAK,WAAU,MAAkB,EAAE,IAAgB,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,KAAa,EAAE,UAA6B;IACnJ,OAAO,MAAM,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;AAC3E,CAAC,CAAA;AACD,MAAM,WAAW,GAAG,UAAS,MAAkB,EAAE,IAAgB,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,KAAa;IAC7G,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AACxD,CAAC,CAAA;AAED,IAAI,aAAa,GAAgJ,YAAY,CAAC;AAC9K,IAAI,YAAY,GAAwG,WAAW,CAAA;AAGnI,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,OAAkB,EAAE,KAAgB,EA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ACzD,UAAU,CAAC,QAAQ,GAAG,UAAS,IAAyG;IACpI,IAAI,UAAU,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KAAE;IAC5D,YAAY,GAAG,IAAI,CAAC;AACxB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/sha2.js b/lib.esm/crypto/sha2.js new file mode 100644 index 000000000..1cd63a645 --- /dev/null +++ b/lib.esm/crypto/sha2.js @@ -0,0 +1,38 @@ +import { createHash } from "./crypto.js"; +import { hexlify, logger } from "../utils/index.js"; +const _sha256 = function (data) { + return createHash("sha256").update(data).digest(); +}; +const _sha512 = function (data) { + return createHash("sha512").update(data).digest(); +}; +let __sha256 = _sha256; +let __sha512 = _sha512; +let locked256 = false, locked512 = false; +export function sha256(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__sha256(data)); +} +sha256._ = _sha256; +sha256.lock = function () { locked256 = true; }; +sha256.register = function (func) { + if (locked256) { + throw new Error("sha256 is locked"); + } + __sha256 = func; +}; +Object.freeze(sha256); +export function sha512(_data) { + const data = logger.getBytes(_data, "data"); + return hexlify(__sha512(data)); +} +sha512._ = _sha512; +sha512.lock = function () { locked512 = true; }; +sha512.register = function (func) { + if (locked512) { + throw new Error("sha512 is locked"); + } + __sha512 = func; +}; +Object.freeze(sha256); +//# sourceMappingURL=sha2.js.map \ No newline at end of file diff --git a/lib.esm/crypto/sha2.js.map b/lib.esm/crypto/sha2.js.map new file mode 100644 index 000000000..03533e5fe --- /dev/null +++ b/lib.esm/crypto/sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.js","sourceRoot":"","sources":["../../src.ts/crypto/sha2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAKpD,MAAM,O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,IAAI,CAAC,CAAC,CAAC,CAAA;AACpD,MAAM,CAAC,QAAQ,GAAG,UAAS,IAAqC;IAC5D,IAAI,SAAS,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;KAAE;IACvD,QAAQ,GAAG,IAAI,CAAC;AACpB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/crypto/signature.js b/lib.esm/crypto/signature.js new file mode 100644 index 000000000..12fc33a58 --- /dev/null +++ b/lib.esm/crypto/signature.js @@ -0,0 +1,229 @@ +import { ZeroHash } from "../constants/index.js"; +import { concat, dataLength, getStore, hexlify, isHexString, logger, setStore } from "../utils/index.js"; +// Constants +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const _guard = {}; +export class Signature { + #props; + get r() { return getStore(this.#props, "r"); } + set r(value) { + if (dataLength(value) !== 32) { + logger.throwArgumentError("invalid r", "value", value); + } + setStore(this.#props, "r", hexlify(value)); + } + get s() { return getStore(this.#props, "s"); } + set s(value) { + if (dataLength(value) !== 32) { + logger.throwArgumentError("invalid r", "value", value); + } + else if (logger.getBytes(value)[0] & 0x80) { + logger.throwArgumentError("non-canonical s", "value", value); + } + setStore(this.#props, "s", hexlify(value)); + } + get v() { return getStore(this.#props, "v"); } + set v(value) { + const v = logger.getNumber(value, "value"); + if (v !== 27 && v !== 28) { + throw new Error("@TODO"); + } + setStore(this.#props, "v", v); + } + get networkV() { return getStore(this.#props, "networkV"); } + get legacyChainId() { + const v = this.networkV; + if (v == null) { + return null; + } + return Signature.getChainId(v); + } + get yParity() { + if (this.v === 27) { + return 0; + } + return 1; + /* + // When v is 0 or 1 it is the recid directly + if (this.v.isZero()) { return 0; } + if (this.v.eq(1)) { return 1; } + + // Otherwise, odd (e.g. 27) is 0 and even (e.g. 28) is 1 + return this.v.and(1).isZero() ? 1: 0; + */ + } + get yParityAndS() { + // The EIP-2098 compact representation + const yParityAndS = logger.getBytes(this.s); + if (this.yParity) { + yParityAndS[0] |= 0x80; + } + return hexlify(yParityAndS); + } + get compactSerialized() { + return concat([this.r, this.yParityAndS]); + } + get serialized() { + return concat([this.r, this.s, (this.yParity ? "0x1c" : "0x1b")]); + } + constructor(guard, r, s, v) { + logger.assertPrivate(guard, _guard, "Signature"); + this.#props = { r, s, v, networkV: null }; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; + } + clone() { + const clone = new Signature(_guard, this.r, this.s, this.v); + if (this.networkV) { + setStore(clone.#props, "networkV", this.networkV); + } + return clone; + } + freeze() { + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + toJSON() { + const networkV = this.networkV; + return { + _type: "signature", + networkV: ((networkV != null) ? networkV.toString() : null), + r: this.r, s: this.s, v: this.v, + }; + } + static create() { + return new Signature(_guard, ZeroHash, ZeroHash, 27); + } + // Get the chain ID from an EIP-155 v + static getChainId(v) { + const bv = logger.getBigInt(v, "v"); + // The v is not an EIP-155 v, so it is the unspecified chain ID + if ((bv == BN_27) || (bv == BN_28)) { + return BN_0; + } + // Bad value for an EIP-155 v + if (bv < BN_35) { + logger.throwArgumentError("invalid EIP-155 v", "v", v); + } + return (bv - BN_35) / BN_2; + } + // Get the EIP-155 v transformed for a given chainId + static getChainIdV(chainId, v) { + return (logger.getBigInt(chainId) * BN_2) + BigInt(35 + v - 27); + } + // Convert an EIP-155 v into a normalized v + static getNormalizedV(v) { + const bv = logger.getBigInt(v); + if (bv == BN_0) { + return 27; + } + if (bv == BN_1) { + return 28; + } + // Otherwise, EIP-155 v means odd is 27 and even is 28 + return (bv & BN_1) ? 27 : 28; + } + static from(sig) { + const throwError = (message) => { + return logger.throwArgumentError(message, "signature", sig); + }; + if (typeof (sig) === "string") { + const bytes = logger.getBytes(sig, "signature"); + if (bytes.length === 64) { + const r = hexlify(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + const v = (s[0] & 0x80) ? 28 : 27; + s[0] &= 0x7f; + return new Signature(_guard, r, hexlify(s), v); + } + if (dataLength(sig) !== 65) { + const r = hexlify(sig.slice(0, 32)); + const s = bytes.slice(32, 64); + if (s[0] & 0x80) { + throwError("non-canonical s"); + } + const v = Signature.getNormalizedV(bytes[64]); + return new Signature(_guard, r, hexlify(s), v); + } + return throwError("invlaid raw signature length"); + } + if (sig instanceof Signature) { + return sig.clone(); + } + // Get r + const r = sig.r; + if (r == null) { + throwError("missing r"); + } + if (!isHexString(r, 32)) { + throwError("invalid r"); + } + // Get s; by any means necessary (we check consistency below) + const s = (function (s, yParityAndS) { + if (s != null) { + if (!isHexString(s, 32)) { + throwError("invalid s"); + } + return s; + } + if (yParityAndS != null) { + if (!isHexString(yParityAndS, 32)) { + throwError("invalid yParityAndS"); + } + const bytes = logger.getBytes(yParityAndS); + bytes[0] &= 0x7f; + return hexlify(bytes); + } + return throwError("missing s"); + })(sig.s, sig.yParityAndS); + if (logger.getBytes(s)[0] & 0x80) { + throwError("non-canonical s"); + } + // Get v; by any means necessary (we check consistency below) + const { networkV, v } = (function (_v, yParityAndS, yParity) { + if (_v != null) { + const v = logger.getBigInt(_v); + return { + networkV: ((v >= BN_35) ? v : undefined), + v: Signature.getNormalizedV(v) + }; + } + if (yParityAndS != null) { + if (!isHexString(yParityAndS, 32)) { + throwError("invalid yParityAndS"); + } + return { v: ((logger.getBytes(yParityAndS)[0] & 0x80) ? 28 : 27) }; + } + if (yParity != null) { + switch (yParity) { + case 0: return { v: 27 }; + case 1: return { v: 28 }; + } + return throwError("invalid yParity"); + } + return throwError("missing v"); + })(sig.v, sig.yParityAndS, sig.yParity); + const result = new Signature(_guard, r, s, v); + if (networkV) { + setStore(result.#props, "networkV", networkV); + } + // If multiple of v, yParity, yParityAndS we given, check they match + if ("yParity" in sig && sig.yParity !== result.yParity) { + throwError("yParity mismatch"); + } + else if ("yParityAndS" in sig && sig.yParityAndS !== result.yParityAndS) { + throwError("yParityAndS mismatch"); + } + return result; + } +} +//# sourceMappingURL=signature.js.map \ No newline at end of file diff --git a/lib.esm/crypto/signature.js.map b/lib.esm/crypto/signature.js.map new file mode 100644 index 000000000..a53f992bc --- /dev/null +++ b/lib.esm/crypto/signature.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signature.js","sourceRoot":"","sources":["../../src.ts/crypto/signature.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EACH,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EACvE,MAAM,mBAAmB,CAAC;AAK3B,YAAY;AACZ,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAGzB,MAAM,MAAM,GAAG,EAAG,CAAC;AAwBnB,MAAM,OAAO,SAAS;IAClB,MAAM,CAAgE;IAEtE,IAAI,CAAC,KAAa,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACtD,IAAI,CAAC,CAAC,KAAgB;QAClB,IAAI,UAAU,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE;YAC1B,MAAM,CAAC,kBAAkB,CAAC,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC1D;QACD,QAAQ,CAAC,IAAI,CAAC,M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,CAAC,WAAW,EAAE;YACvE,UAAU,CAAC,sBAAsB,CAAC,CAAC;SACtC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/crypto/signing-key.js b/lib.esm/crypto/signing-key.js new file mode 100644 index 000000000..28208027f --- /dev/null +++ b/lib.esm/crypto/signing-key.js @@ -0,0 +1,106 @@ +import * as secp256k1 from "@noble/secp256k1"; +import { concat, hexlify, toHex, logger } from "../utils/index.js"; +import { computeHmac } from "./hmac.js"; +import { Signature } from "./signature.js"; +//const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +// Make noble-secp256k1 sync +secp256k1.utils.hmacSha256Sync = function (key, ...messages) { + return logger.getBytes(computeHmac("sha256", key, concat(messages))); +}; +export class SigningKey { + #privateKey; + constructor(privateKey) { + /* @TODO + logger.assertArgument(() => { + if (dataLength(privateKey) !== 32) { throw new Error("bad length"); } + return toBigInt(privateKey) < N; + }, "invalid private key", "privateKey", "[REDACTED]"); + */ + this.#privateKey = hexlify(privateKey); + } + get privateKey() { return this.#privateKey; } + get publicKey() { return SigningKey.computePublicKey(this.#privateKey); } + get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); } + sign(digest) { + /* @TODO + logger.assertArgument(() => (dataLength(digest) === 32), "invalid digest length", "digest", digest); + */ + const [sigDer, recid] = secp256k1.signSync(logger.getBytesCopy(digest), logger.getBytesCopy(this.#privateKey), { + recovered: true, + canonical: true + }); + const sig = secp256k1.Signature.fromHex(sigDer); + return Signature.from({ + r: toHex("0x" + sig.r.toString(16), 32), + s: toHex("0x" + sig.s.toString(16), 32), + v: (recid ? 0x1c : 0x1b) + }).freeze(); + } + computeShardSecret(other) { + const pubKey = SigningKey.computePublicKey(other); + return hexlify(secp256k1.getSharedSecret(logger.getBytesCopy(this.#privateKey), pubKey)); + } + static computePublicKey(key, compressed) { + let bytes = logger.getBytes(key, "key"); + if (bytes.length === 32) { + const pubKey = secp256k1.getPublicKey(bytes, !!compressed); + return hexlify(pubKey); + } + if (bytes.length === 64) { + const pub = new Uint8Array(65); + pub[0] = 0x04; + pub.set(bytes, 1); + bytes = pub; + } + const point = secp256k1.Point.fromHex(bytes); + return hexlify(point.toRawBytes(compressed)); + } + static recoverPublicKey(digest, signature) { + const sig = Signature.from(signature); + const der = secp256k1.Signature.fromCompact(logger.getBytesCopy(concat([sig.r, sig.s]))).toDERRawBytes(); + const pubKey = secp256k1.recoverPublicKey(logger.getBytesCopy(digest), der, sig.yParity); + if (pubKey != null) { + return hexlify(pubKey); + } + return logger.throwArgumentError("invalid signautre for digest", "signature", signature); + } + static _addPoints(p0, p1, compressed) { + const pub0 = secp256k1.Point.fromHex(SigningKey.computePublicKey(p0).substring(2)); + const pub1 = secp256k1.Point.fromHex(SigningKey.computePublicKey(p1).substring(2)); + return "0x" + pub0.add(pub1).toHex(!!compressed); + } +} +/* +const key = new SigningKey("0x1234567890123456789012345678901234567890123456789012345678901234"); +console.log(key); +console.log(key.sign("0x1234567890123456789012345678901234567890123456789012345678901234")); +{ + const privKey = "0x1234567812345678123456781234567812345678123456781234567812345678"; + const signingKey = new SigningKey(privKey); + console.log("0", signingKey, signingKey.publicKey, signingKey.publicKeyCompressed); + + let pubKey = SigningKey.computePublicKey(privKey); + let pubKeyComp = SigningKey.computePublicKey(privKey, true); + let pubKeyRaw = "0x" + SigningKey.computePublicKey(privKey).substring(4); + console.log("A", pubKey, pubKeyComp); + + let a = SigningKey.computePublicKey(pubKey); + let b = SigningKey.computePublicKey(pubKey, true); + console.log("B", a, b); + + a = SigningKey.computePublicKey(pubKeyComp); + b = SigningKey.computePublicKey(pubKeyComp, true); + console.log("C", a, b); + + a = SigningKey.computePublicKey(pubKeyRaw); + b = SigningKey.computePublicKey(pubKeyRaw, true); + console.log("D", a, b); + + const digest = "0x1122334411223344112233441122334411223344112233441122334411223344"; + const sig = signingKey.sign(digest); + console.log("SS", sig, sig.r, sig.s, sig.yParity); + + console.log("R", SigningKey.recoverPublicKey(digest, sig)); +} +*/ +//# sourceMappingURL=signing-key.js.map \ No newline at end of file diff --git a/lib.esm/crypto/signing-key.js.map b/lib.esm/crypto/signing-key.js.map new file mode 100644 index 000000000..7b7d78616 --- /dev/null +++ b/lib.esm/crypto/signing-key.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signing-key.js","sourceRoot":"","sources":["../../src.ts/crypto/signing-key.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,SAAS,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEnE,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAO3C,yFAAyF;AAEzF,4BAA4B;AAC5B,SAAS,CAAC,KAAK,CAAC,cAAc,GAAG,UAAS,GAAe,EAAE,GAAG,QAA2B;IACrF,OAAO,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AACzE,CAAC,CAAA;AAED,MAAM,OAAO,UAAU;IACnB,WAAW,CAAS;IAEpB,YAAY,UAAqB;QAC7B;;;;;UAKE;QACF,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC3C,CAAC;IAED,IAAI,UAAU,KAAa,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACrD,IAAI,SAAS,KAAa,OAAO,UAAU,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;IACjF,IAAI,mBAAmB,KAAa,OAAO,UAAU,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAEjG,IAAI,CAAC,MAAiB;QAClB;;UAEE;QAEF,MAAM,C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CAAC,CAAC,CAAC,CAAC;QACnF,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QACnF,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,CAAA;IACpD,CAAC;CACJ;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgCE"} \ No newline at end of file diff --git a/lib.esm/ethers.js b/lib.esm/ethers.js new file mode 100644 index 000000000..0ab0933a6 --- /dev/null +++ b/lib.esm/ethers.js @@ -0,0 +1,19 @@ +///////////////////////////// +// +export { version } from "./_version.js"; +export { formatBytes32String, parseBytes32String, AbiCoder, defaultAbiCoder, ConstructorFragment, ErrorFragment, EventFragment, Fragment, FunctionFragment, ParamType, checkResultErrors, Indexed, Interface, LogDescription, Result, TransactionDescription, Typed, } from "./abi/index.js"; +export { getAddress, getIcapAddress, getCreateAddress, getCreate2Address } from "./address/index.js"; +export { ZeroAddress, NegativeOne, Zero, One, Two, WeiPerEther, MaxUint256, MinInt256, MaxInt256, ZeroHash, EtherSymbol, MessagePrefix } from "./constants/index.js"; +export { BaseContract, Contract, ContractFactory, ContractEventPayload, ContractTransactionReceipt, ContractTransactionResponse, EventLog, } from "./contract/index.js"; +export { computeHmac, randomBytes, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync, lock, Signature, SigningKey } from "./crypto/index.js"; +export { id, +//isValidName, namehash, dnsEncode +hashMessage, solidityPacked, solidityPackedKeccak256, solidityPackedSha256, TypedDataEncoder } from "./hash/index.js"; +export { accessListify, computeAddress, recoverAddress, Transaction } from "./transaction/index.js"; +export { decodeBase58, encodeBase58, isCallException, isError, FetchRequest, FetchResponse, FixedFormat, FixedNumber, formatFixed, parseFixed, assertArgument, Logger, logger, fromTwos, toTwos, mask, toArray, toBigInt, toHex, toNumber, formatEther, parseEther, formatUnits, parseUnits, _toEscapedUtf8String, toUtf8Bytes, toUtf8CodePoints, toUtf8String, Utf8ErrorFuncs, decodeRlp, encodeRlp } from "./utils/index.js"; +export { defaultPath, getAccountPath, HDNodeWallet, HDNodeVoidWallet, HDNodeWalletManager, isCrowdsaleJson, decryptCrowdsaleJson, isKeystoreJson, decryptKeystoreJsonSync, decryptKeystoreJson, encryptKeystoreJson, Mnemonic, Wallet } from "./wallet/index.js"; +export { Wordlist, langEn, LangEn, wordlists, WordlistOwl, WordlistOwlA } from "./wordlists/index.js"; +export { FallbackProvider, JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner, AlchemyProvider, AnkrProvider, CloudflareProvider, EtherscanProvider, InfuraProvider, +//PocketProvider } from "./provider-pocket.js"; +IpcSocketProvider, SocketProvider, WebSocketProvider, Network } from "./providers/index.js"; +//# sourceMappingURL=ethers.js.map \ No newline at end of file diff --git a/lib.esm/ethers.js.map b/lib.esm/ethers.js.map new file mode 100644 index 000000000..b9aad7626 --- /dev/null +++ b/lib.esm/ethers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ethers.js","sourceRoot":"","sources":["../src.ts/ethers.ts"],"names":[],"mappings":"AAEA,6BAA6B;AAC7B,EAAE;AAEF,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,OAAO,EACH,mBAAmB,EAAE,kBAAkB,EAEvC,QAAQ,EAAE,eAAe,EACzB,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,QAAQ,EAAE,gBAAgB,EAAE,SAAS,EAExF,iBAAiB,EAAE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,sBAAsB,EACrF,KAAK,GACR,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACH,UAAU,EAAE,cAAc,EAC1B,gBAAgB,EAAE,iBAAiB,EACtC,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACH,WAAW,EACX,WAAW,EAAE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B,EAC5D,mBAAmB,EACnB,QAAQ,EACR,MAAM,EACT,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACH,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EACjE,MAAM,sBAAsB,CAAC;AAwB9B,OAAO,EACH,gBAAgB,EAChB,kBAAkB,EAAE,eAAe,EAAE,aAAa,EAElD,eAAe,EAAE,YAAY,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc;AACpF,+CAA+C;AAE/C,iBAAiB,EAAE,cAAc,EAAE,iBAAiB,EAEpD,OAAO,EACV,MAAM,sBAAsB,CAAC"} \ No newline at end of file diff --git a/lib.esm/hash/id.js b/lib.esm/hash/id.js new file mode 100644 index 000000000..63433b2f2 --- /dev/null +++ b/lib.esm/hash/id.js @@ -0,0 +1,6 @@ +import { keccak256 } from "../crypto/keccak.js"; +import { toUtf8Bytes } from "../utils/index.js"; +export function id(value) { + return keccak256(toUtf8Bytes(value)); +} +//# sourceMappingURL=id.js.map \ No newline at end of file diff --git a/lib.esm/hash/id.js.map b/lib.esm/hash/id.js.map new file mode 100644 index 000000000..5df4870f9 --- /dev/null +++ b/lib.esm/hash/id.js.map @@ -0,0 +1 @@ +{"version":3,"file":"id.js","sourceRoot":"","sources":["../../src.ts/hash/id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,UAAU,EAAE,CAAC,KAAa;IAC5B,OAAO,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;AACzC,CAAC"} \ No newline at end of file diff --git a/lib.esm/hash/index.js b/lib.esm/hash/index.js new file mode 100644 index 000000000..b847bd446 --- /dev/null +++ b/lib.esm/hash/index.js @@ -0,0 +1,6 @@ +export { id } from "./id.js"; +export { isValidName, namehash, dnsEncode } from "./namehash.js"; +export { hashMessage } from "./message.js"; +export { solidityPacked, solidityPackedKeccak256, solidityPackedSha256 } from "./solidity.js"; +export { TypedDataEncoder } from "./typed-data.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/hash/index.js.map b/lib.esm/hash/index.js.map new file mode 100644 index 000000000..5d2e3946d --- /dev/null +++ b/lib.esm/hash/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/hash/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAA;AAC5B,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACH,cAAc,EAAE,uBAAuB,EAAE,oBAAoB,EAChE,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/lib.esm/hash/message.js b/lib.esm/hash/message.js new file mode 100644 index 000000000..78a873f74 --- /dev/null +++ b/lib.esm/hash/message.js @@ -0,0 +1,14 @@ +import { keccak256 } from "../crypto/keccak.js"; +import { MessagePrefix } from "../constants/index.js"; +import { concat, toUtf8Bytes } from "../utils/index.js"; +export function hashMessage(message) { + if (typeof (message) === "string") { + message = toUtf8Bytes(message); + } + return keccak256(concat([ + toUtf8Bytes(MessagePrefix), + toUtf8Bytes(String(message.length)), + message + ])); +} +//# sourceMappingURL=message.js.map \ No newline at end of file diff --git a/lib.esm/hash/message.js.map b/lib.esm/hash/message.js.map new file mode 100644 index 000000000..ec0390f5f --- /dev/null +++ b/lib.esm/hash/message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"message.js","sourceRoot":"","sources":["../../src.ts/hash/message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGxD,MAAM,UAAU,WAAW,CAAC,OAA4B;IACpD,IAAI,OAAM,CAAC,OAAO,CAAC,KAAK,QAAQ,EAAE;QAAE,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;KAAE;IACrE,OAAO,SAAS,CAAC,MAAM,CAAC;QACpB,WAAW,CAAC,aAAa,CAAC;QAC1B,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACnC,OAAO;KACV,CAAC,CAAC,CAAC;AACR,CAAC"} \ No newline at end of file diff --git a/lib.esm/hash/namehash.js b/lib.esm/hash/namehash.js new file mode 100644 index 000000000..64c075642 --- /dev/null +++ b/lib.esm/hash/namehash.js @@ -0,0 +1,72 @@ +import { keccak256 } from "../crypto/keccak.js"; +import { concat, hexlify, logger, toUtf8Bytes, toUtf8String } from "../utils/index.js"; +//import { ens_normalize } from "./ens-normalize/lib"; +// @TOOD: +function ens_normalize(name) { + return name; +} +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + if (comp.length === 0) { + throw new Error("invalid ENS name; empty component"); + } + return comp; +} +function ensNameSplit(name) { + const bytes = toUtf8Bytes(ens_normalize(name)); + const comps = []; + if (name.length === 0) { + return comps; + } + let last = 0; + for (let i = 0; i < bytes.length; i++) { + const d = bytes[i]; + // A separator (i.e. "."); copy this component + if (d === 0x2e) { + comps.push(checkComponent(bytes.slice(last, i))); + last = i + 1; + } + } + // There was a stray separator at the end of the name + if (last >= bytes.length) { + throw new Error("invalid ENS name; empty component"); + } + comps.push(checkComponent(bytes.slice(last))); + return comps; +} +export function ensNormalize(name) { + return ensNameSplit(name).map((comp) => toUtf8String(comp)).join("."); +} +export function isValidName(name) { + try { + return (ensNameSplit(name).length !== 0); + } + catch (error) { } + return false; +} +export function namehash(name) { + /* istanbul ignore if */ + if (typeof (name) !== "string") { + logger.throwArgumentError("invalid ENS name; not a string", "name", name); + } + let result = Zeros; + const comps = ensNameSplit(name); + while (comps.length) { + result = keccak256(concat([result, keccak256((comps.pop()))])); + } + return hexlify(result); +} +export function dnsEncode(name) { + return hexlify(concat(ensNameSplit(name).map((comp) => { + // DNS does not allow components over 63 bytes in length + if (comp.length > 63) { + throw new Error("invalid DNS encoded entry; length exceeds 63 bytes"); + } + const bytes = new Uint8Array(comp.length + 1); + bytes.set(comp, 1); + bytes[0] = bytes.length - 1; + return bytes; + }))) + "00"; +} +//# sourceMappingURL=namehash.js.map \ No newline at end of file diff --git a/lib.esm/hash/namehash.js.map b/lib.esm/hash/namehash.js.map new file mode 100644 index 000000000..5cf35d29b --- /dev/null +++ b/lib.esm/hash/namehash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"namehash.js","sourceRoot":"","sources":["../../src.ts/hash/namehash.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGvF,sDAAsD;AACtD,SAAS;AACT,SAAS,aAAa,CAAC,IAAY;IAC/B,OAAO,IAAI,CAAC;AAChB,CAAC;AAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACjC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAEd,SAAS,cAAc,CAAC,IAAgB;IACpC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;KAAE;IAChF,OAAO,IAAI,CAAC;AAChB,CAAC;AAED,SAAS,YAAY,CAAC,IAAY;IAC9B,MAAM,KAAK,GAAG,WAAW,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/C,MAAM,KAAK,GAAsB,EAAG,CAAC;IAErC,IAAI,IA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CAAC,kBAAkB,CAAC,gCAAgC,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;KAC7E;IAED,IAAI,MAAM,GAAwB,KAAK,CAAC;IAExC,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IACjC,OAAO,KAAK,CAAC,MAAM,EAAE;QACjB,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAE,MAAM,EAAE,SAAS,CAAa,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC;KAChF;IAED,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,IAAY;IAClC,OAAO,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QAClD,wDAAwD;QACxD,IAAI,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE;YAClB,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACzE;QAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC9C,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QACnB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5B,OAAO,KAAK,CAAC;IAEjB,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/lib.esm/hash/solidity.js b/lib.esm/hash/solidity.js new file mode 100644 index 000000000..277c7f51e --- /dev/null +++ b/lib.esm/hash/solidity.js @@ -0,0 +1,104 @@ +import { concat, dataLength, hexlify, logger, toArray, toTwos, toUtf8Bytes, zeroPadBytes, zeroPadValue } from "../utils/index.js"; +import { keccak256 as _keccak256 } from "../crypto/keccak.js"; +import { sha256 as _sha256 } from "../crypto/sha2.js"; +const regexBytes = new RegExp("^bytes([0-9]+)$"); +const regexNumber = new RegExp("^(u?int)([0-9]*)$"); +const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); +function _pack(type, value, isArray) { + switch (type) { + case "address": + if (isArray) { + return logger.getBytes(zeroPadValue(value, 32)); + } + return logger.getBytes(value); + case "string": + return toUtf8Bytes(value); + case "bytes": + return logger.getBytes(value); + case "bool": + value = (!!value ? "0x01" : "0x00"); + if (isArray) { + return logger.getBytes(zeroPadValue(value, 32)); + } + return logger.getBytes(value); + } + let match = type.match(regexNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) { + return logger.throwArgumentError("invalid number type", "type", type); + } + if (isArray) { + size = 256; + } + value = toTwos(value, size); + return logger.getBytes(zeroPadValue(toArray(value), size / 8)); + } + match = type.match(regexBytes); + if (match) { + const size = parseInt(match[1]); + if (String(size) !== match[1] || size === 0 || size > 32) { + return logger.throwArgumentError("invalid bytes type", "type", type); + } + if (dataLength(value) !== size) { + return logger.throwArgumentError(`invalid value for ${type}`, "value", value); + } + if (isArray) { + return logger.getBytes(zeroPadBytes(value, 32)); + } + return value; + } + match = type.match(regexArray); + if (match && Array.isArray(value)) { + const baseType = match[1]; + const count = parseInt(match[2] || String(value.length)); + if (count != value.length) { + logger.throwArgumentError(`invalid array length for ${type}`, "value", value); + } + const result = []; + value.forEach(function (value) { + result.push(_pack(baseType, value, true)); + }); + return logger.getBytes(concat(result)); + } + return logger.throwArgumentError("invalid type", "type", type); +} +// @TODO: Array Enum +export function solidityPacked(types, values) { + if (types.length != values.length) { + logger.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values); + } + const tight = []; + types.forEach(function (type, index) { + tight.push(_pack(type, values[index])); + }); + return hexlify(concat(tight)); +} +/** + * Computes the non-standard packed (tightly packed) keccak256 hash of + * the values given the types. + * + * @param {Array} types - The Solidity types to interpret each value as [default: bar] + * @param {Array} values - The values to pack + * + * @returns: {HexString} the hexstring of the hash + * @example: + * solidityPackedKeccak256([ "address", "uint" ], [ "0x1234", 45 ]); + * //_result: + * + * @see https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode + */ +export function solidityPackedKeccak256(types, values) { + return _keccak256(solidityPacked(types, values)); +} +/** + * Test Function, for fun + * + * @param foo - something fun + */ +export function test(foo) { +} +export function solidityPackedSha256(types, values) { + return _sha256(solidityPacked(types, values)); +} +//# sourceMappingURL=solidity.js.map \ No newline at end of file diff --git a/lib.esm/hash/solidity.js.map b/lib.esm/hash/solidity.js.map new file mode 100644 index 000000000..b8adef456 --- /dev/null +++ b/lib.esm/hash/solidity.js.map @@ -0,0 +1 @@ +{"version":3,"file":"solidity.js","sourceRoot":"","sources":["../../src.ts/hash/solidity.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAChG,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,SAAS,IAAI,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAGtD,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACjD,MAAM,WAAW,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACpD,MAAM,UAAU,GAAG,IAAI,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAGtD,SAAS,KAAK,CAAC,IAAY,EAAE,KAAU,EAAE,OAAiB;IACtD,QAAO,IAAI,EAAE;QACT,KAAK,SAAS;YACV,IAAI,OAAO,EAAE;gBAAE,OAAO,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC;aAAE;YACjE,OAAO,MAAM,CAAC,QAAQ,CAAC,KA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AC;QACH,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;KAC1C;IAED,OAAO,MAAM,CAAC,kBAAkB,CAAC,cAAc,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;AAClE,CAAC;AAED,oBAAoB;AAEpB,MAAM,UAAU,cAAc,CAAC,KAA4B,EAAE,MAA0B;IACnF,IAAI,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;QAC/B,MAAM,CAAC,kBAAkB,CAAC,oDAAoD,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;KACpG;IACD,MAAM,KAAK,GAAsB,EAAE,CAAC;IACpC,KAAK,CAAC,OAAO,CAAC,UAAS,IAAI,EAAE,KAAK;QAC9B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAA4B,EAAE,MAA0B;IAC5F,OAAO,UAAU,CAAC,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AACrD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,IAAI,CAAC,GAAoB;AACzC,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,KAA4B,EAAE,MAA0B;IACzF,OAAO,OAAO,CAAC,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/lib.esm/hash/typed-data.js b/lib.esm/hash/typed-data.js new file mode 100644 index 000000000..d28cbcd4d --- /dev/null +++ b/lib.esm/hash/typed-data.js @@ -0,0 +1,429 @@ +//import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer"; +import { getAddress } from "../address/index.js"; +import { keccak256 } from "../crypto/index.js"; +import { concat, defineProperties, hexlify, isHexString, mask, toHex, toTwos, zeroPadValue } from "../utils/index.js"; +import { id } from "./id.js"; +import { logger } from "../utils/logger.js"; +const padding = new Uint8Array(32); +padding.fill(0); +const BN__1 = BigInt(-1); +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +; +; +function hexPadRight(value) { + const bytes = logger.getBytes(value); + const padOffset = bytes.length % 32; + if (padOffset) { + return concat([bytes, padding.slice(padOffset)]); + } + return hexlify(bytes); +} +const hexTrue = toHex(BN_1, 32); +const hexFalse = toHex(BN_0, 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" +}; +const domainFieldNames = [ + "name", "version", "chainId", "verifyingContract", "salt" +]; +function checkString(key) { + return function (value) { + if (typeof (value) !== "string") { + logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + } + return value; + }; +} +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function (value) { + return logger.getBigInt(value, "domain.chainId"); + }, + verifyingContract: function (value) { + try { + return getAddress(value).toLowerCase(); + } + catch (error) { } + return logger.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function (value) { + const bytes = logger.getBytes(value, "domain.salt"); + if (bytes.length !== 32) { + logger.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); + } + return hexlify(bytes); + } +}; +function getBaseEncoder(type) { + // intXX and uintXX + { + const match = type.match(/^(u?)int(\d*)$/); + if (match) { + const signed = (match[1] === ""); + const width = parseInt(match[2] || "256"); + if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) { + logger.throwArgumentError("invalid numeric width", "type", type); + } + const boundsUpper = mask(BN_MAX_UINT256, signed ? (width - 1) : width); + const boundsLower = signed ? ((boundsUpper + BN_1) * BN__1) : BN_0; + return function (_value) { + const value = logger.getBigInt(_value, "value"); + if (value < boundsLower || value > boundsUpper) { + logger.throwArgumentError(`value out-of-bounds for ${type}`, "value", value); + } + return toHex(toTwos(value, 256), 32); + }; + } + } + // bytesXX + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + if (width === 0 || width > 32 || match[1] !== String(width)) { + logger.throwArgumentError("invalid bytes width", "type", type); + } + return function (value) { + const bytes = logger.getBytes(value); + if (bytes.length !== width) { + logger.throwArgumentError(`invalid length for ${type}`, "value", value); + } + return hexPadRight(value); + }; + } + } + switch (type) { + case "address": return function (value) { + return zeroPadValue(getAddress(value), 32); + }; + case "bool": return function (value) { + return ((!value) ? hexFalse : hexTrue); + }; + case "bytes": return function (value) { + return keccak256(value); + }; + case "string": return function (value) { + return id(value); + }; + } + return null; +} +function encodeType(name, fields) { + return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`; +} +export class TypedDataEncoder { + primaryType; + #types; + get types() { + return JSON.parse(this.#types); + } + #fullTypes; + #encoderCache; + constructor(types) { + this.#types = JSON.stringify(types); + this.#fullTypes = new Map(); + this.#encoderCache = new Map(); + // Link struct types to their direct child structs + const links = new Map(); + // Link structs to structs which contain them as a child + const parents = new Map(); + // Link all subtypes within a given struct + const subtypes = new Map(); + Object.keys(types).forEach((type) => { + links.set(type, new Set()); + parents.set(type, []); + subtypes.set(type, new Set()); + }); + for (const name in types) { + const uniqueNames = new Set(); + for (const field of types[name]) { + // Check each field has a unique name + if (uniqueNames.has(field.name)) { + logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types); + } + uniqueNames.add(field.name); + // Get the base type (drop any array specifiers) + const baseType = (field.type.match(/^([^\x5b]*)(\x5b|$)/))[1] || null; + if (baseType === name) { + logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types); + } + // Is this a base encoding type? + const encoder = getBaseEncoder(baseType); + if (encoder) { + continue; + } + if (!parents.has(baseType)) { + logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types); + } + // Add linkage + parents.get(baseType).push(name); + links.get(name).add(baseType); + } + } + // Deduce the primary type + const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0)); + if (primaryTypes.length === 0) { + logger.throwArgumentError("missing primary type", "types", types); + } + else if (primaryTypes.length > 1) { + logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", types); + } + defineProperties(this, { primaryType: primaryTypes[0] }); + // Check for circular type references + function checkCircular(type, found) { + if (found.has(type)) { + logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types); + } + found.add(type); + for (const child of links.get(type)) { + if (!parents.has(child)) { + continue; + } + // Recursively check children + checkCircular(child, found); + // Mark all ancestors as having this decendant + for (const subtype of found) { + subtypes.get(subtype).add(child); + } + } + found.delete(type); + } + checkCircular(this.primaryType, new Set()); + // Compute each fully describe type + for (const [name, set] of subtypes) { + const st = Array.from(set); + st.sort(); + this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join("")); + } + } + getEncoder(type) { + let encoder = this.#encoderCache.get(type); + if (!encoder) { + encoder = this.#getEncoder(type); + this.#encoderCache.set(type, encoder); + } + return encoder; + } + #getEncoder(type) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return encoder; + } + } + // Array + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const subEncoder = this.getEncoder(subtype); + const length = parseInt(match[3]); + return (value) => { + if (length >= 0 && value.length !== length) { + logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + let result = value.map(subEncoder); + if (this.#fullTypes.has(subtype)) { + result = result.map(keccak256); + } + return keccak256(concat(result)); + }; + } + // Struct + const fields = this.types[type]; + if (fields) { + const encodedType = id(this.#fullTypes.get(type)); + return (value) => { + const values = fields.map(({ name, type }) => { + const result = this.getEncoder(type)(value[name]); + if (this.#fullTypes.has(type)) { + return keccak256(result); + } + return result; + }); + values.unshift(encodedType); + return concat(values); + }; + } + return logger.throwArgumentError(`unknown type: ${type}`, "type", type); + } + encodeType(name) { + const result = this.#fullTypes.get(name); + if (!result) { + return logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name); + } + return result; + } + encodeData(type, value) { + return this.getEncoder(type)(value); + } + hashStruct(name, value) { + return keccak256(this.encodeData(name, value)); + } + encode(value) { + return this.encodeData(this.primaryType, value); + } + hash(value) { + return this.hashStruct(this.primaryType, value); + } + _visit(type, value, callback) { + // Basic encoder type (address, bool, uint256, etc) + { + const encoder = getBaseEncoder(type); + if (encoder) { + return callback(type, value); + } + } + // Array + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const length = parseInt(match[3]); + if (length >= 0 && value.length !== length) { + logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + return value.map((v) => this._visit(subtype, v, callback)); + } + // Struct + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name, type }) => { + accum[name] = this._visit(type, value[name], callback); + return accum; + }, {}); + } + return logger.throwArgumentError(`unknown type: ${type}`, "type", type); + } + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + static from(types) { + return new TypedDataEncoder(types); + } + static getPrimaryType(types) { + return TypedDataEncoder.from(types).primaryType; + } + static hashStruct(name, types, value) { + return TypedDataEncoder.from(types).hashStruct(name, value); + } + static hashDomain(domain) { + const domainFields = []; + for (const name in domain) { + const type = domainFieldTypes[name]; + if (!type) { + logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); + } + domainFields.push({ name, type }); + } + domainFields.sort((a, b) => { + return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); + }); + return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain); + } + static encode(domain, types, value) { + return concat([ + "0x1901", + TypedDataEncoder.hashDomain(domain), + TypedDataEncoder.from(types).hash(value) + ]); + } + static hash(domain, types, value) { + return keccak256(TypedDataEncoder.encode(domain, types, value)); + } + // Replaces all address types with ENS names with their looked up address + static async resolveNames(domain, types, value, resolveName) { + // Make a copy to isolate it from the object passed in + domain = Object.assign({}, domain); + // Look up all ENS names + const ensCache = {}; + // Do we need to look up the domain's verifyingContract? + if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) { + ensCache[domain.verifyingContract] = "0x"; + } + // We are going to use the encoder to visit all the base values + const encoder = TypedDataEncoder.from(types); + // Get a list of all the addresses + encoder.visit(value, (type, value) => { + if (type === "address" && !isHexString(value, 20)) { + ensCache[value] = "0x"; + } + return value; + }); + // Lookup each name + for (const name in ensCache) { + ensCache[name] = await resolveName(name); + } + // Replace the domain verifyingContract if needed + if (domain.verifyingContract && ensCache[domain.verifyingContract]) { + domain.verifyingContract = ensCache[domain.verifyingContract]; + } + // Replace all ENS names with their address + value = encoder.visit(value, (type, value) => { + if (type === "address" && ensCache[value]) { + return ensCache[value]; + } + return value; + }); + return { domain, value }; + } + static getPayload(domain, types, value) { + // Validate the domain fields + TypedDataEncoder.hashDomain(domain); + // Derive the EIP712Domain Struct reference type + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name) => { + const value = domain[name]; + if (value == null) { + return; + } + domainValues[name] = domainChecks[name](value); + domainTypes.push({ name, type: domainFieldTypes[name] }); + }); + const encoder = TypedDataEncoder.from(types); + const typesWithDomain = Object.assign({}, types); + if (typesWithDomain.EIP712Domain) { + logger.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types); + } + else { + typesWithDomain.EIP712Domain = domainTypes; + } + // Validate the data structures and types + encoder.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder.primaryType, + message: encoder.visit(value, (type, value) => { + // bytes + if (type.match(/^bytes(\d*)/)) { + return hexlify(logger.getBytes(value)); + } + // uint or int + if (type.match(/^u?int/)) { + return logger.getBigInt(value).toString(); + } + switch (type) { + case "address": + return value.toLowerCase(); + case "bool": + return !!value; + case "string": + if (typeof (value) !== "string") { + logger.throwArgumentError(`invalid string`, "value", value); + } + return value; + } + return logger.throwArgumentError("unsupported type", "type", type); + }) + }; + } +} +//# sourceMappingURL=typed-data.js.map \ No newline at end of file diff --git a/lib.esm/hash/typed-data.js.map b/lib.esm/hash/typed-data.js.map new file mode 100644 index 000000000..f8b14462c --- /dev/null +++ b/lib.esm/hash/typed-data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typed-data.js","sourceRoot":"","sources":["../../src.ts/hash/typed-data.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EACH,MAAM,EAAE,gBAAgB,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EACpF,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAK5C,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAEhB,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AACzB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,cAAc,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AAQnG,CAAC;AAKD,CAAC;AAEF,SAAS,WAAW,CAAC,KAAgB;IACjC,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAA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BACd,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE;oBACtB,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAC;iBAC7C;gBAED,QAAQ,IAAI,EAAE;oBACV,KAAK,SAAS;wBACV,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;oBAC/B,KAAK,MAAM;wBACP,OAAO,CAAC,CAAC,KAAK,CAAC;oBACnB,KAAK,QAAQ;wBACT,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;4BAC5B,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;yBAC/D;wBACD,OAAO,KAAK,CAAC;iBACpB;gBAED,OAAO,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;YACvE,CAAC,CAAC;SACL,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/index.js b/lib.esm/index.js new file mode 100644 index 000000000..ce0658856 --- /dev/null +++ b/lib.esm/index.js @@ -0,0 +1,4 @@ +import * as ethers from "./ethers.js"; +export { ethers }; +export * from "./ethers.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/index.js.map b/lib.esm/index.js.map new file mode 100644 index 000000000..402b428df --- /dev/null +++ b/lib.esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src.ts/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAE,MAAM,EAAE,CAAC;AAElB,cAAc,aAAa,CAAC"} \ 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 000000000..6fb5788a4 --- /dev/null +++ b/lib.esm/providers/abstract-provider.js @@ -0,0 +1,1088 @@ +// @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 { resolveAddress } from "../address/index.js"; +import { concat, dataLength, dataSlice, hexlify, isHexString } from "../utils/data.js"; +import { isCallException } from "../utils/errors.js"; +import { FetchRequest } from "../utils/fetch.js"; +import { toArray, toQuantity } from "../utils/maths.js"; +import { defineProperties, EventPayload, resolveProperties } from "../utils/index.js"; +import { toUtf8String } from "../utils/index.js"; +; +import { logger } from "../utils/logger.js"; +import { EnsResolver } from "./ens-resolver.js"; +import { Network } from "./network.js"; +import { FeeData } from "./provider.js"; +import { PollingBlockSubscriber, PollingEventSubscriber, PollingOrphanSubscriber, PollingTransactionSubscriber } from "./subscriber-polling.js"; +// Constants +const BN_2 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v) => { + 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; + }); +} +export class UnmanagedSubscriber { + 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; +} +// Normalize a ProviderEvent into a Subscription +// @TODO: Make events sync if possible; like block +//function getSyncSubscription(_event: ProviderEvent): Subscription { +//} +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 "pending": + case "debug": + case "network": { + 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" }; + } + return logger.throwArgumentError("unknown ProviderEvent", "event", _event); +} +function getTime() { return (new Date()).getTime(); } +export function copyRequest(tx) { + // @TODO: copy the copy from contracts and use it from this + return tx; +} +export class AbstractProvider { + #subs; + #plugins; + // null=unpaused, true=paused+dropWhilePaused, false=paused + #pausedState; + #networkPromise; + #anyNetwork; + #performCache; + #nextTimer; + #timers; + #disableCcipRead; + // @TODO: This should be a () => Promise so network can be + // done when needed; or rely entirely on _detectNetwork? + constructor(_network) { + 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.#performCache = new Map(); + this.#subs = new Map(); + this.#plugins = new Map(); + this.#pausedState = null; + this.#nextTimer = 0; + this.#timers = new Map(); + this.#disableCcipRead = false; + } + get provider() { return this; } + get plugins() { + return Array.from(this.#plugins.values()); + } + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.validate(this)); + return this; + } + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + set disableCcipRead(value) { this.#disableCcipRead = !!value; } + get disableCcipRead() { return this.#disableCcipRead; } + // Shares multiple identical requests made during the same 250ms + async #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); + } + }, 250); + } + return await perform; + } + 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 }; + } + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + } + catch (error) { } + // 4xx indicates the result is not present; stop + if (resp.statusCode >= 400 && resp.statusCode < 500) { + return logger.throwError(`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); + } + return logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, info: { urls, errorMessages } + }); + } + _wrapTransaction(tx, hash, blockNumber) { + return tx; + } + _detectNetwork() { + return logger.throwError("sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); + } + // Sub-classes should override this and handle PerformActionRequest requests, calling + // the super for any unhandled actions. + async _perform(req) { + return logger.throwError(`unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + // State + async getBlockNumber() { + return logger.getNumber(await this.#perform({ method: "getBlockNumber" }), "%response"); + } + // @TODO: Make this string | Promsie so no await needed if sync is possible + _getAddress(address) { + return resolveAddress(address, this); + /* + if (typeof(address) === "string") { + if (address.match(/^0x[0-9a-f]+$/i)) { return address; } + const resolved = await this.resolveName(address); + if (resolved == null) { throw new Error("not confiugred @TODO"); } + return resolved; + } + return address.getAddress(); + */ + } + _getBlockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return blockTag; + } + if (isHexString(blockTag)) { + if (dataLength(blockTag) === 32) { + return blockTag; + } + return toQuantity(blockTag); + } + if (typeof (blockTag) === "number") { + if (blockTag >= 0) { + return toQuantity(blockTag); + } + return this.getBlockNumber().then((b) => toQuantity(b + blockTag)); + } + return logger.throwArgumentError("invalid blockTag", "blockTag", blockTag); + } + async getNetwork() { + // 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 = this._detectNetwork().then((network) => { + this.emit("network", network, null); + return network; + }, (error) => { + // Reset the networkPromise on failure, so we will try again + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + }); + this.#networkPromise = detectNetwork; + return await detectNetwork; + } + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork() // 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 + logger.throwError(`network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone().freeze(); + } + async getFeeData() { + const { block, gasPrice } = await resolveProperties({ + block: this.getBlock("latest"), + gasPrice: ((async () => { + try { + const gasPrice = await this.#perform({ method: "getGasPrice" }); + return logger.getBigInt(gasPrice, "%response"); + } + catch (error) { } + return null; + })()) + }); + let maxFeePerGas = null, maxPriorityFeePerGas = null; + if (block && block.baseFeePerGas) { + // We may want to compute this more accurately in the future, + // using the formula "check if the base fee is correct". + // See: https://eips.ethereum.org/EIPS/eip-1559 + maxPriorityFeePerGas = BigInt("1500000000"); + // Allow a network to override their maximum priority fee per gas + //const priorityFeePlugin = (await this.getNetwork()).getPlugin("org.ethers.plugins.max-priority-fee"); + //if (priorityFeePlugin) { + // maxPriorityFeePerGas = await priorityFeePlugin.getPriorityFee(this); + //} + maxFeePerGas = (block.baseFeePerGas * BN_2) + maxPriorityFeePerGas; + } + return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + } + async _getTransaction(_request) { + const network = await this.getNetwork(); + // Fill in any addresses + const request = Object.assign({}, _request, await resolveProperties({ + to: (_request.to ? resolveAddress(_request.to, this) : undefined), + from: (_request.from ? resolveAddress(_request.from, this) : undefined), + })); + return network.formatter.transactionRequest(request); + } + async estimateGas(_tx) { + const transaction = await this._getTransaction(_tx); + return logger.getBigInt(await this.#perform({ + method: "estimateGas", transaction + }), "%response"); + } + async #call(tx, blockTag, attempt) { + if (attempt >= MAX_CCIP_REDIRECTS) { + logger.throwError("CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + } + const transaction = copyRequest(tx); + try { + return hexlify(await this._perform({ method: "call", transaction, blockTag })); + } + catch (error) { + // CCIP Read OffchainLookup + if (!this.disableCcipRead && isCallException(error) && 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; + try { + ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + } + catch (error) { + return logger.throwError(error.message, "OFFCHAIN_FAULT", { + reason: "BAD_DATA", + transaction, info: { data } + }); + } + // Check the sender of the OffchainLookup matches the transaction + if (ccipArgs.sender.toLowerCase() !== txSender.toLowerCase()) { + return logger.throwError("CCIP Read sender mismatch", "CALL_EXCEPTION", { + data, transaction, + errorSignature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + errorName: "OffchainLookup", + errorArgs: ccipArgs.errorArgs + }); + } + const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + if (ccipResult == null) { + return logger.throwError("CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + reason: "FETCH_FAILED", + transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } + }); + } + return this.#call({ + to: txSender, + data: concat([ + ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData]) + ]), + }, blockTag, attempt + 1); + } + throw error; + } + } + async call(_tx) { + const [tx, blockTag] = await Promise.all([ + this._getTransaction(_tx), this._getBlockTag(_tx.blockTag) + ]); + return this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1); + } + // Account + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + let blockTag = this._getBlockTag(_blockTag); + if (typeof (address) !== "string" || typeof (blockTag) !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await this.#perform(Object.assign(request, { address, blockTag })); + } + async getBalance(address, blockTag) { + return logger.getBigInt(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return logger.getNumber(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return hexlify(await this.#getAccountValue({ method: "getCode" }, address, blockTag)); + } + async getStorageAt(address, _position, blockTag) { + const position = logger.getBigInt(_position, "position"); + return hexlify(await this.#getAccountValue({ method: "getStorageAt", position }, address, blockTag)); + } + // Write + async broadcastTransaction(signedTx) { + throw new Error(); + return {}; + } + async #getBlock(block, includeTransactions) { + if (isHexString(block, 32)) { + return await this.#perform({ + method: "getBlock", blockHash: block, includeTransactions + }); + } + let blockTag = this._getBlockTag(block); + if (typeof (blockTag) !== "string") { + blockTag = await blockTag; + } + return await this.#perform({ + method: "getBlock", blockTag, includeTransactions + }); + } + // Queries + async getBlock(block) { + const [network, params] = await Promise.all([ + this.getNetwork(), this.#getBlock(block, false) + ]); + if (params == null) { + return null; + } + return network.formatter.block(params, this); + } + async getBlockWithTransactions(block) { + const format = (await this.getNetwork()).formatter; + const params = this.#getBlock(block, true); + if (params == null) { + return null; + } + return format.blockWithTransactions(params, this); + } + async getTransaction(hash) { + const format = (await this.getNetwork()).formatter; + const params = await this.#perform({ method: "getTransaction", hash }); + return format.transactionResponse(params, this); + } + async getTransactionReceipt(hash) { + const format = (await this.getNetwork()).formatter; + const receipt = await this.#perform({ method: "getTransactionReceipt", hash }); + if (receipt == null) { + return null; + } + // Some backends did not backfill the effectiveGasPrice into old transactions + // in the receipt, so we look it up manually and inject it. + if (receipt.gasPrice == null && receipt.effectiveGasPrice == null) { + const tx = await this.#perform({ method: "getTransaction", hash }); + receipt.effectiveGasPrice = tx.gasPrice; + } + return format.receipt(receipt, this); + } + async getTransactionResult(hash) { + const result = await this.#perform({ method: "getTransactionResult", hash }); + if (result == null) { + return null; + } + return hexlify(result); + } + _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) => { + 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; + } + 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.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.toBlock); + } + 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 resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock); + } + // Bloom-filter Queries + async getLogs(_filter) { + const { network, filter } = await resolveProperties({ + network: this.getNetwork(), + filter: this._getFilter(_filter) + }); + return (await this.#perform({ method: "getLogs", filter })).map((l) => { + return network.formatter.log(l, this); + }); + } + // ENS + _getProvider(chainId) { + return logger.throwError("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) { + //if (typeof(name) === "string") { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + /* + } else { + const address = await name.getAddress(); + if (address == null) { + return logger.throwArgumentError("Addressable returned no address", "name", name); + } + return address; + } + */ + return null; + } + async lookupAddress(address) { + throw new Error(); + //return "TODO"; + } + async waitForTransaction(hash, confirms = 1, timeout) { + 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(logger.makeError("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); + } + listener(await this.getBlockNumber()); + }); + } + async waitForBlock(blockTag) { + throw new Error(); + //return new Block({ }, this); + } + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); + } + _setTimeout(_func, 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; + } + _forEachSubscriber(func) { + for (const sub of this.#subs.values()) { + func(sub.subscriber); + } + } + // Event API; sub-classes should override this; any supported + // event filter will have been munged into an EventFilter + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "network": + return new UnmanagedSubscriber(sub.type); + case "block": + return new PollingBlockSubscriber(this); + case "event": + return new PollingEventSubscriber(this, sub.filter); + case "transaction": + return new PollingTransactionSubscriber(this, sub.hash); + case "orphan": + return new PollingOrphanSubscriber(this, sub.filter); + } + throw new Error(`unsupported event: ${sub.type}`); + } + _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 (!sub) { + 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; + }); + 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); + } + // Sub-classes should override this to shutdown any sockets, etc. + // but MUST call this super.shutdown. + async shutdown() { + // Stop all listeners + this.removeAllListeners(); + // Shut down all tiemrs + for (const timerId of this.#timers.keys()) { + this._clearTimeout(timerId); + } + } + get paused() { return (this.#pausedState != null); } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } + else { + this.pause(false); + } + } + pause(dropWhilePaused) { + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; + } + return logger.throwError("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() { + 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, start) { + try { + const bytes = _parseBytes(result, start); + if (bytes) { + return toUtf8String(bytes); + } + } + catch (error) { } + return null; +} +function _parseBytes(result, start) { + if (result === "0x") { + return null; + } + try { + const offset = logger.getNumber(dataSlice(result, start, start + 32)); + const length = logger.getNumber(dataSlice(result, offset, offset + 32)); + return dataSlice(result, offset + 32, offset + 32 + length); + } + catch (error) { } + return null; +} +function numPad(value) { + const result = toArray(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) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +const empty = new Uint8Array([]); +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes(datas) { + const result = []; + 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 = logger.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) { + const result = { + sender: "", urls: [], calldata: "", selector: "", extraData: "", errorArgs: [] + }; + if (dataLength(data) < 5 * 32) { + throw new Error("insufficient OffchainLookup data"); + } + const sender = dataSlice(data, 0, 32); + if (dataSlice(sender, 0, 12) !== dataSlice(zeros, 0, 12)) { + throw new Error("corrupt OffchainLookup sender"); + } + result.sender = dataSlice(sender, 12); + // Read the URLs from the response + try { + const urls = []; + const urlsOffset = logger.getNumber(dataSlice(data, 32, 64)); + const urlsLength = logger.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) { + throw new Error("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) { + throw new Error("corrupt OffchainLookup calldata"); + } + // Get the callbackSelector (bytes4) + if (dataSlice(data, 100, 128) !== dataSlice(zeros, 0, 28)) { + throw new Error("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) { + throw new Error("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 000000000..96d2e7c7b --- /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,QAAQ;AACR,oBAAoB;AACpB,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,2EAA2E;AAE3E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACvF,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC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CAAC;QACzC,IAAI,SAAS,IAAI,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;SAAE;QACpD,MAAM,CAAC,SAAS,GAAG,SAAS,CAAC;KAChC;IAAC,OAAO,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;KAAE;IAExE,MAAM,CAAC,SAAS,GAAG,yCAAyC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAO,MAAO,CAAC,CAAC,CAAC,CAAC,CAAA;IAGpG,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/abstract-signer.js b/lib.esm/providers/abstract-signer.js new file mode 100644 index 000000000..47d25269c --- /dev/null +++ b/lib.esm/providers/abstract-signer.js @@ -0,0 +1,143 @@ +import { logger } from "../utils/logger.js"; +import { Transaction } from "../transaction/index.js"; +import { defineProperties, resolveProperties } from "../utils/index.js"; +export class AbstractSigner { + provider; + constructor(provider) { + defineProperties(this, { provider: (provider || null) }); + } + #checkProvider(operation) { + if (this.provider) { + return this.provider; + } + return logger.throwError("missing provider", "UNSUPPORTED_OPERATION", { operation }); + } + async getNonce(blockTag) { + return this.#checkProvider("getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async #populate(op, tx) { + const provider = this.#checkProvider(op); + //let pop: Deferrable = Object.assign({ }, tx); + let pop = Object.assign({}, tx); + if (pop.to != null) { + pop.to = provider.resolveName(pop.to).then((to) => { + if (to == null) { + return logger.throwArgumentError("transaction to ENS name not configured", "tx.to", pop.to); + } + return to; + }); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + this.getAddress(), + this.resolveName(from) + ]).then(([address, from]) => { + if (!from || address.toLowerCase() !== from.toLowerCase()) { + return logger.throwArgumentError("transaction from mismatch", "tx.from", from); + } + return address; + }); + } + return pop; + } + async populateCall(tx) { + const pop = await this.#populate("populateCall", tx); + return pop; + } + async populateTransaction(tx) { + const pop = await this.#populate("populateTransaction", tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.gasLimit == null) { + pop.gasLimit = await this.estimateGas(pop); + } + //@TODO: Copy type logic from AbstractSigner in v5 + return await resolveProperties(pop); + } + async estimateGas(tx) { + return this.#checkProvider("estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return this.#checkProvider("call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = this.#checkProvider("resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = this.#checkProvider("sendTransaction"); + const txObj = Transaction.from(await this.populateTransaction(tx)); + return await provider.broadcastTransaction(await this.signTransaction(txObj)); + } +} +export class VoidSigner extends AbstractSigner { + address; + constructor(address, provider) { + super(provider); + defineProperties(this, { address }); + } + async getAddress() { return this.address; } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + return logger.throwError(`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"); + } +} +export class WrappedSigner extends AbstractSigner { + #signer; + constructor(signer) { + super(signer.provider); + this.#signer = signer; + } + async getAddress() { + return await this.#signer.getAddress(); + } + connect(provider) { + return new WrappedSigner(this.#signer.connect(provider)); + } + async getNonce(blockTag) { + return await this.#signer.getNonce(blockTag); + } + async populateCall(tx) { + return await this.#signer.populateCall(tx); + } + async populateTransaction(tx) { + return await this.#signer.populateTransaction(tx); + } + async estimateGas(tx) { + return await this.#signer.estimateGas(tx); + } + async call(tx) { + return await this.#signer.call(tx); + } + async resolveName(name) { + return this.#signer.resolveName(name); + } + async signTransaction(tx) { + return await this.#signer.signTransaction(tx); + } + async sendTransaction(tx) { + return await this.#signer.sendTransaction(tx); + } + async signMessage(message) { + return await this.#signer.signMessage(message); + } + async signTypedData(domain, types, value) { + return await this.#signer.signTypedData(domain, types, value); + } +} +//# 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 000000000..7600cf659 --- /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,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAWxE,MAAM,OAAgB,cAAc;IACvB,QAAQ,CAAK;IAEtB,YAAY,QAAY;QACpB,gBAAgB,CAAiB,IAAI,EAAE,EAAE,QAAQ,EAAE,CAAC,QAAQ,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAKD,cAAc,CAAC,SAAiB;QAC5B,IAAI,IAAI,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAC,QAAQ,CAAC;SAAE;QAC5C,OAAO,MAAM,CAAC,UAAU,CAAC,kBAAkB,EAAE,uBAAuB,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACzF,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,QAAmB;QAC9B,OAAO,IAAI,CAAC,cAAc,CAAC,qBAAqB,CAAC,CAAC,mBAAmB,CAAC,MAAM,IAAI,CAAC,UAAU,EAAE,EAAE,QAAQ,CAAC,CAAC;IAC7G,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,EAAU,EAAE,EAAoC;QAC5D,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;QAEzC,mEAAmE;QACnE,IAAI,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KAA4C,EAAE,KAA0B;QACjH,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/common-networks.js b/lib.esm/providers/common-networks.js new file mode 100644 index 000000000..562b31e8a --- /dev/null +++ b/lib.esm/providers/common-networks.js @@ -0,0 +1,77 @@ +/** + * Exports the same Network as "./network.js" except with common + * networks injected registered. + */ +import { EnsPlugin, GasCostPlugin } from "./plugins-network.js"; +import { EtherscanPlugin } from "./provider-etherscan.js"; +import { Network } from "./network.js"; +// See: https://chainlist.org +export function injectCommonNetworks() { + /// Register popular Ethereum networks + function registerEth(name, chainId, options) { + const func = function () { + const network = new Network(name, chainId); + // We use 0 to disable ENS + if (options.ensNetwork != null) { + network.attachPlugin(new EnsPlugin(null, options.ensNetwork)); + } + if (options.priorityFee) { + // network.attachPlugin(new MaxPriorityFeePlugin(options.priorityFee)); + } + if (options.etherscan) { + const { url, apiKey } = options.etherscan; + network.attachPlugin(new EtherscanPlugin(url, apiKey)); + } + network.attachPlugin(new GasCostPlugin()); + return network; + }; + // Register the network by name and chain ID + Network.register(name, func); + Network.register(chainId, func); + if (options.altNames) { + options.altNames.forEach((name) => { + Network.register(name, func); + }); + } + } + registerEth("homestead", 1, { ensNetwork: 1, altNames: ["mainnet"] }); + registerEth("ropsten", 3, { ensNetwork: 3 }); + registerEth("rinkeby", 4, { ensNetwork: 4 }); + registerEth("goerli", 5, { ensNetwork: 5 }); + registerEth("kovan", 42, { ensNetwork: 42 }); + registerEth("classic", 61, {}); + registerEth("classicKotti", 6, {}); + registerEth("xdai", 100, { ensNetwork: 1 }); + // Polygon has a 35 gwei maxPriorityFee requirement + registerEth("matic", 137, { + ensNetwork: 1, + // priorityFee: 35000000000, + etherscan: { + apiKey: "W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7", + url: "https:/\/api.polygonscan.com/" + } + }); + registerEth("maticMumbai", 80001, { + // priorityFee: 35000000000, + etherscan: { + apiKey: "W6T8DJW654GNTQ34EFEYYP3EZD9DD27CT7", + url: "https:/\/api-testnet.polygonscan.com/" + } + }); + registerEth("bnb", 56, { + ensNetwork: 1, + etherscan: { + apiKey: "EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9", + url: "http:/\/api.bscscan.com" + } + }); + registerEth("bnbt", 97, { + etherscan: { + apiKey: "EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9", + url: "http:/\/api-testnet.bscscan.com" + } + }); +} +injectCommonNetworks(); +export { Network }; +//# sourceMappingURL=common-networks.js.map \ No newline at end of file diff --git a/lib.esm/providers/common-networks.js.map b/lib.esm/providers/common-networks.js.map new file mode 100644 index 000000000..30f62cbcf --- /dev/null +++ b/lib.esm/providers/common-networks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common-networks.js","sourceRoot":"","sources":["../../src.ts/providers/common-networks.ts"],"names":[],"mappings":"AACA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE1D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AASvC,6BAA6B;AAC7B,MAAM,UAAU,oBAAoB;IAEhC,sCAAsC;IACtC,SAAS,WAAW,CAAC,IAAY,EAAE,OAAe,EAAE,OAAgB;QAChE,MAAM,IAAI,GAAG;YACT,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAE3C,0BAA0B;YAC1B,IAAI,OAAO,CAAC,UAAU,IAAI,IAAI,EAAE;gBAC5B,OAAO,CAAC,YAAY,CAAC,IAAI,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;aACjE;YAED,IAAI,OAAO,CAAC,WAAW,EAAE;gBACrC,sFAAsF;aACzE;YAED,IAAI,OAAO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W,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC,CAAC;IAE5C,mDAAmD;IACnD,WAAW,CAAC,OAAO,EAAE,GAAG,EAAE;QACtB,UAAU,EAAE,CAAC;QACrB,mCAAmC;QAC3B,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,+BAA+B;SACvC;KACJ,CAAC,CAAC;IACH,WAAW,CAAC,aAAa,EAAE,KAAK,EAAE;QACtC,mCAAmC;QAC3B,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,uCAAuC;SAC/C;KACJ,CAAC,CAAC;IAEH,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE;QACnB,UAAU,EAAE,CAAC;QACb,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,yBAAyB;SACjC;KACJ,CAAC,CAAC;IACH,WAAW,CAAC,MAAM,EAAE,EAAE,EAAE;QACpB,SAAS,EAAE;YACP,MAAM,EAAE,oCAAoC;YAC5C,GAAG,EAAE,iCAAiC;SACzC;KACJ,CAAC,CAAC;AACP,CAAC;AAED,oBAAoB,EAAE,CAAC;AAEvB,OAAO,EAAE,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/community.js b/lib.esm/providers/community.js new file mode 100644 index 000000000..f89c309ff --- /dev/null +++ b/lib.esm/providers/community.js @@ -0,0 +1,21 @@ +// Show the throttle message only once +const shown = new Set(); +export function showThrottleMessage(service) { + if (shown.has(service)) { + return; + } + shown.add(service); + console.log("========= NOTICE ========="); + console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`); + console.log(""); + console.log("The default API keys for each service are provided as a highly-throttled,"); + console.log("community resource for low-traffic projects and early prototyping."); + console.log(""); + console.log("While your application will continue to function, we highly recommended"); + console.log("signing up for your own API keys to improve performance, increase your"); + console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); + console.log(""); + console.log("For more details: https:/\/docs.ethers.io/api-keys/"); + console.log("=========================="); +} +//# sourceMappingURL=community.js.map \ No newline at end of file diff --git a/lib.esm/providers/community.js.map b/lib.esm/providers/community.js.map new file mode 100644 index 000000000..e32b68b4c --- /dev/null +++ b/lib.esm/providers/community.js.map @@ -0,0 +1 @@ +{"version":3,"file":"community.js","sourceRoot":"","sources":["../../src.ts/providers/community.ts"],"names":[],"mappings":"AAKA,sCAAsC;AACtC,MAAM,KAAK,GAAgB,IAAI,GAAG,EAAE,CAAC;AACrC,MAAM,UAAU,mBAAmB,CAAC,OAAe;IAC/C,IAAI,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;QAAE,OAAO;KAAE;IACnC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAEnB,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;IACzC,OAAO,CAAC,GAAG,CAAC,6BAA8B,OAAQ,sCAAsC,CAAC,CAAC;IAC1F,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;IACzF,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IAClF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,yEAAyE,CAAC,CAAC;IACvF,OAAO,CAAC,GAAG,CAAC,wEAAwE,CAAC,CAAC;IACtF,OAAO,CAAC,GAAG,CAAC,+EAA+E,CAAC,CAAC;IAC7F,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChB,OAAO,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAAC;IACnE,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAC9C,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/contracts.js b/lib.esm/providers/contracts.js new file mode 100644 index 000000000..202a39eb5 --- /dev/null +++ b/lib.esm/providers/contracts.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=contracts.js.map \ No newline at end of file diff --git a/lib.esm/providers/contracts.js.map b/lib.esm/providers/contracts.js.map new file mode 100644 index 000000000..42ac4de89 --- /dev/null +++ b/lib.esm/providers/contracts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../src.ts/providers/contracts.ts"],"names":[],"mappings":""} \ 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 000000000..ffd1010c3 --- /dev/null +++ b/lib.esm/providers/default-provider.js @@ -0,0 +1,94 @@ +import { AnkrProvider } from "./provider-ankr.js"; +import { AlchemyProvider } from "./provider-alchemy.js"; +import { CloudflareProvider } from "./provider-cloudflare.js"; +import { EtherscanProvider } from "./provider-etherscan.js"; +import { InfuraProvider } from "./provider-infura.js"; +//import { PocketProvider } from "./provider-pocket.js"; +import { FallbackProvider } from "./provider-fallback.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import { WebSocketProvider } from "./provider-websocket.js"; +function isWebSocketLike(value) { + return (value && typeof (value.send) === "function" && + typeof (value.close) === "function"); +} +export function getDefaultProvider(network, options) { + if (options == null) { + options = {}; + } + if (typeof (network) === "string" && network.match(/^https?:/)) { + return new JsonRpcProvider(network); + } + if (typeof (network) === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) { + return new WebSocketProvider(network); + } + const providers = []; + if (options.alchemy !== "-") { + try { + providers.push(new AlchemyProvider(network, options.alchemy)); + } + catch (error) { + console.log(error); + } + } + if (options.ankr !== "-") { + try { + providers.push(new AnkrProvider(network, options.ankr)); + } + catch (error) { + console.log(error); + } + } + if (options.cloudflare !== "-") { + try { + providers.push(new CloudflareProvider(network)); + } + catch (error) { + console.log(error); + } + } + if (options.etherscan !== "-") { + try { + providers.push(new EtherscanProvider(network, options.etherscan)); + } + catch (error) { + console.log(error); + } + } + if (options.infura !== "-") { + try { + let projectId = options.infura; + let projectSecret = undefined; + if (typeof (projectId) === "object") { + projectSecret = projectId.projectSecret; + projectId = projectId.projectId; + } + providers.push(new InfuraProvider(network, projectId, projectSecret)); + } + catch (error) { + console.log(error); + } + } + /* + 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); } + } + */ + if (providers.length === 0) { + throw new Error("TODO"); + } + if (providers.length === 1) { + return providers[0]; + } + return new FallbackProvider(providers); +} +//# 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 000000000..e5cacb212 --- /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,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,wDAAwD;AAExD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,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,KA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,CAAC;SAAE;KAC1C;IAED,IAAI,OAAO,CAAC,SAAS,KAAK,GAAG,EAAE;QAC3B,IAAI;YACA,SAAS,CAAC,IAAI,CAAC,IAAI,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;SACrE;QAAC,OAAO,KAAK,EAAE;YAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAAE;KAC1C;IAED,IAAI,OAAO,CAAC,MAAM,KAAK,GAAG,EAAE;QACxB,IAAI;YACA,IAAI,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC;YAC/B,IAAI,aAAa,GAAuB,SAAS,CAAC;YAClD,IAAI,OAAM,CAAC,SAAS,CAAC,KAAK,QAAQ,EAAE;gBAChC,aAAa,GAAG,SAAS,CAAC,aAAa,CAAC;gBACxC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;aACnC;YACD,SAAS,CAAC,IAAI,CAAC,IAAI,cAAc,CAAC,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC,CAAC;SACzE;QAAC,OAAO,KAAK,EAAE;YAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAAE;KAC1C;IACL;;;;;;;;;;;;;;MAcE;IACE,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC;KAAE;IACxD,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAAE,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC;KAAE;IAEpD,OAAO,IAAI,gBAAgB,CAAC,SAAS,CAAC,CAAC;AAC3C,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/ens-resolver.js b/lib.esm/providers/ens-resolver.js new file mode 100644 index 000000000..83b1569db --- /dev/null +++ b/lib.esm/providers/ens-resolver.js @@ -0,0 +1,465 @@ +import { ZeroHash } from "../constants/hashes.js"; +import { dnsEncode, namehash } from "../hash/index.js"; +import { defineProperties, encodeBase58, toArray, toNumber, toUtf8Bytes, toUtf8String } from "../utils/index.js"; +import { concat, dataSlice, hexlify, zeroPadValue } from "../utils/data.js"; +import { FetchRequest } from "../utils/fetch.js"; +import { logger } from "../utils/logger.js"; +const BN_1 = BigInt(1); +const Empty = new Uint8Array([]); +function parseBytes(result, start) { + if (result === "0x") { + return null; + } + const offset = toNumber(dataSlice(result, start, start + 32)); + const length = toNumber(dataSlice(result, offset, offset + 32)); + return dataSlice(result, offset + 32, offset + 32 + length); +} +function parseString(result, start) { + try { + const bytes = parseBytes(result, start); + if (bytes != null) { + return toUtf8String(bytes); + } + } + catch (error) { } + return null; +} +function numPad(value) { + const result = toArray(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) { + if ((value.length % 32) === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +// ABI Encodes a series of (bytes, bytes, ...) +function encodeBytes(datas) { + const result = []; + 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 = logger.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); +} +// @TODO: This should use the fetch-data:ipfs gateway +// Trim off the ipfs:// prefix and return the default gateway URL +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } + else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } + else { + logger.throwArgumentError("unsupported IPFS format", "link", link); + } + return `https:/\/gateway.ipfs.io/ipfs/${link}`; +} +; +; +export class MulticoinProviderPlugin { + name; + constructor(name) { + defineProperties(this, { name }); + } + validate(proivder) { + return this; + } + supportsCoinType(coinType) { + return false; + } + async encodeAddress(coinType, address) { + throw new Error("unsupported coin"); + } + async decodeAddress(coinType, data) { + throw new Error("unsupported coin"); + } +} +const BasicMulticoinPluginId = "org.ethers.provider-prugins.basicmulticoin"; +export class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin { + constructor() { + super(BasicMulticoinPluginId); + } +} +const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i"); +const matchers = [ + new RegExp("^(https):/\/(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"), +]; +export class EnsResolver { + provider; + address; + name; + // For EIP-2544 names, the ancestor that provided the resolver + #supports2544; + constructor(provider, address, name) { + defineProperties(this, { provider, address, name }); + this.#supports2544 = null; + } + async supportsWildcard() { + if (!this.#supports2544) { + // supportsInterface(bytes4 = selector("resolve(bytes,bytes)")) + this.#supports2544 = this.provider.call({ + to: this.address, + data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000" + }).then((result) => { + return (logger.getBigInt(result) === BN_1); + }).catch((error) => { + if (error.code === "CALL_EXCEPTION") { + return false; + } + // Rethrow the error: link is down, etc. Let future attempts retry. + this.#supports2544 = null; + throw error; + }); + } + return await this.#supports2544; + } + async _fetch(selector, parameters = "0x") { + // e.g. keccak256("addr(bytes32,uint256)") + const addrData = concat([selector, namehash(this.name), parameters]); + const tx = { + to: this.address, + enableCcipRead: true, + data: addrData + }; + // Wildcard support; use EIP-2544 to resolve the request + let wrapped = false; + if (await this.supportsWildcard()) { + wrapped = true; + // selector("resolve(bytes,bytes)") + tx.data = concat(["0x9061b923", encodeBytes([dnsEncode(this.name), addrData])]); + } + try { + let data = await this.provider.call(tx); + if ((logger.getBytes(data).length % 32) === 4) { + return logger.throwError("resolver threw error", "CALL_EXCEPTION", { + transaction: tx, data + }); + } + if (wrapped) { + return parseBytes(data, 0); + } + return data; + } + catch (error) { + if (error.code !== "CALL_EXCEPTION") { + throw error; + } + } + return null; + } + async getAddress(coinType = 60) { + if (coinType === 60) { + try { + // keccak256("addr(bytes32)") + const result = await this._fetch("0x3b3b57de"); + // No address + if (result === "0x" || result === ZeroHash) { + return null; + } + const network = await this.provider.getNetwork(); + return network.formatter.callAddress(result); + } + catch (error) { + if (error.code === "CALL_EXCEPTION") { + return null; + } + throw error; + } + } + let coinPlugin = null; + for (const plugin of this.provider.plugins) { + if (!(plugin instanceof MulticoinProviderPlugin)) { + continue; + } + if (plugin.supportsCoinType(coinType)) { + coinPlugin = plugin; + break; + } + } + if (coinPlugin == null) { + return null; + } + // keccak256("addr(bytes32,uint256") + const data = parseBytes((await this._fetch("0xf1cb7e06", numPad(coinType))) || "0x", 0); + // No address + if (data == null || data === "0x") { + return null; + } + // Compute the address + const address = await coinPlugin.encodeAddress(coinType, data); + if (address != null) { + return address; + } + return logger.throwError(`invalid coin data`, "UNSUPPORTED_OPERATION", { + operation: `getAddress(${coinType})`, + info: { coinType, data } + }); + } + async getText(key) { + // The key encoded as parameter to fetchBytes + let keyBytes = toUtf8Bytes(key); + // The nodehash consumes the first slot, so the string pointer targets + // offset 64, with the length at offset 64 and data starting at offset 96 + const calldata = logger.getBytes(concat([numPad(64), numPad(keyBytes.length), keyBytes])); + const hexBytes = parseBytes((await this._fetch("0x59d1d43c", bytesPad(calldata))) || "0x", 0); + if (hexBytes == null || hexBytes === "0x") { + return null; + } + return toUtf8String(hexBytes); + } + async getContentHash() { + // keccak256("contenthash()") + const hexBytes = parseBytes((await this._fetch("0xbc1c58d1")) || "0x", 0); + // No contenthash + if (hexBytes == null || hexBytes === "0x") { + return null; + } + // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key) + const ipfs = hexBytes.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const scheme = (ipfs[1] === "e3010170") ? "ipfs" : "ipns"; + const length = parseInt(ipfs[4], 16); + if (ipfs[5].length === length * 2) { + return `${scheme}:/\/${encodeBase58("0x" + ipfs[2])}`; + } + } + // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32) + const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm && swarm[1].length === 64) { + return `bzz:/\/${swarm[1]}`; + } + return logger.throwError(`invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { + operation: "getContentHash()", + info: { data: hexBytes } + }); + } + async getAvatar() { + return (await this._getAvatar()).url; + } + async _getAvatar() { + const linkage = [{ type: "name", value: this.name }]; + try { + // test data for ricmoo.eth + //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233"; + const avatar = await this.getText("avatar"); + if (avatar == null) { + linkage.push({ type: "!avatar", value: "" }); + throw new Error("!avatar"); + } + linkage.push({ type: "avatar", value: avatar }); + for (let i = 0; i < matchers.length; i++) { + const match = avatar.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch (scheme) { + case "https": + case "data": + linkage.push({ type: "url", value: avatar }); + return { linkage, url: avatar }; + case "ipfs": { + const url = getIpfsLink(avatar); + linkage.push({ type: "ipfs", value: avatar }); + linkage.push({ type: "url", value: url }); + return { linkage, url }; + } + case "erc721": + case "erc1155": { + // Depending on the ERC type, use tokenURI(uint256) or url(uint256) + const selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c"; + linkage.push({ type: scheme, value: avatar }); + // The owner of this name + const owner = await this.getAddress(); + if (owner == null) { + linkage.push({ type: "!owner", value: "" }); + throw new Error("!owner"); + } + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + linkage.push({ type: `!${scheme}caip`, value: (match[2] || "") }); + throw new Error("!caip"); + } + const formatter = (await this.provider.getNetwork()).formatter; + const addr = formatter.address(comps[0]); + const tokenId = numPad(comps[1]); + // Check that this account owns the token + if (scheme === "erc721") { + // ownerOf(uint256 tokenId) + const tokenOwner = formatter.callAddress(await this.provider.call({ + to: addr, data: concat(["0x6352211e", tokenId]) + })); + if (owner !== tokenOwner) { + linkage.push({ type: "!owner", value: tokenOwner }); + throw new Error("!owner"); + } + linkage.push({ type: "owner", value: tokenOwner }); + } + else if (scheme === "erc1155") { + // balanceOf(address owner, uint256 tokenId) + const balance = logger.getBigInt(await this.provider.call({ + to: addr, data: concat(["0x00fdd58e", zeroPadValue(owner, 32), tokenId]) + })); + if (!balance) { + linkage.push({ type: "!balance", value: "0" }); + throw new Error("!balance"); + } + linkage.push({ type: "balance", value: balance.toString() }); + } + // Call the token contract for the metadata URL + const tx = { + to: comps[0], + data: concat([selector, tokenId]) + }; + let metadataUrl = parseString(await this.provider.call(tx), 0); + if (metadataUrl == null) { + linkage.push({ type: "!metadata-url", value: "" }); + throw new Error("!metadata-url"); + } + linkage.push({ type: "metadata-url-base", value: metadataUrl }); + // ERC-1155 allows a generic {id} in the URL + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", hexlify(tokenId).substring(2)); + linkage.push({ type: "metadata-url-expanded", value: metadataUrl }); + } + // Transform IPFS metadata links + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ type: "metadata-url", value: metadataUrl }); + // Get the token metadata + let metadata = {}; + const response = await (new FetchRequest(metadataUrl)).send(); + response.assertOk(); + try { + metadata = response.bodyJson; + } + catch (error) { + try { + linkage.push({ type: "!metadata", value: response.bodyText }); + } + catch (error) { + const bytes = response.body; + if (bytes) { + linkage.push({ type: "!metadata", value: hexlify(bytes) }); + } + throw error; + } + throw error; + } + if (!metadata) { + linkage.push({ type: "!metadata", value: "" }); + throw new Error("!metadata"); + } + linkage.push({ type: "metadata", value: JSON.stringify(metadata) }); + // Pull the image URL out + let imageUrl = metadata.image; + if (typeof (imageUrl) !== "string") { + linkage.push({ type: "!imageUrl", value: "" }); + throw new Error("!imageUrl"); + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) { + // Allow + } + else { + // Transform IPFS link to gateway + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + linkage.push({ type: "!imageUrl-ipfs", value: imageUrl }); + throw new Error("!imageUrl-ipfs"); + } + linkage.push({ type: "imageUrl-ipfs", value: imageUrl }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ type: "url", value: imageUrl }); + return { linkage, url: imageUrl }; + } + } + } + } + catch (error) { + console.log("EE", error); + } + return { linkage, url: null }; + } + static async #getResolver(provider, name) { + const network = await provider.getNetwork(); + const ensPlugin = network.getPlugin("org.ethers.network-plugins.ens"); + // No ENS... + if (!ensPlugin) { + return logger.throwError("network does not support ENS", "UNSUPPORTED_OPERATION", { + operation: "getResolver", info: { network: network.name } + }); + } + try { + // keccak256("resolver(bytes32)") + const addrData = await provider.call({ + to: ensPlugin.address, + data: concat(["0x0178b8bf", namehash(name)]), + enableCcipRead: true + }); + const addr = network.formatter.callAddress(addrData); + if (addr === dataSlice(ZeroHash, 0, 20)) { + return null; + } + return addr; + } + catch (error) { + // ENS registry cannot throw errors on resolver(bytes32), + // so probably a link error + throw error; + } + return null; + } + static async fromName(provider, name) { + let currentName = name; + while (true) { + if (currentName === "" || currentName === ".") { + return null; + } + // Optimization since the eth node cannot change and does + // not have a wildcar resolver + if (name !== "eth" && currentName === "eth") { + return null; + } + // Check the current node for a resolver + const addr = await EnsResolver.#getResolver(provider, currentName); + // Found a resolver! + if (addr != null) { + const resolver = new EnsResolver(provider, addr, name); + // Legacy resolver found, using EIP-2544 so it isn't safe to use + if (currentName !== name && !(await resolver.supportsWildcard())) { + return null; + } + return resolver; + } + // Get the parent node + currentName = currentName.split(".").slice(1).join("."); + } + } +} +//# sourceMappingURL=ens-resolver.js.map \ No newline at end of file diff --git a/lib.esm/providers/ens-resolver.js.map b/lib.esm/providers/ens-resolver.js.map new file mode 100644 index 000000000..e112febb7 --- /dev/null +++ b/lib.esm/providers/ens-resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ens-resolver.js","sourceRoot":"","sources":["../../src.ts/provid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IAAI,EAAE;gBACd,MAAM,QAAQ,GAAG,IAAI,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;gBAEvD,gEAAgE;gBAChE,IAAI,WAAW,KAAK,IAAI,IAAI,CAAC,CAAC,MAAM,QAAQ,CAAC,gBAAgB,EAAE,CAAC,EAAE;oBAAE,OAAO,IAAI,CAAC;iBAAE;gBAElF,OAAO,QAAQ,CAAC;aACnB;YAED,sBAAsB;YACtB,WAAW,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAC3D;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/formatter.js b/lib.esm/providers/formatter.js new file mode 100644 index 000000000..bc3d47cc9 --- /dev/null +++ b/lib.esm/providers/formatter.js @@ -0,0 +1,385 @@ +// Belongs to Networks; requires abstract-provider +// provider requires abstract-provider and network +/** + * Formatter + * + * This is responsibile for converting much of the various + * loose network values into a concrete ethers-ready value. + * + * For example, converting addresses to checksum addresses, + * validating a hash is 32 bytes, and so on. + * + * By sub-classing this class and providing it in a custom + * Network object this allows exotic (non-Ethereum) networks + * to be fairly simple to adapt to ethers. + */ +import { getAddress, getCreateAddress } from "../address/index.js"; +import { dataLength, dataSlice, isHexString } from "../utils/data.js"; +import { toQuantity } from "../utils/maths.js"; +import { logger } from "../utils/logger.js"; +import { Signature } from "../crypto/signature.js"; +import { accessListify } from "../transaction/index.js"; +import { Block, Log, TransactionReceipt, TransactionResponse } from "./provider.js"; +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +//export type AccessListSet = { address: string, storageKeys: Array }; +//export type AccessList = Array; +//export type AccessListish = AccessList | +// Array<[ string, Array ]> | +// Record>; +function stringify(value) { + if (typeof (value) !== "string") { + throw new Error("invalid string"); + } + return value; +} +export class Formatter { + #format; + #baseBlock; + constructor() { + const address = this.address.bind(this); + const bigNumber = this.bigNumber.bind(this); + const blockTag = this.blockTag.bind(this); + const data = this.data.bind(this); + const hash = this.hash.bind(this); + const number = this.number.bind(this); + const uint256 = this.uint256.bind(this); + const topics = this.arrayOf(hash); + this.#format = { + address, + bigNumber, + blockTag, + data, + hash, + number, + uint256, + topics, + filter: this.object({ + fromBlock: this.allowNull(blockTag, undefined), + toBlock: this.allowNull(blockTag, undefined), + blockHash: this.allowNull(hash, undefined), + address: this.allowNull(address, undefined), + topics: this.allowNull(topics, undefined) + }), + transactionRequest: this.object({ + from: this.allowNull(address), + type: this.allowNull(number), + to: this.allowNull(address), + nonce: this.allowNull(number), + gasLimit: this.allowNull(uint256), + gasPrice: this.allowNull(uint256), + maxFeePerGas: this.allowNull(uint256), + maxPriorityFeePerGas: this.allowNull(uint256), + data: this.allowNull(data), + value: this.allowNull(uint256), + }), + transactionResponse: this.object({ + hash: hash, + index: number, + type: this.allowNull(number, 0), + // These can be null for pending blocks + blockHash: this.allowNull(hash), + blockNumber: this.allowNull(number), + // For Legacy transactions, this comes from the v + chainId: this.allowNull(number), + from: address, + to: this.address, + gasLimit: bigNumber, + gasPrice: this.allowNull(bigNumber), + maxFeePerGas: this.allowNull(bigNumber), + maxPriorityFeePerGas: this.allowNull(bigNumber), + value: bigNumber, + data: data, + nonce: number, + r: hash, + s: hash, + v: number, + accessList: this.allowNull(this.accessList) + }, { + index: ["transactionIndex"] + }), + }; + this.#baseBlock = this.object({ + number: number, + hash: this.allowNull(hash, null), + timestamp: number, + parentHash: hash, + nonce: this.allowNull(stringify, "0x0000000000000000"), + difficulty: bigNumber, + gasLimit: bigNumber, + gasUsed: bigNumber, + miner: this.allowNull(address, "0x0000000000000000000000000000000000000000"), + extraData: stringify, + baseFeePerGas: this.allowNull(bigNumber), + }); + } + // An address + address(value) { + return getAddress(value); + } + // An address from a call result; may be zero-padded + callAddress(value) { + if (dataLength(value) !== 32 || dataSlice(value, 0, 12) !== "0x000000000000000000000000") { + logger.throwArgumentError("invalid call address", "value", value); + } + return this.address(dataSlice(value, 12)); + } + // An address from a transaction (e.g. { from: string, nonce: number }) + contractAddress(value) { + return getCreateAddress({ + from: this.address(value.from), + nonce: logger.getNumber(value.nonce, "value.nonce") + }); + } + // Block Tag + blockTag(value) { + if (value == null) { + return "latest"; + } + switch (value) { + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return value; + } + if (typeof (value) === "number" || (isHexString(value) && dataLength(value) < 32)) { + return toQuantity(value); + } + return logger.throwArgumentError("invalid blockTag", "value", value); + } + // Block objects + block(value, provider) { + const params = this.#baseBlock(value); + params.transactions = value.transactions.map((t) => this.hash(t)); + return new Block(params, provider); + } + blockWithTransactions(value, provider) { + throw new Error(); + } + // Transactions + transactionRequest(value, provider) { + return this.#format.transactionRequest(value); + } + transactionResponse(value, provider) { + value = Object.assign({}, value); + // @TODO: Use the remap feature + if (value.data == null && value.input != null) { + value.data = value.input; + } + if (value.gasLimit == null && value.gas) { + value.gasLimit = value.gas; + } + value = this.#format.transactionResponse(value); + const sig = Signature.from({ r: value.r, s: value.s, v: value.v }); + value.signature = sig; + if (value.chainId == null) { + value.chainId = sig.legacyChainId; + } + return new TransactionResponse(value, provider); + } + // Receipts + log(value, provider) { + const log = this.object({ + address: this.address, + blockHash: this.hash, + blockNumber: this.number, + data: this.data, + index: this.number, + removed: this.boolean, + topics: this.topics, + transactionHash: this.hash, + transactionIndex: this.number, + }, { + index: ["logIndex"] + })(value); + return new Log(log, provider); + } + receipt(value, provider) { + const receipt = this.object({ + blockHash: this.hash, + blockNumber: this.number, + contractAddress: this.allowNull(this.address), + cumulativeGasUsed: this.bigNumber, + from: this.address, + gasUsed: this.bigNumber, + logs: this.arrayOf((v) => (this.log(v, provider))), + logsBloom: this.data, + root: this.allowNull(this.data), + status: this.allowNull(this.number), + to: this.address, + gasPrice: this.allowNull(this.bigNumber), + hash: this.hash, + index: this.number, + type: this.allowNull(this.number, 0), + }, { + hash: ["transactionHash"], + gasPrice: ["effectiveGasPrice"], + index: ["transactionIndex"] + })(value); + // RSK incorrectly implemented EIP-658, so we munge things a bit here for it + if (receipt.root != null) { + if (receipt.root.length <= 4) { + // Could be 0x00, 0x0, 0x01 or 0x1 + const value = parseInt(receipt.root); + if (value === 0 || value === 1) { + // Make sure if both are specified, they match + if (receipt.status != null && receipt.status !== value) { + return logger.throwError("alt-root-status/status mismatch", "BAD_DATA", { + value: { root: receipt.root, status: receipt.status } + }); + } + receipt.status = value; + delete receipt.root; + } + else { + return logger.throwError("invalid alt-root-status", "BAD_DATA", { + value: receipt.root + }); + } + } + else if (!isHexString(receipt.root, 32)) { + // Must be a valid bytes32 + return logger.throwError("invalid receipt root hash", "BAD_DATA", { + value: receipt.root + }); + } + } + //receipt.byzantium = (receipt.root == null); + return new TransactionReceipt(receipt, provider); + } + // Fitlers + topics(value) { + return this.#format.topics(value); + } + filter(value) { + return this.#format.filter(value); + } + filterLog(value) { + console.log("ME", value); + return null; + } + // Converts a serialized transaction to a TransactionResponse + transaction(value) { + throw new Error(); + } + // Useful utility formatters functions, which if need be use the + // methods within the formatter to ensure internal compatibility + // Access List; converts an AccessListish to an AccessList + accessList(value) { + return accessListify(value); + } + // Converts falsish values to a specific value, otherwise use the formatter. Calls preserve `this`. + allowFalsish(format, ifFalse) { + return ((value) => { + if (!value) { + return ifFalse; + } + return format.call(this, value); + }); + } + // Allows null, optionally replacing it with a default value. Calls preserve `this`. + allowNull(format, ifNull) { + return ((value) => { + if (value == null) { + return ifNull; + } + return format.call(this, value); + }); + } + // Requires an Array satisfying the formatter. Calls preserves `this`. + arrayOf(format) { + return ((array) => { + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + return array.map((i) => format.call(this, i)); + }); + } + // Requires a value which is a value BigNumber + bigNumber(value) { + return logger.getBigInt(value, "value"); + } + uint256(value) { + const result = this.bigNumber(value); + if (result < 0 || result > BN_MAX_UINT256) { + logger.throwArgumentError("invalid uint256", "value", value); + } + return result; + } + // Requires a value which is a value boolean or string equivalent + boolean(value) { + switch (value) { + case true: + case "true": + return true; + case false: + case "false": + return false; + } + return logger.throwArgumentError(`invalid boolean; ${JSON.stringify(value)}`, "value", value); + } + // Requires a value which is a valid hexstring. If dataOrLength is true, + // the length must be even (i.e. a datahexstring) or if it is a number, + // specifies teh number of bytes value must represent + _hexstring(dataOrLength) { + if (dataOrLength == null) { + dataOrLength = false; + } + return (function (value) { + if (isHexString(value, dataOrLength)) { + return value.toLowerCase(); + } + throw new Error("bad hexstring"); + }); + } + data(value) { + if (dataLength(value) == null) { + logger.throwArgumentError("", "value", value); + } + return value; + } + // Requires a network-native hash + hash(value) { + if (dataLength(value) !== 32) { + logger.throwArgumentError("", "value", value); + } + return this.#format.data(value); + } + // Requires a valid number, within the IEEE 754 safe range + number(value) { + return logger.getNumber(value); + } + // Requires an object which matches a fleet of other formatters + // Any FormatFunc may return `undefined` to have the value omitted + // from the result object. Calls preserve `this`. + object(format, altNames) { + return ((value) => { + const result = {}; + for (const key in format) { + let srcKey = key; + if (altNames && key in altNames && !(srcKey in value)) { + for (const altKey of altNames[key]) { + if (altKey in value) { + srcKey = altKey; + break; + } + } + } + try { + const nv = format[key].call(this, value[srcKey]); + if (nv !== undefined) { + result[key] = nv; + } + } + catch (error) { + const message = (error instanceof Error) ? error.message : "not-an-error"; + logger.throwError(`invalid value for value.${key} (${message})`, "BAD_DATA", { value }); + } + } + return result; + }); + } +} +//# sourceMappingURL=formatter.js.map \ No newline at end of file diff --git a/lib.esm/providers/formatter.js.map b/lib.esm/providers/formatter.js.map new file mode 100644 index 000000000..0683c34ee --- /dev/null +++ b/lib.esm/providers/formatter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatter.js","sourceRoot":"","sources":["../../src.ts/providers/formatter.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,kDAAkD;AAElD;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACnE,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AAU;QACb,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IAED,+DAA+D;IAC/D,kEAAkE;IAClE,iDAAiD;IACjD,MAAM,CAAC,MAAkC,EAAE,QAAwC;QAC/E,OAAO,CAAC,CAAC,KAAU,EAAE,EAAE;YACnB,MAAM,MAAM,GAAQ,EAAG,CAAC;YACxB,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;gBACtB,IAAI,MAAM,GAAG,GAAG,CAAC;gBACjB,IAAI,QAAQ,IAAI,GAAG,IAAI,QAAQ,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,EAAE;oBACnD,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,GAAG,CAAC,EAAE;wBAChC,IAAI,MAAM,IAAI,KAAK,EAAE;4BACjB,MAAM,GAAG,MAAM,CAAC;4BAChB,MAAM;yBACT;qBACJ;iBACJ;gBAED,IAAI;oBACA,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;oBACjD,IAAI,EAAE,KAAK,SAAS,EAAE;wBAAE,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;qBAAE;iBAC9C;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,OAAO,GAAG,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAA,CAAC,CAAC,cAAc,CAAC;oBACzE,MAAM,CAAC,UAAU,CAAC,2BAA4B,GAAI,KAAM,OAAQ,GAAG,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;iBAC9F;aACJ;YACD,OAAO,MAAM,CAAC;QAClB,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/index.js b/lib.esm/providers/index.js new file mode 100644 index 000000000..8268a3140 --- /dev/null +++ b/lib.esm/providers/index.js @@ -0,0 +1,38 @@ +/* +export { + AbstractProvider, UnmanagedSubscriber +} from "./abstract-provider.js"; +*/ +export { AbstractSigner, VoidSigner, WrappedSigner } from "./abstract-signer.js"; +/* +export { + showThrottleMessage +} from "./community.js"; + +export { getDefaultProvider } from "./default-provider.js"; + +export { EnsResolver } from "./ens-resolver.js"; +*/ +export { Formatter } from "./formatter.js"; +export { Network } from "./common-networks.js"; +export { NetworkPlugin, GasCostPlugin, EnsPlugin, +//LayerOneConnectionPlugin, +//MaxPriorityFeePlugin, +//PriceOraclePlugin, + } from "./plugins-network.js"; +export { Block, FeeData, Log, TransactionReceipt, TransactionResponse, dummyProvider, copyRequest, +//resolveTransactionRequest, + } from "./provider.js"; +export { FallbackProvider } from "./provider-fallback.js"; +export { JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner } from "./provider-jsonrpc.js"; +export { AlchemyProvider } from "./provider-alchemy.js"; +export { AnkrProvider } from "./provider-ankr.js"; +export { CloudflareProvider } from "./provider-cloudflare.js"; +export { EtherscanProvider } from "./provider-etherscan.js"; +export { InfuraProvider } from "./provider-infura.js"; +//export { PocketProvider } from "./provider-pocket.js"; +import { IpcSocketProvider } from "./provider-ipcsocket.js"; /*-browser*/ +export { IpcSocketProvider }; +export { SocketProvider } from "./provider-socket.js"; +export { WebSocketProvider } from "./provider-websocket.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/providers/index.js.map b/lib.esm/providers/index.js.map new file mode 100644 index 000000000..37aae19e8 --- /dev/null +++ b/lib.esm/providers/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/providers/index.ts"],"names":[],"mappings":"AAAA;;;;EAIE;AAEF,OAAO,EACH,cAAc,EACd,UAAU,EACV,aAAa,EAChB,MAAM,sBAAsB,CAAC;AAC9B;;;;;;;;EAQE;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAE/C,OAAO,EACH,aAAa,EACb,aAAa,EACb,SAAS;AACT,2BAA2B;AAC3B,uBAAuB;AACvB,oBAAoB;EACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACH,KAAK,EACL,OAAO,EACP,GAAG,EACH,kBAAkB,EAClB,mBAAmB,EAEnB,aAAa,EAEb,WAAW;AACX,4BAA4B;EAC/B,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,wDAAwD;AAExD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC,CAAC,YAAY;AACzE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/network.js b/lib.esm/providers/network.js new file mode 100644 index 000000000..b8f851b01 --- /dev/null +++ b/lib.esm/providers/network.js @@ -0,0 +1,187 @@ +import { logger } from "../utils/logger.js"; +import { getStore, setStore } from "../utils/storage.js"; +import { Formatter } from "./formatter.js"; +import { EnsPlugin, GasCostPlugin } from "./plugins-network.js"; +/* * * * +// Networks which operation against an L2 can use this plugin to +// specify how to access L1, for the purpose of resolving ENS, +// for example. +export class LayerOneConnectionPlugin extends NetworkPlugin { + readonly provider!: Provider; +// @TODO: Rename to ChainAccess and allow for connecting to any chain + constructor(provider: Provider) { + super("org.ethers.plugins.layer-one-connection"); + defineProperties(this, { provider }); + } + + clone(): LayerOneConnectionPlugin { + return new LayerOneConnectionPlugin(this.provider); + } +} +*/ +/* * * * +export class PriceOraclePlugin extends NetworkPlugin { + readonly address!: string; + + constructor(address: string) { + super("org.ethers.plugins.price-oracle"); + defineProperties(this, { address }); + } + + clone(): PriceOraclePlugin { + return new PriceOraclePlugin(this.address); + } +} +*/ +// Networks or clients with a higher need for security (such as clients +// that may automatically make CCIP requests without user interaction) +// can use this plugin to anonymize requests or intercept CCIP requests +// to notify and/or receive authorization from the user +/* * * * +export type FetchDataFunc = (req: Frozen) => Promise; +export class CcipPreflightPlugin extends NetworkPlugin { + readonly fetchData!: FetchDataFunc; + + constructor(fetchData: FetchDataFunc) { + super("org.ethers.plugins.ccip-preflight"); + defineProperties(this, { fetchData }); + } + + clone(): CcipPreflightPlugin { + return new CcipPreflightPlugin(this.fetchData); + } +} +*/ +const Networks = new Map(); +const defaultFormatter = new Formatter(); +export class Network { + #props; + constructor(name, _chainId, formatter) { + const chainId = logger.getBigInt(_chainId); + if (formatter == null) { + formatter = defaultFormatter; + } + const plugins = new Map(); + this.#props = { name, chainId, formatter, plugins }; + } + toJSON() { + return { name: this.name, chainId: this.chainId }; + } + get name() { return getStore(this.#props, "name"); } + set name(value) { setStore(this.#props, "name", value); } + get chainId() { return getStore(this.#props, "chainId"); } + set chainId(value) { setStore(this.#props, "chainId", logger.getBigInt(value, "chainId")); } + get formatter() { return getStore(this.#props, "formatter"); } + set formatter(value) { setStore(this.#props, "formatter", value); } + get plugins() { + return Array.from(this.#props.plugins.values()); + } + attachPlugin(plugin) { + if (this.isFrozen()) { + throw new Error("frozen"); + } + if (this.#props.plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#props.plugins.set(plugin.name, plugin.validate(this)); + return this; + } + getPlugin(name) { + return (this.#props.plugins.get(name)) || null; + } + // Gets a list of Plugins which match basename, ignoring any fragment + getPlugins(basename) { + return (this.plugins.filter((p) => (p.name.split("#")[0] === basename))); + } + clone() { + const clone = new Network(this.name, this.chainId, this.formatter); + this.plugins.forEach((plugin) => { + clone.attachPlugin(plugin.clone()); + }); + return clone; + } + freeze() { + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + computeIntrinsicGas(tx) { + const costs = this.getPlugin("org.ethers.gas-cost") || (new GasCostPlugin()); + let gas = costs.txBase; + if (tx.to == null) { + gas += costs.txCreate; + } + if (tx.data) { + for (let i = 2; i < tx.data.length; i += 2) { + if (tx.data.substring(i, i + 2) === "00") { + gas += costs.txDataZero; + } + else { + gas += costs.txDataNonzero; + } + } + } + if (tx.accessList) { + const accessList = this.formatter.accessList(tx.accessList); + for (const addr in accessList) { + gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; + } + } + return gas; + } + static from(network) { + // Default network + if (network == null) { + return Network.from("homestead"); + } + // Canonical name or chain ID + if (typeof (network) === "number") { + network = BigInt(network); + } + if (typeof (network) === "string" || typeof (network) === "bigint") { + const networkFunc = Networks.get(network); + if (networkFunc) { + return networkFunc(); + } + if (typeof (network) === "bigint") { + return new Network("unknown", network); + } + logger.throwArgumentError("unknown network", "network", network); + } + // Clonable with network-like abilities + if (typeof (network.clone) === "function") { + const clone = network.clone(); + //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") { + //} + return clone; + } + // Networkish + if (typeof (network) === "object") { + if (typeof (network.name) !== "string" || typeof (network.chainId) !== "number") { + logger.throwArgumentError("invalid network object name or chainId", "network", network); + } + const custom = new Network((network.name), (network.chainId)); + if (network.ensAddress || network.ensNetwork != null) { + custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork)); + } + //if ((network).layerOneConnection) { + // custom.attachPlugin(new LayerOneConnectionPlugin((network).layerOneConnection)); + //} + return custom; + } + return logger.throwArgumentError("invalid network", "network", network); + } + static register(nameOrChainId, networkFunc) { + if (typeof (nameOrChainId) === "number") { + nameOrChainId = BigInt(nameOrChainId); + } + const existing = Networks.get(nameOrChainId); + if (existing) { + logger.throwArgumentError(`conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); + } + Networks.set(nameOrChainId, networkFunc); + } +} +//# sourceMappingURL=network.js.map \ No newline at end of file diff --git a/lib.esm/providers/network.js.map b/lib.esm/providers/network.js.map new file mode 100644 index 000000000..b132c10a5 --- /dev/null +++ b/lib.esm/providers/network.js.map @@ -0,0 +1 @@ +{"version":3,"file":"network.js","sourceRoot":"","sources":["../../src.ts/providers/network.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AA0BhE;;;;;;;;;;;;;;;;EAgBE;AAEF;;;;;;;;;;;;;EAaE;AAEF,uEAAuE;AACvE,sEAAsE;AACtE,uEAAuE;AACvE,uDAAuD;AACvD;;;;;;;;;;;;;;EAcE;AAEF,MAAM,QAAQ,GAAwC,IAAI,GAAG,EAAE,CAAC;AAEhE,MAAM,gBAAgB,GAAG,IAAI,SAAS,EAAE,CAAC;AAEzC,MAAM,OAAO,OAAO;IAChB,MAAM,CAOJ;IAEF,YAAY,IAAY,EAAE,QAAsB,EAAE,SAAqB;QACnE,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC3C,IAAI,SAAS,IAAI,IAAI,EAAE;YAAE,SAAS,GAAG,gBAAgB,CAAC;SAAE;QACxD,MAAM,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,EAAE,IAA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AO,MAAM,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,aAAuC,EAAE,WAA0B;QAC/E,IAAI,OAAM,CAAC,aAAa,CAAC,KAAK,QAAQ,EAAE;YAAE,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;SAAE;QAClF,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC7C,IAAI,QAAQ,EAAE;YACV,MAAM,CAAC,kBAAkB,CAAC,2BAA4B,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAE,EAAE,EAAE,eAAe,EAAE,aAAa,CAAC,CAAC;SAC3H;QACD,QAAQ,CAAC,GAAG,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;IAC7C,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/pagination.js b/lib.esm/providers/pagination.js new file mode 100644 index 000000000..dad94f2fa --- /dev/null +++ b/lib.esm/providers/pagination.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=pagination.js.map \ No newline at end of file diff --git a/lib.esm/providers/pagination.js.map b/lib.esm/providers/pagination.js.map new file mode 100644 index 000000000..d08e925cb --- /dev/null +++ b/lib.esm/providers/pagination.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pagination.js","sourceRoot":"","sources":["../../src.ts/providers/pagination.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib.esm/providers/plugins-network.js b/lib.esm/providers/plugins-network.js new file mode 100644 index 000000000..abd0e5939 --- /dev/null +++ b/lib.esm/providers/plugins-network.js @@ -0,0 +1,105 @@ +import { defineProperties } from "../utils/properties.js"; +import { logger } from "../utils/logger.js"; +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +export class NetworkPlugin { + name; + constructor(name) { + defineProperties(this, { name }); + } + clone() { + return new NetworkPlugin(this.name); + } + validate(network) { + return this; + } +} +export class GasCostPlugin extends NetworkPlugin { + effectiveBlock; + txBase; + txCreate; + txDataZero; + txDataNonzero; + txAccessListStorageKey; + txAccessListAddress; + constructor(effectiveBlock = 0, costs) { + super(`org.ethers.network-plugins.gas-cost#${(effectiveBlock || 0)}`); + const props = { effectiveBlock }; + function set(name, nullish) { + let value = (costs || {})[name]; + if (value == null) { + value = nullish; + } + if (typeof (value) !== "number") { + logger.throwArgumentError(`invalud value for ${name}`, "costs", costs); + } + props[name] = value; + } + set("txBase", 21000); + set("txCreate", 32000); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + defineProperties(this, props); + } + clone() { + return new GasCostPlugin(this.effectiveBlock, this); + } +} +// Networks shoudl use this plugin to specify the contract address +// and network necessary to resolve ENS names. +export class EnsPlugin extends NetworkPlugin { + // The ENS contract address + address; + // The network ID that the ENS contract lives on + targetNetwork; + constructor(address, targetNetwork) { + super("org.ethers.network-plugins.ens"); + defineProperties(this, { + address: (address || EnsAddress), + targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork) + }); + } + clone() { + return new EnsPlugin(this.address, this.targetNetwork); + } + validate(network) { + network.formatter.address(this.address); + return this; + } +} +/* +export class MaxPriorityFeePlugin extends NetworkPlugin { + readonly priorityFee!: bigint; + + constructor(priorityFee: BigNumberish) { + super("org.ethers.plugins.max-priority-fee"); + defineProperties(this, { + priorityFee: logger.getBigInt(priorityFee) + }); + } + + async getPriorityFee(provider: Provider): Promise { + return this.priorityFee; + } + + clone(): MaxPriorityFeePlugin { + return new MaxPriorityFeePlugin(this.priorityFee); + } +} +*/ +export class FeeDataNetworkPlugin extends NetworkPlugin { + #feeDataFunc; + get feeDataFunc() { return this.#feeDataFunc; } + constructor(feeDataFunc) { + super("org.ethers.network-plugins.fee-data"); + this.#feeDataFunc = feeDataFunc; + } + async getFeeData(provider) { + return await this.#feeDataFunc(provider); + } + clone() { + return new FeeDataNetworkPlugin(this.#feeDataFunc); + } +} +//# sourceMappingURL=plugins-network.js.map \ No newline at end of file diff --git a/lib.esm/providers/plugins-network.js.map b/lib.esm/providers/plugins-network.js.map new file mode 100644 index 000000000..c3adac267 --- /dev/null +++ b/lib.esm/providers/plugins-network.js.map @@ -0,0 +1 @@ +{"version":3,"file":"plugins-network.js","sourceRoot":"","sources":["../../src.ts/providers/plugins-network.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAQ5C,MAAM,UAAU,GAAG,4CAA4C,CAAC;AAEhE,MAAM,OAAO,aAAa;IACb,IAAI,CAAU;IAEvB,YAAY,IAAY;QACpB,gBAAgB,CAAgB,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,CAAC;IAED,KAAK;QACD,OAAO,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;IAED,QAAQ,CAAC,OAAgB;QACrB,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AAcD,MAAM,OAAO,aAAc,SAAQ,aAAa;IACnC,cAAc,CAAU;IAExB,MAAM,CAAU;IAChB,QAAQ,CAAU;IAClB,UAAU,CAAU;IACpB,aAAa,CAAU;IACvB,sBAAsB,CAAU;IAChC,mBAAmB,CAAU;IAEtC,YAAY,iBAAyB,CAAC,EAAE,KAAyB;QAC7D,KAAK,CAAC,uCAAwC,CAAC,cAAc,IAAI,CAAC,CAAE,EAAE,CAAC,CAAC;QAExE,MAAM,KAAK,GAA2B,EAAE,cAAc,EAAE,CAAC;QACzD,SAAS,GAAG,CAAC,IAA6B,EAAE,OAAe;YACvD,IAAI,KAAK,GAAG,CAAC,KAAK,IAAI,EAAG,CAAC,CAAC,IAAI,CAAC,CAAC;YACjC,IAAI,KAAK,IAAI,IAAI,EAAE;gBAAE,KAAK,GAAG,OAAO,CAAC;aAAE;YACvC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AAO,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACxC,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AACD;;;;;;;;;;;;;;;;;;;EAmBE;AACF,MAAM,OAAO,oBAAqB,SAAQ,aAAa;IAC1C,YAAY,CAA2C;IAEhE,IAAI,WAAW,KAA+C,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;IAEzF,YAAY,WAAqD;QAC7D,KAAK,CAAC,qCAAqC,CAAC,CAAC;QAC7C,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IACpC,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,QAAkB;QAC/B,OAAO,MAAM,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK;QACD,OAAO,IAAI,oBAAoB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-alchemy.js b/lib.esm/providers/provider-alchemy.js new file mode 100644 index 000000000..c96347c9d --- /dev/null +++ b/lib.esm/providers/provider-alchemy.js @@ -0,0 +1,97 @@ +import { defineProperties } from "../utils/properties.js"; +import { FetchRequest } from "../utils/fetch.js"; +import { showThrottleMessage } from "./community.js"; +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; +function getHost(name) { + switch (name) { + case "homestead": + return "eth-mainnet.alchemyapi.io"; + case "ropsten": + return "eth-ropsten.alchemyapi.io"; + case "rinkeby": + return "eth-rinkeby.alchemyapi.io"; + case "goerli": + return "eth-goerli.alchemyapi.io"; + case "kovan": + return "eth-kovan.alchemyapi.io"; + case "matic": + return "polygon-mainnet.g.alchemy.com"; + case "maticmum": + return "polygon-mumbai.g.alchemy.com"; + case "arbitrum": + return "arb-mainnet.g.alchemy.com"; + case "arbitrum-rinkeby": + return "arb-rinkeby.g.alchemy.com"; + case "optimism": + return "opt-mainnet.g.alchemy.com"; + case "optimism-kovan": + return "opt-kovan.g.alchemy.com"; + } + return logger.throwArgumentError("unsupported network", "network", name); +} +export class AlchemyProvider extends JsonRpcProvider { + apiKey; + constructor(_network = "homestead", apiKey) { + const network = Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = AlchemyProvider.getRequest(network, apiKey); + super(request, network, { staticNetwork: network }); + defineProperties(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AlchemyProvider(chainId, this.apiKey); + } + catch (error) { } + return super._getProvider(chainId); + } + async _perform(req) { + // https://docs.alchemy.com/reference/trace-transaction + if (req.method === "getTransactionResult") { + const trace = await this.send("trace_transaction", [req.hash]); + if (trace == null) { + return null; + } + let data; + let error = false; + try { + data = trace[0].result.output; + error = (trace[0].error === "Reverted"); + } + catch (error) { } + if (data) { + if (error) { + logger.throwError("an error occurred during transaction executions", "CALL_EXCEPTION", { + data + }); + } + return data; + } + return logger.throwError("could not parse trace result", "BAD_DATA", { value: trace }); + } + return await super._perform(req); + } + isCommunityResource() { + return (this.apiKey === defaultApiKey); + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = new FetchRequest(`https:/\/${getHost(network.name)}/v2/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request, response, attempt) => { + showThrottleMessage("alchemy"); + return true; + }; + } + return request; + } +} +//# sourceMappingURL=provider-alchemy.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-alchemy.js.map b/lib.esm/providers/provider-alchemy.js.map new file mode 100644 index 000000000..b3bd1cd8c --- /dev/null +++ b/lib.esm/providers/provider-alchemy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-alchemy.js","sourceRoot":"","sources":["../../src.ts/providers/provider-alchemy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBA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;SAC1F;QAED,OAAO,MAAM,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACrC,CAAC;IAED,mBAAmB;QACf,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC,CAAC;IAC3C,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,OAAgB,EAAE,MAAe;QAC/C,IAAI,MAAM,IAAI,IAAI,EAAE;YAAE,MAAM,GAAG,aAAa,CAAC;SAAE;QAE/C,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,YAAa,OAAO,CAAC,OAAO,CAAC,IAAI,CAAE,OAAQ,MAAO,EAAE,CAAC,CAAC;QACvF,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;QAEzB,IAAI,MAAM,KAAK,aAAa,EAAE;YAC1B,OAAO,CAAC,SAAS,GAAG,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;gBACrD,mBAAmB,CAAC,SAAS,CAAC,CAAC;gBAC/B,OAAO,IAAI,CAAC;YAChB,CAAC,CAAA;SACJ;QAED,OAAO,OAAO,CAAC;IACnB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-ankr.js b/lib.esm/providers/provider-ankr.js new file mode 100644 index 000000000..60f34420c --- /dev/null +++ b/lib.esm/providers/provider-ankr.js @@ -0,0 +1,63 @@ +import { defineProperties } from "../utils/properties.js"; +import { FetchRequest } from "../utils/fetch.js"; +import { showThrottleMessage } from "./community.js"; +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +const defaultApiKey = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; +function getHost(name) { + switch (name) { + case "homestead": + return "rpc.ankr.com/eth"; + case "ropsten": + return "rpc.ankr.com/eth_ropsten"; + case "rinkeby": + return "rpc.ankr.com/eth_rinkeby"; + case "goerli": + return "rpc.ankr.com/eth_goerli"; + case "matic": + return "rpc.ankr.com/polygon"; + case "arbitrum": + return "rpc.ankr.com/arbitrum"; + } + return logger.throwArgumentError("unsupported network", "network", name); +} +export class AnkrProvider extends JsonRpcProvider { + apiKey; + constructor(_network = "homestead", apiKey) { + const network = Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey; + } + // Ankr does not support filterId, so we force polling + const options = { polling: true, staticNetwork: network }; + const request = AnkrProvider.getRequest(network, apiKey); + super(request, network, options); + defineProperties(this, { apiKey }); + } + _getProvider(chainId) { + try { + return new AnkrProvider(chainId, this.apiKey); + } + catch (error) { } + return super._getProvider(chainId); + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = new FetchRequest(`https:/\/${getHost(network.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request, response, attempt) => { + showThrottleMessage("AnkrProvider"); + return true; + }; + } + return request; + } + isCommunityResource() { + return (this.apiKey === defaultApiKey); + } +} +//# sourceMappingURL=provider-ankr.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-ankr.js.map b/lib.esm/providers/provider-ankr.js.map new file mode 100644 index 000000000..e1f2f730b --- /dev/null +++ b/lib.esm/providers/provider-ankr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ankr.js","sourceRoot":"","sources":["../../src.ts/providers/provider-ankr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAMxD,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEzF,SAAS,OAAO,CAAC,IAAY;IACzB,QAA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M,GAAG,aAAa,CAAC;SAAE;QAE/C,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,YAAa,OAAO,CAAC,OAAO,CAAC,IAAI,CAAE,IAAK,MAAO,EAAE,CAAC,CAAC;QACpF,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;QAEzB,IAAI,MAAM,KAAK,aAAa,EAAE;YAC1B,OAAO,CAAC,SAAS,GAAG,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;gBACrD,mBAAmB,CAAC,cAAc,CAAC,CAAC;gBACpC,OAAO,IAAI,CAAC;YAChB,CAAC,CAAC;SACL;QAED,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,mBAAmB;QACf,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC,CAAC;IAC3C,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-cloudflare.js b/lib.esm/providers/provider-cloudflare.js new file mode 100644 index 000000000..bd78f1686 --- /dev/null +++ b/lib.esm/providers/provider-cloudflare.js @@ -0,0 +1,13 @@ +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +export class CloudflareProvider extends JsonRpcProvider { + constructor(_network = "homestead") { + const network = Network.from(_network); + if (network.name !== "homestead") { + return logger.throwArgumentError("unsupported network", "network", _network); + } + super("https:/\/cloudflare-eth.com/", network, { staticNetwork: network }); + } +} +//# sourceMappingURL=provider-cloudflare.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-cloudflare.js.map b/lib.esm/providers/provider-cloudflare.js.map new file mode 100644 index 000000000..930633393 --- /dev/null +++ b/lib.esm/providers/provider-cloudflare.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-cloudflare.js","sourceRoot":"","sources":["../../src.ts/providers/provider-cloudflare.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAKxD,MAAM,OAAO,kBAAmB,SAAQ,eAAe;IACnD,YAAY,WAAuB,WAAW;QAC1C,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACvC,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE;YAC9B,OAAO,MAAM,CAAC,kBAAkB,CAAC,qBAAqB,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;SAChF;QACD,KAAK,CAAC,8BAA8B,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-etherscan.js b/lib.esm/providers/provider-etherscan.js new file mode 100644 index 000000000..a83b57244 --- /dev/null +++ b/lib.esm/providers/provider-etherscan.js @@ -0,0 +1,463 @@ +import { hexlify, isHexString } from "../utils/data.js"; +import { toQuantity } from "../utils/maths.js"; +import { isError } from "../utils/errors.js"; +import { defineProperties } from "../utils/properties.js"; +import { toUtf8String } from "../utils/utf8.js"; +import { FetchRequest } from "../utils/fetch.js"; +if (false) { + console.log(isHexString, isError); +} // @TODO +import { AbstractProvider } from "./abstract-provider.js"; +import { Network } from "./network.js"; +import { NetworkPlugin } from "./plugins-network.js"; +import { logger } from "../utils/logger.js"; +const defaultApiKey = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB"; +const EtherscanPluginId = "org.ethers.plugins.etherscan"; +export class EtherscanPlugin extends NetworkPlugin { + baseUrl; + communityApiKey; + constructor(baseUrl, communityApiKey) { + super(EtherscanPluginId); + //if (communityApiKey == null) { communityApiKey = null; } + defineProperties(this, { baseUrl, communityApiKey }); + } + clone() { + return new EtherscanPlugin(this.baseUrl, this.communityApiKey); + } +} +export class EtherscanProvider extends AbstractProvider { + network; + apiKey; + constructor(_network, apiKey) { + super(); + const network = Network.from(_network); + if (apiKey == null) { + const plugin = network.getPlugin(EtherscanPluginId); + if (plugin) { + apiKey = plugin.communityApiKey; + } + else { + apiKey = defaultApiKey; + } + } + defineProperties(this, { apiKey, network }); + // Test that the network is supported by Etherscan + this.getBaseUrl(); + } + getBaseUrl() { + const plugin = this.network.getPlugin(EtherscanPluginId); + if (plugin) { + return plugin.baseUrl; + } + switch (this.network.name) { + case "homestead": + return "https:/\/api.etherscan.io"; + case "ropsten": + return "https:/\/api-ropsten.etherscan.io"; + case "rinkeby": + return "https:/\/api-rinkeby.etherscan.io"; + case "kovan": + return "https:/\/api-kovan.etherscan.io"; + case "goerli": + return "https:/\/api-goerli.etherscan.io"; + default: + } + return logger.throwArgumentError("unsupported network", "network", this.network); + } + getUrl(module, params) { + const query = Object.keys(params).reduce((accum, key) => { + const value = params[key]; + if (value != null) { + accum += `&${key}=${value}`; + } + return accum; + }, ""); + const apiKey = ((this.apiKey) ? `&apikey=${this.apiKey}` : ""); + return `${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`; + } + getPostUrl() { + return `${this.getBaseUrl()}/api`; + } + getPostData(module, params) { + params.module = module; + params.apikey = this.apiKey; + return params; + } + async detectNetwork() { + return this.network; + } + async fetch(module, params, post) { + const url = (post ? this.getPostUrl() : this.getUrl(module, params)); + const payload = (post ? this.getPostData(module, params) : null); + /* + this.emit("debug", { + action: "request", + request: url, + provider: this + }); + */ + const request = new FetchRequest(url); + request.processFunc = async (request, response) => { + const result = response.hasBody() ? JSON.parse(toUtf8String(response.body)) : {}; + const throttle = ((typeof (result.result) === "string") ? result.result : "").toLowerCase().indexOf("rate limit") >= 0; + if (module === "proxy") { + // This JSON response indicates we are being throttled + if (result && result.status == 0 && result.message == "NOTOK" && throttle) { + response.throwThrottleError(result.result); + } + } + else { + if (throttle) { + response.throwThrottleError(result.result); + } + } + return response; + }; + // @TODO: + //throttleSlotInterval: 1000, + if (payload) { + request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); + request.body = Object.keys(payload).map((k) => `${k}=${payload[k]}`).join("&"); + } + const response = await request.send(); + response.assertOk(); + if (!response.hasBody()) { + throw new Error(); + } + /* + this.emit("debug", { + action: "response", + request: url, + response: deepCopy(result), + provider: this + }); + */ + const result = JSON.parse(toUtf8String(response.body)); + if (module === "proxy") { + if (result.jsonrpc != "2.0") { + // @TODO: not any + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + throw error; + } + if (result.error) { + // @TODO: not any + const error = new Error(result.error.message || "unknown error"); + if (result.error.code) { + error.code = result.error.code; + } + if (result.error.data) { + error.data = result.error.data; + } + throw error; + } + return result.result; + } + else { + // getLogs, getHistory have weird success responses + if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { + return result.result; + } + if (result.status != 1 || result.message != "OK") { + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + // if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) { + // error.throttleRetry = true; + // } + throw error; + } + return result.result; + } + } + // The transaction has already been sanitized by the calls in Provider + _getTransactionPostData(transaction) { + const result = {}; + for (let key in transaction) { + if (transaction[key] == null) { + continue; + } + let value = transaction[key]; + if (key === "type" && value === 0) { + continue; + } + // Quantity-types require no leading zero, unless 0 + if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) { + value = toQuantity(hexlify(value)); + } + else if (key === "accessList") { + value = "[" + this.network.formatter.accessList(value).map((set) => { + return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; + }).join(",") + "]"; + } + else { + value = hexlify(value); + } + result[key] = value; + } + return result; + } + _checkError(req, error, transaction) { + /* + let body = ""; + if (isError(error, Logger.Errors.SERVER_ERROR) && error.response && error.response.hasBody()) { + body = toUtf8String(error.response.body); + } + console.log(body); + + // Undo the "convenience" some nodes are attempting to prevent backwards + // incompatibility; maybe for v6 consider forwarding reverts as errors + if (method === "call" && body) { + + // Etherscan keeps changing their string + if (body.match(/reverted/i) || body.match(/VM execution error/i)) { + + // Etherscan prefixes the data like "Reverted 0x1234" + let data = e.data; + if (data) { data = "0x" + data.replace(/^.*0x/i, ""); } + if (!isHexString(data)) { data = "0x"; } + + logger.throwError("call exception", Logger.Errors.CALL_EXCEPTION, { + error, data + }); + } + } + + // Get the message from any nested error structure + let message = error.message; + if (isError(error, Logger.Errors.SERVER_ERROR)) { + if (error.error && typeof(error.error.message) === "string") { + message = error.error.message; + } else if (typeof(error.body) === "string") { + message = error.body; + } else if (typeof(error.responseText) === "string") { + message = error.responseText; + } + } + message = (message || "").toLowerCase(); + + // "Insufficient funds. The account you tried to send transaction from + // does not have enough funds. Required 21464000000000 and got: 0" + if (message.match(/insufficient funds/)) { + logger.throwError("insufficient funds for intrinsic transaction cost", Logger.Errors.INSUFFICIENT_FUNDS, { + error, transaction, info: { method } + }); + } + + // "Transaction with the same hash was already imported." + if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { + logger.throwError("nonce has already been used", Logger.Errors.NONCE_EXPIRED, { + error, transaction, info: { method } + }); + } + + // "Transaction gas price is too low. There is another transaction with + // same nonce in the queue. Try increasing the gas price or incrementing the nonce." + if (message.match(/another transaction with same nonce/)) { + logger.throwError("replacement fee too low", Logger.Errors.REPLACEMENT_UNDERPRICED, { + error, transaction, info: { method } + }); + } + + if (message.match(/execution failed due to an exception|execution reverted/)) { + logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.Errors.UNPREDICTABLE_GAS_LIMIT, { + error, transaction, info: { method } + }); + } + */ + throw error; + } + async _detectNetwork() { + return this.network; + } + async _perform(req) { + switch (req.method) { + case "chainId": + return this.network.chainId; + case "getBlockNumber": + return this.fetch("proxy", { action: "eth_blockNumber" }); + case "getGasPrice": + return this.fetch("proxy", { action: "eth_gasPrice" }); + case "getBalance": + // Returns base-10 result + return this.fetch("account", { + action: "balance", + address: req.address, + tag: req.blockTag + }); + case "getTransactionCount": + return this.fetch("proxy", { + action: "eth_getTransactionCount", + address: req.address, + tag: req.blockTag + }); + case "getCode": + return this.fetch("proxy", { + action: "eth_getCode", + address: req.address, + tag: req.blockTag + }); + case "getStorageAt": + return this.fetch("proxy", { + action: "eth_getStorageAt", + address: req.address, + position: req.position, + tag: req.blockTag + }); + case "broadcastTransaction": + return this.fetch("proxy", { + action: "eth_sendRawTransaction", + hex: req.signedTransaction + }, true).catch((error) => { + return this._checkError(req, error, req.signedTransaction); + }); + case "getBlock": + if ("blockTag" in req) { + return this.fetch("proxy", { + action: "eth_getBlockByNumber", + tag: req.blockTag, + boolean: (req.includeTransactions ? "true" : "false") + }); + } + return logger.throwError("getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", { + operation: "getBlock(blockHash)" + }); + case "getTransaction": + return this.fetch("proxy", { + action: "eth_getTransactionByHash", + txhash: req.hash + }); + case "getTransactionReceipt": + return this.fetch("proxy", { + action: "eth_getTransactionReceipt", + txhash: req.hash + }); + case "call": { + if (req.blockTag !== "latest") { + throw new Error("EtherscanProvider does not support blockTag for call"); + } + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_call"; + try { + return await this.fetch("proxy", postData, true); + } + catch (error) { + return this._checkError(req, error, req.transaction); + } + } + case "estimateGas": { + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_estimateGas"; + try { + return await this.fetch("proxy", postData, true); + } + catch (error) { + return this._checkError(req, error, req.transaction); + } + } + /* + case "getLogs": { + // Needs to complain if more than one address is passed in + const args: Record = { action: "getLogs" } + + if (params.filter.fromBlock) { + args.fromBlock = checkLogTag(params.filter.fromBlock); + } + + if (params.filter.toBlock) { + args.toBlock = checkLogTag(params.filter.toBlock); + } + + if (params.filter.address) { + args.address = params.filter.address; + } + + // @TODO: We can handle slightly more complicated logs using the logs API + if (params.filter.topics && params.filter.topics.length > 0) { + if (params.filter.topics.length > 1) { + logger.throwError("unsupported topic count", Logger.Errors.UNSUPPORTED_OPERATION, { topics: params.filter.topics }); + } + if (params.filter.topics.length === 1) { + const topic0 = params.filter.topics[0]; + if (typeof(topic0) !== "string" || topic0.length !== 66) { + logger.throwError("unsupported topic format", Logger.Errors.UNSUPPORTED_OPERATION, { topic0: topic0 }); + } + args.topic0 = topic0; + } + } + + const logs: Array = await this.fetch("logs", args); + + // Cache txHash => blockHash + let blocks: { [tag: string]: string } = {}; + + // Add any missing blockHash to the logs + for (let i = 0; i < logs.length; i++) { + const log = logs[i]; + if (log.blockHash != null) { continue; } + if (blocks[log.blockNumber] == null) { + const block = await this.getBlock(log.blockNumber); + if (block) { + blocks[log.blockNumber] = block.hash; + } + } + + log.blockHash = blocks[log.blockNumber]; + } + + return logs; + } + */ + default: + break; + } + return super._perform(req); + } + async getNetwork() { + return this.network; + } + async getEtherPrice() { + if (this.network.name !== "homestead") { + return 0.0; + } + return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd); + } + isCommunityResource() { + const plugin = this.network.getPlugin(EtherscanPluginId); + if (plugin) { + return (plugin.communityApiKey === this.apiKey); + } + return (defaultApiKey === this.apiKey); + } +} +/* +(async function() { + const provider = new EtherscanProvider(); + console.log(provider); + console.log(await provider.getBlockNumber()); + / * + provider.on("block", (b) => { + console.log("BB", b); + }); + console.log(await provider.getTransactionReceipt("0xa5ded92f548e9f362192f9ab7e5b3fbc9b5a919a868e29247f177d49ce38de6e")); + + provider.once("0xa5ded92f548e9f362192f9ab7e5b3fbc9b5a919a868e29247f177d49ce38de6e", (tx) => { + console.log("TT", tx); + }); + * / + try { + console.log(await provider.getBlock(100)); + } catch (error) { + console.log(error); + } + + try { + console.log(await provider.getBlock(13821768)); + } catch (error) { + console.log(error); + } + +})(); +*/ +//# sourceMappingURL=provider-etherscan.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-etherscan.js.map b/lib.esm/providers/provider-etherscan.js.map new file mode 100644 index 000000000..bf27ada81 --- /dev/null +++ b/lib.esm/providers/provider-etherscan.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-etherscan.js","source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ED,OAAO,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,KAAK,CAAC,aAAa;QACf,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE;YAAE,OAAO,GAAG,CAAC;SAAE;QACtD,OAAO,UAAU,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAClF,CAAC;IAED,mBAAmB;QACf,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAkB,iBAAiB,CAAC,CAAC;QAC1E,IAAI,MAAM,EAAE;YAAE,OAAO,CAAC,MAAM,CAAC,eAAe,KAAK,IAAI,CAAC,MAAM,CAAC,CAAC;SAAE;QAEhE,OAAO,CAAC,aAAa,KAAK,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;CACJ;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4BE"} \ 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 000000000..b5332979c --- /dev/null +++ b/lib.esm/providers/provider-fallback.js @@ -0,0 +1,413 @@ +import { hexlify } from "../utils/data.js"; +import { AbstractProvider } from "./abstract-provider.js"; +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +//const BN_0 = BigInt("0"); +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(); } +; +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 +}; +async function waitForSync(config, blockNumber) { + while (config.blockNumber < 0 || config.blockNumber < blockNumber) { + if (!config._updateNumber) { + config._updateNumber = (async () => { + const blockNumber = await config.provider.getBlockNumber(); + if (blockNumber > config.blockNumber) { + config.blockNumber = blockNumber; + } + config._updateNumber = null; + })(); + } + await config._updateNumber; + config.outOfSync++; + } +} +// Normalizes a result to a string that can be used to compare against +// other results using normal string equality +function normalize(network, value, req) { + switch (req.method) { + case "chainId": + return logger.getBigInt(value).toString(); + case "getBlockNumber": + return logger.getNumber(value).toString(); + case "getGasPrice": + return logger.getBigInt(value).toString(); + case "getBalance": + return logger.getBigInt(value).toString(); + case "getTransactionCount": + return logger.getNumber(value).toString(); + case "getCode": + return hexlify(value); + case "getStorageAt": + return hexlify(value); + case "getBlock": + if (req.includeTransactions) { + return JSON.stringify(network.formatter.blockWithTransactions(value)); + } + return JSON.stringify(network.formatter.block(value)); + case "getTransaction": + return JSON.stringify(network.formatter.transactionResponse(value)); + case "getTransactionReceipt": + return JSON.stringify(network.formatter.receipt(value)); + case "call": + return hexlify(value); + case "estimateGas": + return logger.getBigInt(value).toString(); + case "getLogs": + return JSON.stringify(value.map((v) => network.formatter.log(v))); + } + return logger.throwError("unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${JSON.stringify(req.method)})` + }); +} +// This strategy picks the highest wieght result, as long as the weight is +// equal to or greater than quorum +function checkQuorum(quorum, results) { + const tally = new Map(); + for (const { result, normal, weight } of results) { + const t = tally.get(normal) || { result, weight: 0 }; + t.weight += weight; + tally.set(normal, t); + } + let bestWeight = 0; + let bestResult = undefined; + for (const { weight, result } of tally.values()) { + if (weight >= quorum && weight > bestWeight) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +/* +function getMean(results: Array): bigint { + const total = results.reduce((a, r) => (a + BigInt(r.result)), BN_0); + return total / BigInt(results.length); +} +*/ +function getMedian(results) { + // Get the sorted values + const values = results.map((r) => BigInt(r.result)); + values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0)); + const mid = 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 getFuzzyMode(quorum, results) { + if (quorum === 1) { + return logger.getNumber(getMedian(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, result } of results) { + const r = logger.getNumber(result); + 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; +} +export class FallbackProvider extends AbstractProvider { + //readonly providerConfigs!: ReadonlyArray>>; + quorum; + eventQuorum; + eventWorkers; + #configs; + #height; + #initialSyncPromise; + constructor(providers, network) { + super(network); + 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; + this.quorum = 2; //Math.ceil(providers.length / 2); + this.eventQuorum = 1; + this.eventWorkers = 1; + if (this.quorum > this.#configs.reduce((a, c) => (a + c.weight), 0)) { + logger.throwArgumentError("quorum exceed provider wieght", "quorum", this.quorum); + } + } + // @TOOD: Copy these and only return public values + get providerConfigs() { + return this.#configs.slice(); + } + async _detectNetwork() { + return Network.from(logger.getBigInt(await this._perform({ method: "chainId" }))).freeze(); + } + // @TODO: Add support to select providers to be the event subscriber + //_getSubscriber(sub: Subscription): Subscriber { + // throw new Error("@TODO"); + //} + // Grab the next (random) config that is not already part of configs + #getNextConfig(configs) { + // Shuffle the states, sorted by priority + const allConfigs = this.#configs.slice(); + shuffle(allConfigs); + allConfigs.sort((a, b) => (b.priority - a.priority)); + for (const config of allConfigs) { + if (configs.indexOf(config) === -1) { + return config; + } + } + return null; + } + // Adds a new runner (if available) to running. + #addRunner(running, req) { + const config = this.#getNextConfig(Array.from(running).map((r) => r.config)); + if (config == null) { + return null; + } + const result = {}; + const runner = { + config, result, didBump: false, done: false, + perform: null, staller: null + }; + const now = getTime(); + runner.perform = (async () => { + try { + config.requests++; + result.result = await config.provider._perform(req); + } + catch (error) { + config.errorResponses++; + result.error = error; + } + if (runner.done) { + config.lateResponses++; + } + const dt = (getTime() - now); + config._totalTime += dt; + config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt; + runner.perform = null; + })(); + 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(waitForSync(config, 0)); + promises.push((async () => { + 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) { + const network = (config._network); + if (chainId == null) { + chainId = network.chainId; + } + else if (network.chainId !== chainId) { + logger.throwError("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 ("result" in runner.result) { + const result = runner.result.result; + results.push({ + result, + normal: normalize((runner.config._network), result, req), + 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) { + const height = Math.ceil(logger.getNumber(getMedian(this.#configs.map((c) => ({ + result: c.blockNumber, + normal: logger.getNumber(c.blockNumber).toString(), + weight: c.weight + }))), "%internal")); + this.#height = height; + } + const mode = getFuzzyMode(this.quorum, results); + if (mode === undefined) { + return undefined; + } + if (mode > this.#height) { + this.#height = mode; + } + return this.#height; + } + case "getGasPrice": + case "estimateGas": + return getMedian(results); + case "getBlock": + // Pending blocks are mempool dependant and already + // quite untrustworthy + if ("blockTag" in req && req.blockTag === "pending") { + return results[0].result; + } + return checkQuorum(this.quorum, results); + case "chainId": + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorageAt": + case "getTransaction": + case "getTransactionReceipt": + case "getLogs": + return checkQuorum(this.quorum, results); + case "call": + // @TODO: Check errors + return checkQuorum(this.quorum, results); + case "broadcastTransaction": + throw new Error("TODO"); + } + return logger.throwError("unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${JSON.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 = []; + //const results: Array = [ ]; + //const errors: Array = [ ]; + let newRunners = 0; + for (const runner of running) { + // @TODO: use runner.perfom != null + /* + if ("result" in runner.result) { + results.push(runner.result.result); + } else if ("error" in runner.result) { + errors.push(runner.result.error); + } +*/ + // 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 for quorum + /* + console.log({ results, errors } ); + if (results.length >= this.quorum) { + return results[0]; + } + + if (errors.length >= this.quorum) { + return errors[0]; + } + */ + 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); + } + if (interesting.length === 0) { + throw new Error("quorum not met"); + // return logger.throwError("failed to meet quorum", "", { + // }); + } + // Wait for someone to either complete its perform or trigger a stall + await Promise.race(interesting); + return await this.#waitForQuorum(running, req); + } + async _perform(req) { + await this.#initialSync(); + // Bootstrap enough to meet quorum + const running = new Set(); + for (let i = 0; i < this.quorum; i++) { + this.#addRunner(running, req); + } + const result = this.#waitForQuorum(running, req); + for (const runner of running) { + runner.done = true; + } + return result; + } +} +//# 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 000000000..ae9c1327e --- /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":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAOtC,2BAA2B;AAC3B,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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AE,EAAE;YAClC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;SACjC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QACjD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;YAAE,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;SAAE;QACrD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-infura.js b/lib.esm/providers/provider-infura.js new file mode 100644 index 000000000..9d4b3aa82 --- /dev/null +++ b/lib.esm/providers/provider-infura.js @@ -0,0 +1,81 @@ +import { defineProperties } from "../utils/properties.js"; +import { FetchRequest } from "../utils/fetch.js"; +import { showThrottleMessage } from "./community.js"; +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +const defaultProjectId = "84842078b09946638c03157f83405213"; +function getHost(name) { + switch (name) { + case "homestead": + return "mainnet.infura.io"; + case "ropsten": + return "ropsten.infura.io"; + case "rinkeby": + return "rinkeby.infura.io"; + case "kovan": + return "kovan.infura.io"; + case "goerli": + return "goerli.infura.io"; + case "matic": + return "polygon-mainnet.infura.io"; + case "maticmum": + return "polygon-mumbai.infura.io"; + case "optimism": + return "optimism-mainnet.infura.io"; + case "optimism-kovan": + return "optimism-kovan.infura.io"; + case "arbitrum": + return "arbitrum-mainnet.infura.io"; + case "arbitrum-rinkeby": + return "arbitrum-rinkeby.infura.io"; + } + return logger.throwArgumentError("unsupported network", "network", name); +} +export class InfuraProvider extends JsonRpcProvider { + projectId; + projectSecret; + constructor(_network = "homestead", projectId, projectSecret) { + const network = Network.from(_network); + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = InfuraProvider.getRequest(network, projectId, projectSecret); + super(request, network, { staticNetwork: network }); + defineProperties(this, { projectId, projectSecret }); + } + _getProvider(chainId) { + try { + return new InfuraProvider(chainId, this.projectId, this.projectSecret); + } + catch (error) { } + return super._getProvider(chainId); + } + static getRequest(network, projectId, projectSecret) { + if (projectId == null) { + projectId = defaultProjectId; + } + if (projectSecret == null) { + projectSecret = null; + } + const request = new FetchRequest(`https:/\/${getHost(network.name)}/v3/${projectId}`); + request.allowGzip = true; + if (projectSecret) { + request.setCredentials("", projectSecret); + } + if (projectId === defaultProjectId) { + request.retryFunc = async (request, response, attempt) => { + showThrottleMessage("InfuraProvider"); + return true; + }; + } + return request; + } + isCommunityResource() { + return (this.projectId === defaultProjectId); + } +} +//# sourceMappingURL=provider-infura.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-infura.js.map b/lib.esm/providers/provider-infura.js.map new file mode 100644 index 000000000..14b393a68 --- /dev/null +++ b/lib.esm/providers/provider-infura.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-infura.js","sourceRoot":"","sources":["../../src.ts/providers/provider-infura.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAOxD,MAAM,gBAAgB,GAAG,kCAAkC,CAAC;AAE5D,SAAS,OAAO,CAAC,IAAY;IACzB,QAAO,IAAI,EAAE;QACT,KAAK,WAAW;YACZ,OAAO,mBAAmB,CAAC;QAC/B,KAAK,SAAS;YACV,OAAO,mBAAmB,CAAC;QAC/B,KAAK,SAAS;YACV,OAAO,mBAAmB,CAAC;QAC/B,KAAK,OAAO;YACR,OAAO,iBAAiB,CAAC;QAC7B,KAAK,QAAQ;YACT,OAAO,kBAAkB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AC,UAAU,CAAC,OAAgB,EAAE,SAAyB,EAAE,aAA6B;QACxF,IAAI,SAAS,IAAI,IAAI,EAAE;YAAE,SAAS,GAAG,gBAAgB,CAAC;SAAE;QACxD,IAAI,aAAa,IAAI,IAAI,EAAE;YAAE,aAAa,GAAG,IAAI,CAAC;SAAE;QAEpD,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,YAAa,OAAO,CAAC,OAAO,CAAC,IAAI,CAAE,OAAQ,SAAU,EAAE,CAAC,CAAC;QAC1F,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;QACzB,IAAI,aAAa,EAAE;YAAE,OAAO,CAAC,cAAc,CAAC,EAAE,EAAE,aAAa,CAAC,CAAC;SAAE;QAEjE,IAAI,SAAS,KAAK,gBAAgB,EAAE;YAChC,OAAO,CAAC,SAAS,GAAG,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;gBACrD,mBAAmB,CAAC,gBAAgB,CAAC,CAAC;gBACtC,OAAO,IAAI,CAAC;YAChB,CAAC,CAAC;SACL;QAED,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,mBAAmB;QACf,OAAO,CAAC,IAAI,CAAC,SAAS,KAAK,gBAAgB,CAAC,CAAC;IACjD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-ipcsocket-browser.js b/lib.esm/providers/provider-ipcsocket-browser.js new file mode 100644 index 000000000..d94074ea4 --- /dev/null +++ b/lib.esm/providers/provider-ipcsocket-browser.js @@ -0,0 +1,3 @@ +const IpcSocketProvider = undefined; +export { IpcSocketProvider }; +//# sourceMappingURL=provider-ipcsocket-browser.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-ipcsocket-browser.js.map b/lib.esm/providers/provider-ipcsocket-browser.js.map new file mode 100644 index 000000000..1df6d95ae --- /dev/null +++ b/lib.esm/providers/provider-ipcsocket-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ipcsocket-browser.js","sourceRoot":"","sources":["../../src.ts/providers/provider-ipcsocket-browser.ts"],"names":[],"mappings":"AAAA,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAEpC,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/provider-ipcsocket.js b/lib.esm/providers/provider-ipcsocket.js new file mode 100644 index 000000000..9d43d1119 --- /dev/null +++ b/lib.esm/providers/provider-ipcsocket.js @@ -0,0 +1,86 @@ +import { connect } from "net"; +import { SocketProvider } from "./provider-socket.js"; +// @TODO: Is this sufficient? Is this robust? Will newlines occur between +// all payloads and only between payloads? +function splitBuffer(data) { + const messages = []; + let lastStart = 0; + while (true) { + const nl = data.indexOf(10, lastStart); + if (nl === -1) { + break; + } + messages.push(data.subarray(lastStart, nl).toString().trim()); + lastStart = nl + 1; + } + return { messages, remaining: data.subarray(lastStart) }; +} +export class IpcSocketProvider extends SocketProvider { + #socket; + get socket() { return this.#socket; } + constructor(path, network) { + super(network); + this.#socket = connect(path); + this.socket.on("ready", () => { this._start(); }); + let response = Buffer.alloc(0); + this.socket.on("data", (data) => { + response = Buffer.concat([response, data]); + const { messages, remaining } = splitBuffer(response); + messages.forEach((message) => { + this._processMessage(message); + }); + response = remaining; + }); + this.socket.on("end", () => { + this.emit("close"); + this.socket.destroy(); + this.socket.end(); + }); + } + stop() { + this.socket.destroy(); + this.socket.end(); + } + async _write(message) { + console.log(">>>", message); + this.socket.write(message); + } +} +/* + +import { defineProperties } from "@ethersproject/properties"; + +import { SocketLike, SocketProvider } from "./provider-socket.js"; + +import type { Socket } from "net"; + +export class SocketWrapper implements SocketLike { + #socket: Socket; + + constructor(path: string) { + this.#socket = connect(path); + } + + send(data: string): void { + this.#socket.write(data, () => { }); + } + + addEventListener(event: string, listener: (data: string) => void): void { + //this.#socket.on(event, (value: ) => { + //}); + } + + close(): void { + } +} + +export class IpcProvider extends SocketProvider { + readonly path!: string; + + constructor(path: string) { + super(new SocketWrapper(path)); + defineProperties(this, { path }); + } +} +*/ +//# sourceMappingURL=provider-ipcsocket.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-ipcsocket.js.map b/lib.esm/providers/provider-ipcsocket.js.map new file mode 100644 index 000000000..340b6e4a6 --- /dev/null +++ b/lib.esm/providers/provider-ipcsocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ipcsocket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-ipcsocket.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAC9B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAMtD,yEAAyE;AACzE,0CAA0C;AAC1C,SAAS,WAAW,CAAC,IAAY;IAC7B,MAAM,QAAQ,GAAkB,EAAG,CAAC;IAEpC,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,OAAO,IAAI,EAAE;QACT,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE;YAAE,MAAM;SAAE;QACzB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QAC9D,SAAS,GAAG,EAAE,GAAG,CAAC,CAAC;KACtB;IAED,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;AAC7D,CAAC;AAED,MAAM,OAAO,iBAAkB,SAAQ,cAAc;IACjD,OAAO,CAAS;IAChB,IAAI,MAAM,KAAa,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE7C,YAAY,IAAY,EAAE,OAAoB;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAE7B,IAAI,CAAC,MAA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sonrpc.js b/lib.esm/providers/provider-jsonrpc.js new file mode 100644 index 000000000..0c7cdf350 --- /dev/null +++ b/lib.esm/providers/provider-jsonrpc.js @@ -0,0 +1,687 @@ +// @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 { resolveAddress } from "../address/index.js"; +import { hexlify } from "../utils/data.js"; +import { FetchRequest } from "../utils/fetch.js"; +import { toQuantity } from "../utils/maths.js"; +import { defineProperties } from "../utils/properties.js"; +import { TypedDataEncoder } from "../hash/typed-data.js"; +import { toUtf8Bytes } from "../utils/utf8.js"; +import { accessListify } from "../transaction/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"; +import { logger } from "../utils/logger.js"; +//function copy(value: T): T { +// return JSON.parse(JSON.stringify(value)); +//} +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 getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +function isPollable(value) { + return (value && typeof (value.pollingInterval) === "number"); +} +const defaultOptions = { + polling: false, + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: (1 << 20), + batchMaxCount: 100 // 100 requests +}; +// @TODO: Unchecked Signers +export class JsonRpcSigner extends AbstractSigner { + address; + constructor(provider, address) { + super(provider); + defineProperties(this, { address }); + } + connect(provider) { + return logger.throwError("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); + } + //async getNetwork(): Promise> { + // return await this.provider.getNetwork(); + //} + //async estimateGas(tx: TransactionRequest): Promise { + // return await this.provider.estimateGas(tx); + //} + //async call(tx: TransactionRequest): Promise { + // return await this.provider.call(tx); + //} + //async resolveName(name: string | Addressable): Promise { + // return await this.provider.resolveName(name); + //} + //async getNonce(blockTag?: BlockTag): Promise { + // return await this.provider.getTransactionCountOf(this.address); + //} + // 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); + if (from == null || from.toLowerCase() !== this.address.toLowerCase()) { + logger.throwArgumentError("from address mismatch", "transaction", _tx); + } + tx.from = from; + })()); + } + else { + tx.from = this.address; + } + // The JSON-RPC for eth_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("eth_sendTransaction", [hexTx]); + } + async sendTransaction(tx) { + // This cannot be mined any earlier than any recent block + const blockNumber = await this.provider.getBlockNumber(); + // 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]; + const checkTx = async () => { + // Try getting the transaction + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(this.provider._wrapTransaction(tx, hash, blockNumber)); + return; + } + // 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); + if (from == null || from.toLowerCase() !== this.address.toLowerCase()) { + return logger.throwArgumentError("from address mismatch", "transaction", _tx); + } + tx.from = from; + } + else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("eth_sign_Transaction", [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); + if (address == null) { + return logger.throwArgumentError("TypedData does not support null address", "value", value); + } + return address; + }); + return await this.provider.send("eth_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#eth_sign + async _legacySignMessage(_message) { + const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message); + return await this.provider.send("eth_sign", [ + this.address.toLowerCase(), hexlify(message) + ]); + } +} +export class JsonRpcApiProvider extends AbstractProvider { + #options; + #nextId; + #payloads; + #drainTimer; + constructor(network, options) { + super(network); + this.#nextId = 1; + this.#options = Object.assign({}, defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + // This could be relaxed in the future to just check equivalent networks + const staticNetwork = this._getOption("staticNetwork"); + if (staticNetwork && staticNetwork !== network) { + logger.throwArgumentError("staticNetwork MUST match network object", "options", options); + } + } + _getOption(key) { + return this.#options[key]; + } + // @TODO: Merge this into send + //prepareRequest(method: string, params: Array): JsonRpcPayload { + // return { + // method, params, id: (this.#nextId++), jsonrpc: "2.0" + // }; + //} + /* + async send(method: string, params: Array): Promise { + // @TODO: This should construct and queue the payload + throw new Error("sub-class must implement this"); + } + */ + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + 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 payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload)); + this.emit("debug", { action: "sendRpcPayload", payload }); + 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) { + // 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) { + return reject(new Error("@TODO: no result")); + } + // The response is an error + if ("error" in resp) { + return reject(this.getRpcError(payload, resp)); + } + // 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); + } + } + })(); + } + }, this.#options.batchStallTime); + } + // Sub-classes should **NOT** override this + send(method, params) { + // @TODO: cache chainId?? purge on switch_networks + const id = this.#nextId++; + const promise = new Promise((resolve, reject) => { + this.#payloads.push({ + resolve, reject, + payload: { method, params, id, jsonrpc: "2.0" } + }); + }); + // If there is not a pending drainTimer, set one + this.#scheduleDrain(); + return promise; + } + // Sub-classes MUST override this + _send(payload) { + return logger.throwError("sub-classes must override _send", "UNSUPPORTED_OPERATION", { + operation: "jsonRpcApiProvider._send" + }); + } + async getSigner(address = 0) { + const accountsPromise = this.send("eth_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 [network, accounts] = await Promise.all([this.getNetwork(), accountsPromise]); + // Account address + address = network.formatter.address(address); + for (const account of accounts) { + if (network.formatter.address(account) === account) { + return new JsonRpcSigner(this, account); + } + } + throw new Error("invalid account"); + } + // Sub-classes can override this; it detects the *actual* network we + // are connected to + async _detectNetwork() { + // We have a static network (like INFURA) + const network = this._getOption("staticNetwork"); + if (network) { + return network; + } + return Network.from(logger.getBigInt(await this._perform({ method: "chainId" }))); + } + _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); + } + // Normalize a JSON-RPC transaction + 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(logger.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; + } + // Get the necessary paramters for making a JSON-RPC request + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "eth_chainId", args: [] }; + case "getBlockNumber": + return { method: "eth_blockNumber", args: [] }; + case "getGasPrice": + return { method: "eth_gasPrice", args: [] }; + case "getBalance": + return { + method: "eth_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "eth_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "eth_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorageAt": + return { + method: "eth_getStorageAt", + args: [ + getLowerCase(req.address), + ("0x" + req.position.toString(16)), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "eth_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "eth_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] + }; + } + else if ("blockHash" in req) { + return { + method: "eth_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] + }; + } + break; + case "getTransaction": + return { + method: "eth_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "eth_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "eth_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "eth_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + 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: "eth_getLogs", args: [req.filter] }; + } + return null; + } + getRpcError(payload, error) { + console.log("getRpcError", payload, error); + return new Error(`JSON-RPC badness; @TODO: ${error}`); + /* + if (payload.method === "eth_call") { + const result = spelunkData(error); + if (result) { + // @TODO: Extract errorSignature, errorName, errorArgs, reason if + // it is Error(string) or Panic(uint25) + return logger.makeError("execution reverted during JSON-RPC call", "CALL_EXCEPTION", { + data: result.data, + transaction: args[0] + }); + } + + return logger.makeError("missing revert data during JSON-RPC call", "CALL_EXCEPTION", { + data: "0x", transaction: args[0], info: { error } + }); + } + + if (method === "eth_estimateGas") { + // @TODO: Spelunk, and adapt the above to allow missing data. + // Then throw an UNPREDICTABLE_GAS exception + } + + const message = JSON.stringify(spelunkMessage(error)); + + if (message.match(/insufficient funds|base fee exceeds gas limit/)) { + return logger.makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: args[0] + }); + } + + if (message.match(/nonce/) && message.match(/too low/)) { + return logger.makeError("nonce has already been used", "NONCE_EXPIRED", { + transaction: args[0] + }); + } + + // "replacement transaction underpriced" + if (message.match(/replacement transaction/) && message.match(/underpriced/)) { + return logger.makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { + transaction: args[0] + }); + } + + if (message.match(/only replay-protected/)) { + return logger.makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, info: { transaction: args[0] } + }); + } + + if (method === "estimateGas" && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) { + return logger.makeError("cannot estimate gas; transaction may fail or may require manual gas limit", "UNPREDICTABLE_GAS_LIMIT", { + transaction: args[0] + }); + } + + return error; + */ + } + 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 + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && logger.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(); + 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); + /* + @TODO: Add debug output to send + this.emit("debug", { type: "sendRequest", request }); + try { + const result = + //console.log("RR", result); + this.emit("debug", { type: "getResponse", result }); + return result; + } catch (error) { + this.emit("debug", { type: "getError", error }); + throw error; + //throw this.getRpcError(request.method, request.args, error); + } + */ + } + return super._perform(req); + } +} +export class JsonRpcProvider extends JsonRpcApiProvider { + #connect; + #pollingInterval; + constructor(url, network, options) { + if (url == null) { + url = "http:/\/localhost:8545"; + } + super(network, options); + if (typeof (url) === "string") { + this.#connect = new FetchRequest(url); + } + else { + this.#connect = url.clone(); + } + this.#pollingInterval = 4000; + } + async _send(payload) { + // Configure a POST connection for the requested method + const request = this.#connect.clone(); + request.body = JSON.stringify(payload); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; + } + get pollingInterval() { return this.#pollingInterval; } + set pollingInterval(value) { + if (!Number.isInteger(value) || value < 0) { + throw new Error("invalid interval"); + } + this.#pollingInterval = value; + this._forEachSubscriber((sub) => { + if (isPollable(sub)) { + sub.pollingInterval = this.#pollingInterval; + } + }); + } +} +// This class should only be used when it is not possible for the +// underlying network to change, such as with INFURA. If you are +// using MetaMask or some other client which allows users to change +// their network DO NOT USE THIS. Bad things will happen. +/* +export class StaticJsonRpcProvider extends JsonRpcProvider { + readonly network!: Network; + + constructor(url: string | ConnectionInfo, network?: Network, options?: JsonRpcOptions) { + super(url, network, options); + defineProperties(this, { network }); + } + + async _detectNetwork(): Promise { + return this.network; + } +} +*/ +/* +function spelunkData(value: any): null | { message: string, data: string } { + if (value == null) { return null; } + + // These *are* the droids we're looking for. + if (typeof(value.message) === "string" && value.message.match("reverted") && 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: any, result: Array): void { + 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: any): Array { + const result: Array = [ ]; + _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 000000000..3a82d651d --- /dev/null +++ b/lib.esm/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,SAAS;AACT,yBAAyB;AAEzB,yQAAyQ;AAEzQ,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAExD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CA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,CAAC,GAAG,CAAC,EAAE;gBACjB,GAAG,CAAC,eAAe,GAAG,IAAI,CAAC,gBAAgB,CAAC;aAC/C;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAED,iEAAiE;AACjE,gEAAgE;AAChE,mEAAmE;AACnE,yDAAyD;AACzD;;;;;;;;;;;;;EAaE;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwDE"} \ No newline at end of file diff --git a/lib.esm/providers/provider-pocket.js b/lib.esm/providers/provider-pocket.js new file mode 100644 index 000000000..c2ffa7fa5 --- /dev/null +++ b/lib.esm/providers/provider-pocket.js @@ -0,0 +1,101 @@ +"use strict"; +/* +import { defineProperties } from "../utils/properties.js"; +import { FetchRequest } from "../web/index.js"; + +import { showThrottleMessage } from "./community.js"; +import { logger } from "../utils/logger.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; + +import type { ConnectionInfo, ThrottleRetryFunc } from "../web/index.js"; + +import type { CommunityResourcable } from "./community.js"; +import type { Networkish } from "./network.js"; + + + +// These are load-balancer-based application IDs +const defaultAppIds: Record = { + homestead: "6004bcd10040261633ade990", + ropsten: "6004bd4d0040261633ade991", + rinkeby: "6004bda20040261633ade994", + goerli: "6004bd860040261633ade992", +}; + +function getHost(name: string): string { + switch(name) { + case "homestead": + return "eth-mainnet.gateway.pokt.network"; + case "ropsten": + return "eth-ropsten.gateway.pokt.network"; + case "rinkeby": + return "eth-rinkeby.gateway.pokt.network"; + case "goerli": + return "eth-goerli.gateway.pokt.network"; + } + + return logger.throwArgumentError("unsupported network", "network", name); +} + +function normalizeApiKey(network: Network, _appId?: null | string, applicationSecretKey?: null | string, loadBalancer?: boolean): { applicationId: string, applicationSecretKey: null | string, loadBalancer: boolean, community: boolean } { + loadBalancer = !!loadBalancer; + + let community = false; + let applicationId = _appId; + if (applicationId == null) { + applicationId = defaultAppIds[network.name]; + if (applicationId == null) { + logger.throwArgumentError("network does not support default applicationId", "applicationId", _appId); + } + loadBalancer = true; + community = true; + } else if (applicationId === defaultAppIds[network.name]) { + loadBalancer = true; + community = true; + } + if (applicationSecretKey == null) { applicationSecretKey = null; } + + return { applicationId, applicationSecretKey, community, loadBalancer }; +} + +export class PocketProvider extends JsonRpcProvider implements CommunityResourcable { + readonly applicationId!: string; + readonly applicationSecretKey!: null | string; + readonly loadBalancer!: boolean; + + constructor(_network: Networkish = "homestead", _appId?: null | string, _secretKey?: null | string, _loadBalancer?: boolean) { + const network = Network.from(_network); + const { applicationId, applicationSecretKey, loadBalancer } = normalizeApiKey(network, _appId, _secretKey, _loadBalancer); + + const connection = PocketProvider.getConnection(network, applicationId, applicationSecretKey, loadBalancer); + super(connection, network, { staticNetwork: network }); + + defineProperties(this, { applicationId, applicationSecretKey, loadBalancer }); + } + + static getConnection(network: Network, _appId?: null | string, _secretKey?: null | string, _loadBalancer?: boolean): ConnectionInfo { + const { applicationId, applicationSecretKey, community, loadBalancer } = normalizeApiKey(network, _appId, _secretKey, _loadBalancer); + + let url = `https:/\/${ getHost(network.name) }/v1/`; + if (loadBalancer) { url += "lb/"; } + url += applicationId; + + const request = new FetchRequest(url); + request.allowGzip = true; + if (applicationSecretKey) { request.setCredentials("", applicationSecretKey); } + + const throttleRetry: ThrottleRetryFunc = async (request, response, attempt) => { + if (community) { showThrottleMessage("PocketProvider"); } + return true; + }; + + return { request, throttleRetry }; + } + + isCommunityResource(): boolean { + return (this.applicationId === defaultAppIds[this.network.name]); + } +} +*/ +//# sourceMappingURL=provider-pocket.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-pocket.js.map b/lib.esm/providers/provider-pocket.js.map new file mode 100644 index 000000000..48d33a040 --- /dev/null +++ b/lib.esm/providers/provider-pocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-pocket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-pocket.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkGE"} \ No newline at end of file diff --git a/lib.esm/providers/provider-socket.js b/lib.esm/providers/provider-socket.js new file mode 100644 index 000000000..3a9aadc53 --- /dev/null +++ b/lib.esm/providers/provider-socket.js @@ -0,0 +1,217 @@ +/** + * SocketProvider + * + * Generic long-lived socket provider. + * + * Sub-classing notes + * - a sub-class MUST call the `_start()` method once connected + * - a sub-class MUST override the `_write(string)` method + * - a sub-class MUST call `_processMessage(string)` for each message + */ +import { UnmanagedSubscriber } from "./abstract-provider.js"; +import { assertArgument, logger } from "../utils/logger.js"; +import { JsonRpcApiProvider } from "./provider-jsonrpc.js"; +export class SocketSubscriber { + #provider; + #filter; + get filter() { return JSON.parse(this.#filter); } + #filterId; + #paused; + #emitPromise; + constructor(provider, filter) { + this.#provider = provider; + this.#filter = JSON.stringify(filter); + this.#filterId = null; + this.#paused = null; + this.#emitPromise = null; + } + start() { + this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId) => { + ; + this.#provider._register(filterId, this); + return filterId; + }); + } + stop() { + (this.#filterId).then((filterId) => { + this.#provider.send("eth_unsubscribe", [filterId]); + }); + this.#filterId = null; + } + // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs + // and resume + pause(dropWhilePaused) { + if (!dropWhilePaused) { + logger.throwError("preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { + operation: "pause(false)" + }); + } + this.#paused = !!dropWhilePaused; + } + resume() { + this.#paused = null; + } + _handleMessage(message) { + if (this.#filterId == null) { + return; + } + if (this.#paused === null) { + let emitPromise = this.#emitPromise; + if (emitPromise == null) { + emitPromise = this._emit(this.#provider, message); + } + else { + emitPromise = emitPromise.then(async () => { + await this._emit(this.#provider, message); + }); + } + this.#emitPromise = emitPromise.then(() => { + if (this.#emitPromise === emitPromise) { + this.#emitPromise = null; + } + }); + } + } + async _emit(provider, message) { + throw new Error("sub-classes must implemente this; _emit"); + } +} +export class SocketBlockSubscriber extends SocketSubscriber { + constructor(provider) { + super(provider, ["newHeads"]); + } + async _emit(provider, message) { + provider.emit("block", parseInt(message.number)); + } +} +export class SocketPendingSubscriber extends SocketSubscriber { + constructor(provider) { + super(provider, ["newPendingTransactions"]); + } + async _emit(provider, message) { + provider.emit("pending", message); + } +} +export class SocketEventSubscriber extends SocketSubscriber { + #logFilter; + get logFilter() { return JSON.parse(this.#logFilter); } + #formatter; + constructor(provider, filter) { + super(provider, ["logs", filter]); + this.#logFilter = JSON.stringify(filter); + this.#formatter = provider.getNetwork().then((network) => network.formatter); + } + async _emit(provider, message) { + const formatter = await this.#formatter; + provider.emit(this.#logFilter, formatter.log(message, provider)); + } +} +export class SocketProvider extends JsonRpcApiProvider { + #callbacks; + #ready; + // Maps each filterId to its subscriber + #subs; + // If any events come in before a subscriber has finished + // registering, queue them + #pending; + constructor(network) { + super(network, { batchMaxCount: 1 }); + this.#callbacks = new Map(); + this.#ready = false; + this.#subs = new Map(); + this.#pending = new Map(); + } + _getSubscriber(sub) { + switch (sub.type) { + case "close": + return new UnmanagedSubscriber("close"); + case "block": + return new SocketBlockSubscriber(this); + case "pending": + return new SocketPendingSubscriber(this); + case "event": + return new SocketEventSubscriber(this, sub.filter); + case "orphan": + // Handled auto-matically within AbstractProvider + // when the log.removed = true + if (sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("drop-log"); + } + } + return super._getSubscriber(sub); + } + _register(filterId, subscriber) { + this.#subs.set(filterId, subscriber); + const pending = this.#pending.get(filterId); + if (pending) { + for (const message of pending) { + subscriber._handleMessage(message); + } + this.#pending.delete(filterId); + } + } + async _send(payload) { + // WebSocket provider doesn't accept batches + assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload); + // @TODO: stringify payloads here and store to prevent mutations + const promise = new Promise((resolve, reject) => { + this.#callbacks.set(payload.id, { payload, resolve, reject }); + }); + if (this.#ready) { + await this._write(JSON.stringify(payload)); + } + return [await promise]; + } + // Sub-classes must call this once they are connected + async _start() { + if (this.#ready) { + return; + } + this.#ready = true; + for (const { payload } of this.#callbacks.values()) { + await this._write(JSON.stringify(payload)); + } + } + // Sub-classes must call this for each message + async _processMessage(message) { + const result = (JSON.parse(message)); + if ("id" in result) { + const callback = this.#callbacks.get(result.id); + if (callback == null) { + console.log("Weird... Response for not a thing we sent"); + return; + } + this.#callbacks.delete(result.id); + if ("error" in result) { + const { message, code, data } = result.error; + const error = logger.makeError(message || "unkonwn error", "SERVER_ERROR", { + request: `ws:${JSON.stringify(callback.payload)}`, + info: { code, data } + }); + callback.reject(error); + } + else { + callback.resolve(result.result); + } + } + else if (result.method === "eth_subscription") { + const filterId = result.params.subscription; + const subscriber = this.#subs.get(filterId); + if (subscriber) { + subscriber._handleMessage(result.params.result); + } + else { + let pending = this.#pending.get(filterId); + if (pending == null) { + pending = []; + this.#pending.set(filterId, pending); + } + pending.push(result.params.result); + } + } + } + async _write(message) { + throw new Error("sub-classes must override this"); + } +} +//# sourceMappingURL=provider-socket.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-socket.js.map b/lib.esm/providers/provider-socket.js.map new file mode 100644 index 000000000..4bc722165 --- /dev/null +++ b/lib.esm/providers/provider-socket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-socket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-socket.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAiB3D,MAAM,OAAO,gBAAgB;IACzB,SAAS,CAAiB;IAE1B,OAAO,CAAS;IAChB,IAAI,MAAM,KAAiB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CA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C;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/provider-websocket.js b/lib.esm/providers/provider-websocket.js new file mode 100644 index 000000000..8eafdaa15 --- /dev/null +++ b/lib.esm/providers/provider-websocket.js @@ -0,0 +1,26 @@ +import { WebSocket as _WebSocket } from "./ws.js"; /*-browser*/ +import { SocketProvider } from "./provider-socket.js"; +export class WebSocketProvider extends SocketProvider { + url; + #websocket; + get websocket() { return this.#websocket; } + constructor(url, network) { + super(network); + if (typeof (url) === "string") { + this.#websocket = new _WebSocket(url); + } + else { + this.#websocket = url; + } + this.websocket.onopen = () => { + this._start(); + }; + this.websocket.onmessage = (message) => { + this._processMessage(message.data); + }; + } + async _write(message) { + this.websocket.send(message); + } +} +//# sourceMappingURL=provider-websocket.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-websocket.js.map b/lib.esm/providers/provider-websocket.js.map new file mode 100644 index 000000000..bb449ef3c --- /dev/null +++ b/lib.esm/providers/provider-websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-websocket.js","sourceRoot":"","sources":["../../src.ts/providers/provider-websocket.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,IAAI,UAAU,EAAE,MAAM,SAAS,CAAC,CAAC,YAAY;AAE/D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAetD,MAAM,OAAO,iBAAkB,SAAQ,cAAc;IACjD,GAAG,CAAU;IAEb,UAAU,CAAgB;IAC1B,IAAI,SAAS,KAAoB,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAE1D,YAAY,GAA2B,EAAE,OAAoB;QACzD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,OAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE;YAC1B,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;SACzC;aAAM;YACH,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC;SACzB;QAED,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,GAAG,EAAE;YACzB,IAAI,CAAC,MAAM,EAAE,CAAC;QAClB,CAAC,CAAC;QAEF,IAAI,CAAC,SAAS,CAAC,SAAS,GAAG,CAAC,OAAyB,EAAE,EAAE;YACrD,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACvC,CAAC,CAAC;IACN,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAAe;QACxB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACJ"} \ 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 000000000..956a088c6 --- /dev/null +++ b/lib.esm/providers/provider.js @@ -0,0 +1,551 @@ +//import { resolveAddress } from "@ethersproject/address"; +import { hexlify } from "../utils/data.js"; +import { logger } from "../utils/logger.js"; +import { defineProperties } from "../utils/properties.js"; +import { accessListify } from "../transaction/index.js"; +// ----------------------- +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +// @TODO? implements Required +export class FeeData { + gasPrice; + maxFeePerGas; + maxPriorityFeePerGas; + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + defineProperties(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), + }; + } +} +; +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 in bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = logger.getBigInt(req[key], `request.${key}`); + } + const numberKeys = "type,nonce".split(/,/); + for (const key in numberKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = logger.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.enableCcipReadEnabled = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + return result; +} +; +export class Block { + provider; + number; + hash; + timestamp; + parentHash; + nonce; + difficulty; + gasLimit; + gasUsed; + miner; + extraData; + baseFeePerGas; + #transactions; + constructor(block, provider) { + if (provider == null) { + provider = dummyProvider; + } + this.#transactions = Object.freeze(block.transactions.map((tx) => { + if (typeof (tx) !== "string" && tx.provider !== provider) { + throw new Error("provider mismatch"); + } + return tx; + })); + ; + 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) + }); + } + get transactions() { return this.#transactions; } + //connect(provider: Provider): Block { + // return new Block(this, provider); + //} + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, nonce, number, parentHash, timestamp, transactions } = this; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + hash, miner, nonce, number, parentHash, timestamp, + transactions, + }; + } + [Symbol.iterator]() { + let index = 0; + return { + next: () => { + if (index < this.length) { + return { + value: this.transactions[index++], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + get length() { return this.transactions.length; } + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1000); + } + async getTransaction(index) { + const tx = this.transactions[index]; + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + isMined() { return !!this.hash; } + isLondon() { return !!this.baseFeePerGas; } + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +export class Log { + provider; + transactionHash; + blockHash; + blockNumber; + removed; + address; + data; + topics; + index; + transactionIndex; + constructor(log, provider) { + if (provider == null) { + provider = dummyProvider; + } + 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, + }); + } + //connect(provider: Provider): Log { + // return new Log(this, provider); + //} + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, blockHash, blockNumber, data, index, + removed, topics, transactionHash, transactionIndex + }; + } + async getBlock() { + return (await this.provider.getBlock(this.blockHash)); + } + async getTransaction() { + return (await this.provider.getTransaction(this.transactionHash)); + } + async getTransactionReceipt() { + return (await this.provider.getTransactionReceipt(this.transactionHash)); + } + removedEvent() { + return createRemovedLogFilter(this); + } +} +export class TransactionReceipt { + provider; + to; + from; + contractAddress; + hash; + index; + blockHash; + blockNumber; + logsBloom; + gasUsed; + cumulativeGasUsed; + gasPrice; + byzantium; + status; + root; + #logs; + constructor(tx, provider) { + if (provider == null) { + provider = dummyProvider; + } + this.#logs = Object.freeze(tx.logs.map((log) => { + if (provider !== log.provider) { + //return log.connect(provider); + throw new Error("provider mismatch"); + } + return log; + })); + 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: (tx.effectiveGasPrice || tx.gasPrice), + byzantium: tx.byzantium, + status: tx.status, + root: tx.root + }); + } + get logs() { return this.#logs; } + //connect(provider: Provider): TransactionReceipt { + // return new TransactionReceipt(this, provider); + //} + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, byzantium, status, root } = 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, root, status, to + }; + } + 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 }; + } + }; + } + get fee() { + return this.gasUsed * this.gasPrice; + } + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + async confirmations() { + return (await this.provider.getBlockNumber()) - this.blockNumber + 1; + } + removedEvent() { + return createRemovedTransactionFilter(this); + } + reorderedEvent(other) { + if (other && !other.isMined()) { + return logger.throwError("unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "reorderedEvent(other)" + }); + } + return createReorderedTransactionFilter(this, other); + } +} +; +export class TransactionResponse { + provider; + blockNumber; + blockHash; + index; + hash; + type; + to; + from; + nonce; + gasLimit; + gasPrice; + maxPriorityFeePerGas; + maxFeePerGas; + data; + value; + chainId; + signature; + accessList; + constructor(tx, provider) { + if (provider == null) { + provider = dummyProvider; + } + 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.gasPrice = tx.gasPrice; + 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; + } + //connect(provider: Provider): TransactionResponse { + // return new TransactionResponse(this, provider); + //} + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList } = this; + return { + _type: "TransactionReceipt", + accessList, blockNumber, blockHash, + chainId: toJson(this.chainId), + data, from, + gasLimit: toJson(this.gasLimit), + gasPrice: toJson(this.gasPrice), + hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + nonce, signature, to, index, type, + value: toJson(this.value), + }; + } + async getBlock() { + 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); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + async getTransaction() { + return this.provider.getTransaction(this.hash); + } + async wait(confirms) { + return this.provider.waitForTransaction(this.hash, confirms); + } + isMined() { + return (this.blockHash != null); + } + isLegacy() { + return (this.type === 0); + } + isBerlin() { + return (this.type === 1); + } + isLondon() { + return (this.type === 2); + } + removedEvent() { + if (!this.isMined()) { + return logger.throwError("unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + return createRemovedTransactionFilter(this); + } + reorderedEvent(other) { + if (!this.isMined()) { + return logger.throwError("unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + if (other && !other.isMined()) { + return logger.throwError("unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + } + return createReorderedTransactionFilter(this, other); + } +} +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 + } }; +} +function fail() { + throw new Error("this provider should not be used"); +} +class DummyProvider { + get provider() { return this; } + async getNetwork() { return fail(); } + async getFeeData() { return fail(); } + async estimateGas(tx) { return fail(); } + async call(tx) { return fail(); } + async resolveName(name) { return fail(); } + // State + async getBlockNumber() { return fail(); } + // Account + async getBalance(address, blockTag) { + return fail(); + } + async getTransactionCount(address, blockTag) { + return fail(); + } + async getCode(address, blockTag) { + return fail(); + } + async getStorageAt(address, position, blockTag) { + return fail(); + } + // Write + async broadcastTransaction(signedTx) { return fail(); } + // Queries + async getBlock(blockHashOrBlockTag) { + return fail(); + } + async getBlockWithTransactions(blockHashOrBlockTag) { + return fail(); + } + async getTransaction(hash) { + return fail(); + } + async getTransactionReceipt(hash) { + return fail(); + } + // Bloom-filter Queries + async getLogs(filter) { + return fail(); + } + // ENS + async lookupAddress(address) { + return fail(); + } + async waitForTransaction(hash, confirms, timeout) { + return fail(); + } + async waitForBlock(blockTag) { + return fail(); + } + // EventEmitterable + async on(event, listener) { return fail(); } + async once(event, listener) { return fail(); } + async emit(event, ...args) { return fail(); } + async listenerCount(event) { return fail(); } + async listeners(event) { return fail(); } + async off(event, listener) { return fail(); } + async removeAllListeners(event) { return fail(); } + async addListener(event, listener) { return fail(); } + async removeListener(event, listener) { return fail(); } +} +/** + * A singleton [[Provider]] instance that can be used as a placeholder. This + * allows API that have a Provider added later to not require a null check. + * + * All operations performed on this [[Provider]] will throw. + */ +export const dummyProvider = new DummyProvider(); +//# 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 000000000..34da421e7 --- /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,0DAA0D;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAcxD,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;AAC1D,MAAM,OAAO,OAAO;IACP,QAAQ,CAAiB;IACzB,YAAY,CAAiB;IAC7B,oBAAoB,CAAiB;IAE9C,YAAY,QAAwB,EAAE,YAA4B,EAAE,oBAAoC;QACpG,gBAAgB,CAAU,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,MAAM;QACF,MAAM,EACF,QAAQ,EAAE,YAAY,EAAE,oBAAoB,EAC/C,GAAG,IAAI,CAAC;QACT,OAAO;YACH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AK,CAAC,YAAY,CAAC,QAAmB;QAClC,OAAO,IAAI,EAAiB,CAAC;IACjC,CAAC;IAED,mBAAmB;IACnB,KAAK,CAAC,EAAE,CAAC,KAAoB,EAAE,QAAkB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IACpF,KAAK,CAAC,IAAI,CAAC,KAAoB,EAAE,QAAkB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IACtF,KAAK,CAAC,IAAI,CAAC,KAAoB,EAAE,GAAG,IAAgB,IAAsB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1F,KAAK,CAAC,aAAa,CAAC,KAAqB,IAAqB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IAC9E,KAAK,CAAC,SAAS,CAAC,KAAqB,IAA8B,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IACnF,KAAK,CAAC,GAAG,CAAC,KAAoB,EAAE,QAAmB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IACtF,KAAK,CAAC,kBAAkB,CAAC,KAAqB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IAEjF,KAAK,CAAC,WAAW,CAAC,KAAoB,EAAE,QAAkB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7F,KAAK,CAAC,cAAc,CAAC,KAAoB,EAAE,QAAkB,IAAmB,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;CACnG;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,aAAa,GAAa,IAAI,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/signer.js b/lib.esm/providers/signer.js new file mode 100644 index 000000000..7c8f9901a --- /dev/null +++ b/lib.esm/providers/signer.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=signer.js.map \ No newline at end of file diff --git a/lib.esm/providers/signer.js.map b/lib.esm/providers/signer.js.map new file mode 100644 index 000000000..68d48a837 --- /dev/null +++ b/lib.esm/providers/signer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signer.js","sourceRoot":"","sources":["../../src.ts/providers/signer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/lib.esm/providers/subscriber-connection.js b/lib.esm/providers/subscriber-connection.js new file mode 100644 index 000000000..4321a229a --- /dev/null +++ b/lib.esm/providers/subscriber-connection.js @@ -0,0 +1,37 @@ +import { logger } from "../utils/logger.js"; +export class BlockConnectionSubscriber { + #provider; + #blockNumber; + #filterId; + constructor(provider) { + this.#provider = provider; + this.#blockNumber = -2; + this.#filterId = null; + } + start() { + this.#filterId = this.#provider._subscribe(["newHeads"], (result) => { + const blockNumber = logger.getNumber(result.number); + const initial = (this.#blockNumber === -2) ? blockNumber : (this.#blockNumber + 1); + for (let b = initial; b <= blockNumber; b++) { + this.#provider.emit("block", b); + } + this.#blockNumber = blockNumber; + }); + } + stop() { + if (this.#filterId != null) { + this.#provider._unsubscribe(this.#filterId); + this.#filterId = null; + } + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#blockNumber = -2; + } + this.stop(); + } + resume() { + this.start(); + } +} +//# sourceMappingURL=subscriber-connection.js.map \ No newline at end of file diff --git a/lib.esm/providers/subscriber-connection.js.map b/lib.esm/providers/subscriber-connection.js.map new file mode 100644 index 000000000..f4a52e33b --- /dev/null +++ b/lib.esm/providers/subscriber-connection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-connection.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-connection.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAW5C,MAAM,OAAO,yBAAyB;IAClC,SAAS,CAAwB;IACjC,YAAY,CAAS;IAErB,SAAS,CAAgB;IAEzB,YAAY,QAA+B;QACvC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;IAC1B,CAAC;IAED,KAAK;QACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAE,UAAU,CAAE,EAAE,CAAC,MAAW,EAAE,EAAE;YACvE,MAAM,WAAW,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACpD,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAA,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAA;YACjF,KAAK,IAAI,CAAC,GAAG,OAAO,EAAE,CAAC,IAAI,WAAW,EAAE,CAAC,EAAE,EAAE;gBACzC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;aACnC;YACD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QACpC,CAAC,CAAC,CAAC;IACP,CAAC;IAED,IAAI;QACA,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;YACxB,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC5C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;SACzB;IACL,CAAC;IAED,KAAK,CAAC,eAAyB;QAC3B,IAAI,eAAe,EAAE;YAAE,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;SAAE;QAChD,IAAI,CAAC,IAAI,EAAE,CAAC;IAChB,CAAC;IAED,MAAM;QACF,IAAI,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/subscriber-filterid.js b/lib.esm/providers/subscriber-filterid.js new file mode 100644 index 000000000..b6e02f462 --- /dev/null +++ b/lib.esm/providers/subscriber-filterid.js @@ -0,0 +1,105 @@ +import { PollingEventSubscriber } from "./subscriber-polling.js"; +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +export class FilterIdSubscriber { + #provider; + #filterIdPromise; + #poller; + #network; + constructor(provider) { + this.#provider = provider; + this.#filterIdPromise = null; + this.#poller = this.#poll.bind(this); + this.#network = null; + } + _subscribe(provider) { + throw new Error("subclasses must override this"); + } + _emitResults(provider, result) { + throw new Error("subclasses must override this"); + } + _recover(provider) { + throw new Error("subclasses must override this"); + } + async #poll(blockNumber) { + try { + if (this.#filterIdPromise == null) { + this.#filterIdPromise = this._subscribe(this.#provider); + } + const filterId = await this.#filterIdPromise; + if (filterId == null) { + this.#provider._recoverSubscriber(this, this._recover(this.#provider)); + return; + } + const network = await this.#provider.getNetwork(); + if (!this.#network) { + this.#network = network; + } + if (this.#network.chainId !== network.chainId) { + throw new Error("chaid changed"); + } + const result = await this.#provider.send("eth_getFilterChanges", [filterId]); + await this._emitResults(this.#provider, result); + } + catch (error) { + console.log("@TODO", error); + } + this.#provider.once("block", this.#poller); + } + #teardown() { + const filterIdPromise = this.#filterIdPromise; + if (filterIdPromise) { + this.#filterIdPromise = null; + filterIdPromise.then((filterId) => { + this.#provider.send("eth_uninstallFilter", [filterId]); + }); + } + } + start() { this.#poll(-2); } + stop() { + this.#teardown(); + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#teardown(); + } + this.#provider.off("block", this.#poller); + } + resume() { this.start(); } +} +export class FilterIdEventSubscriber extends FilterIdSubscriber { + #event; + constructor(provider, filter) { + super(provider); + this.#event = copy(filter); + } + _recover(provider) { + return new PollingEventSubscriber(provider, this.#event); + } + async _subscribe(provider) { + const filterId = await provider.send("eth_newFilter", [this.#event]); + console.log("____SUB", filterId); + return filterId; + } + async _emitResults(provider, results) { + const network = await provider.getNetwork(); + for (const result of results) { + const log = network.formatter.log(result, provider); + provider.emit(this.#event, log); + } + } +} +export class FilterIdPendingSubscriber extends FilterIdSubscriber { + async _subscribe(provider) { + return await provider.send("eth_newPendingTransactionFilter", []); + } + async _emitResults(provider, results) { + const network = await provider.getNetwork(); + for (const result of results) { + provider.emit("pending", network.formatter.hash(result)); + } + } +} +//# sourceMappingURL=subscriber-filterid.js.map \ No newline at end of file diff --git a/lib.esm/providers/subscriber-filterid.js.map b/lib.esm/providers/subscriber-filterid.js.map new file mode 100644 index 000000000..28a41cad9 --- /dev/null +++ b/lib.esm/providers/subscriber-filterid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-filterid.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-filterid.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAUjE,SAAS,IAAI,CAAC,GAAQ;IAClB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,OAAO,kBAAkB;IAC3B,SAAS,CAAqB;IAE9B,gBAAgB,CAAyB;IACzC,OAAO,CAA+B;IAEtC,QAAQ,CAAyB;IAEjC,YAAY,QAA4B;QACpC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAE1B,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAErC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACzB,CAAC;IAED,UAAU,CAAC,QAA4B;QACnC,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACrD,CAAC;IAED,YAAY,CAAC,QAA0B,EAAE,MAAkB;QACvD,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACrD,CAAC;IAED,QAAQ,CAAC,QAA0B;QAC/B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACrD,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,WAAmB;QAC3B,IAAI;YACA,IAAI,IAAI,CAAC,gBAAgB,IAAI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Q,CAAC,UAAU,EAAE,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;YAC1B,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YACpD,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;SACnC;IACL,CAAC;CACJ;AAED,MAAM,OAAO,yBAA0B,SAAQ,kBAAkB;IAC7D,KAAK,CAAC,UAAU,CAAC,QAA4B;QACzC,OAAO,MAAM,QAAQ,CAAC,IAAI,CAAC,iCAAiC,EAAE,EAAG,CAAC,CAAC;IACvE,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA4B,EAAE,OAAmB;QAChE,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,UAAU,EAAE,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;YAC1B,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;SAC5D;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/subscriber-hotswap.js b/lib.esm/providers/subscriber-hotswap.js new file mode 100644 index 000000000..a7f27e7ad --- /dev/null +++ b/lib.esm/providers/subscriber-hotswap.js @@ -0,0 +1,43 @@ +"use strict"; +/* +import { Subscriber } from "./abstract-provider.js"; + +export class HotSwapSubscriber implements Subscriber { + #target?: Subscriber; + + _switchSubscriber(subscriber: Subscriber): void { + this.#target = subscriber; + } + + start(): void { + if (this.#target) { return this.#target.start(); } + return super.start(); + } + + stop(): void { + if (this.#target) { return this.#target.stop(); } + return super.stop(); + } + + pause(dropWhilePaused?: boolean): void { + if (this.#target) { return this.#target.pause(dropWhilePaused); } + return super.pause(dropWhilePaused); + } + + resume(): void { + if (this.#target) { return this.#target.resume(); } + return super.resume(); + } + + set pollingInterval(value: number) { + if (this.#target) { return this.#target.pollingInterval = value; } + return super.pollingInterval = value; + } + + get pollingInterval(): number { + if (this.#target) { return this.#target.pollingInterval; } + return super.pollingInterval; + } +} +*/ +//# sourceMappingURL=subscriber-hotswap.js.map \ No newline at end of file diff --git a/lib.esm/providers/subscriber-hotswap.js.map b/lib.esm/providers/subscriber-hotswap.js.map new file mode 100644 index 000000000..c8457b9ba --- /dev/null +++ b/lib.esm/providers/subscriber-hotswap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-hotswap.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-hotswap.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwCE"} \ No newline at end of file diff --git a/lib.esm/providers/subscriber-polling.js b/lib.esm/providers/subscriber-polling.js new file mode 100644 index 000000000..b74096417 --- /dev/null +++ b/lib.esm/providers/subscriber-polling.js @@ -0,0 +1,174 @@ +import { isHexString } from "../utils/data.js"; +import { logger } from "../utils/logger.js"; +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +export function getPollingSubscriber(provider, event) { + if (event === "block") { + return new PollingBlockSubscriber(provider); + } + if (isHexString(event, 32)) { + return new PollingTransactionSubscriber(provider, event); + } + return logger.throwError("unsupported polling event", "UNSUPPORTED_OPERATION", { + operation: "getPollingSubscriber", info: { event } + }); +} +// @TODO: refactor this +export class PollingBlockSubscriber { + #provider; + #poller; + #interval; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + constructor(provider) { + this.#provider = provider; + this.#poller = null; + this.#interval = 4000; + this.#blockNumber = -2; + } + get pollingInterval() { return this.#interval; } + set pollingInterval(value) { this.#interval = value; } + async #poll() { + const blockNumber = await this.#provider.getBlockNumber(); + if (this.#blockNumber === -2) { + this.#blockNumber = blockNumber; + return; + } + // @TODO: Put a cap on the maximum number of events per loop? + if (blockNumber !== this.#blockNumber) { + for (let b = this.#blockNumber + 1; b <= blockNumber; b++) { + this.#provider.emit("block", b); + } + this.#blockNumber = blockNumber; + } + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + start() { + if (this.#poller) { + throw new Error("subscriber already running"); + } + this.#poll(); + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + stop() { + if (!this.#poller) { + throw new Error("subscriber not running"); + } + this.#provider._clearTimeout(this.#poller); + this.#poller = null; + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +export class OnBlockSubscriber { + #provider; + #poll; + constructor(provider) { + this.#provider = provider; + this.#poll = (blockNumber) => { + this._poll(blockNumber, this.#provider); + }; + } + async _poll(blockNumber, provider) { + throw new Error("sub-classes must override this"); + } + start() { + this.#poll(-2); + this.#provider.on("block", this.#poll); + } + stop() { + this.#provider.off("block", this.#poll); + } + pause(dropWhilePaused) { this.stop(); } + resume() { this.start(); } +} +export class PollingOrphanSubscriber extends OnBlockSubscriber { + #filter; + constructor(provider, filter) { + super(provider); + this.#filter = copy(filter); + } + async _poll(blockNumber, provider) { + throw new Error("@TODO"); + console.log(this.#filter); + } +} +export class PollingTransactionSubscriber extends OnBlockSubscriber { + #hash; + constructor(provider, hash) { + super(provider); + this.#hash = hash; + } + async _poll(blockNumber, provider) { + const tx = await provider.getTransactionReceipt(this.#hash); + if (tx) { + provider.emit(this.#hash, tx); + } + } +} +export class PollingEventSubscriber { + #provider; + #filter; + #poller; + // The most recent block we have scanned for events. The value -2 + // indicates we still need to fetch an initial block number + #blockNumber; + constructor(provider, filter) { + this.#provider = provider; + this.#filter = copy(filter); + this.#poller = this.#poll.bind(this); + this.#blockNumber = -2; + } + async #poll(blockNumber) { + // The initial block hasn't been determined yet + if (this.#blockNumber === -2) { + return; + } + const filter = copy(this.#filter); + filter.fromBlock = this.#blockNumber + 1; + filter.toBlock = blockNumber; + const logs = await this.#provider.getLogs(filter); + // No logs could just mean the node has not indexed them yet, + // so we keep a sliding window of 60 blocks to keep scanning + if (logs.length === 0) { + if (this.#blockNumber < blockNumber - 60) { + this.#blockNumber = blockNumber - 60; + } + return; + } + this.#blockNumber = blockNumber; + for (const log of logs) { + this.#provider.emit(this.#filter, log); + } + } + start() { + if (this.#blockNumber === -2) { + this.#provider.getBlockNumber().then((blockNumber) => { + this.#blockNumber = blockNumber; + }); + } + this.#provider.on("block", this.#poller); + } + stop() { + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); + } +} +//# sourceMappingURL=subscriber-polling.js.map \ No newline at end of file diff --git a/lib.esm/providers/subscriber-polling.js.map b/lib.esm/providers/subscriber-polling.js.map new file mode 100644 index 000000000..fb2cf27f7 --- /dev/null +++ b/lib.esm/providers/subscriber-polling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-polling.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber-polling.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAI/C,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,SAAS,IAAI,CAAC,GAAQ;IAClB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,QAA0B,EAAE,KAAoB;IACjF,IAAI,KAAK,KAAK,OAAO,EAAE;QAAE,OAAO,IAAI,sBAAsB,CAAC,QAAQ,CAAC,CAAC;KAAE;IACvE,IAAI,WAAW,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE;QAAE,OAAO,IAAI,4BAA4B,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;KAAE;IAEzF,OAAO,MAAM,CAAC,UAAU,CAAC,2BAA2B,EAAE,uBAAuB,EAAE;QAC3E,SAAS,EAAE,sBAAsB,EAAE,IAAI,EAAE,EAAE,KAAK,E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AC,WAAW,EAAE,EAAE;gBACjD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;YACpC,CAAC,CAAC,CAAC;SACN;QACD,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI;QACA,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,eAAyB;QAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,IAAI,eAAe,EAAE;YAAE,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;SAAE;IACpD,CAAC;IAED,MAAM;QACF,IAAI,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/subscriber.js b/lib.esm/providers/subscriber.js new file mode 100644 index 000000000..b5d01060f --- /dev/null +++ b/lib.esm/providers/subscriber.js @@ -0,0 +1,57 @@ +"use strict"; +/* +import { defineProperties } from "@ethersproject/properties"; +export type EventCommon = "block" | "debug" | "blockObject"; + +export type Event = EventCommon | string | { address?: string, topics: Array> } + +export type EventLike = Event | Array; + +export function getTag(eventName: Event): string { + if (typeof(eventName) === "string") { return eventName; } + + if (typeof(eventName) === "object") { + return (eventName.address || "*") + (eventName.topics || []).map((topic) => { + if (typeof(topic) === "string") { return topic; } + return topic.join("|"); + }).join("&"); + } + + throw new Error("FOO"); +} + +export function getEvent(tag: string): Event { +} + +let nextId = 1; + +export class Subscriber { + readonly id!: number; + readonly tag!: string; + + #paused: boolean; + #blockNumber: number; + + constructor(tag: string) { + this.#paused = false; + this.#blockNumber = -1; + defineProperties(this, { id: nextId++, tag }); + } + + get blockNumber(): number { + return this.#blockNumber; + } + _setBlockNumber(blockNumber: number): void { this.#blockNumber = blockNumber; } + + setup(): void { } + teardown(): void { } + + isPaused(): boolean { return this.#paused; } + pause(): void { this.#paused = true; } + resume(): void { this.#paused = false; } + + resubscribeInfo(): string { return this.tag; } + resubscribe(info: string): boolean { return true; } +} +*/ +//# sourceMappingURL=subscriber.js.map \ No newline at end of file diff --git a/lib.esm/providers/subscriber.js.map b/lib.esm/providers/subscriber.js.map new file mode 100644 index 000000000..d30b7a493 --- /dev/null +++ b/lib.esm/providers/subscriber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber.js","sourceRoot":"","sources":["../../src.ts/providers/subscriber.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsDE"} \ No newline at end of file diff --git a/lib.esm/providers/ws-browser.js b/lib.esm/providers/ws-browser.js new file mode 100644 index 000000000..df9584d2c --- /dev/null +++ b/lib.esm/providers/ws-browser.js @@ -0,0 +1,16 @@ +function getGlobal() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + throw new Error('unable to locate global object'); +} +; +const _WebSocket = getGlobal().WebSocket; +export { _WebSocket as WebSocket }; +//# sourceMappingURL=ws-browser.js.map \ No newline at end of file diff --git a/lib.esm/providers/ws-browser.js.map b/lib.esm/providers/ws-browser.js.map new file mode 100644 index 000000000..e23187e89 --- /dev/null +++ b/lib.esm/providers/ws-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws-browser.js","sourceRoot":"","sources":["../../src.ts/providers/ws-browser.ts"],"names":[],"mappings":"AACA,SAAS,SAAS;IAChB,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IACjD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAAE,OAAO,MAAM,CAAC;KAAE;IACrD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QAAE,OAAO,MAAM,CAAC;KAAE;IACrD,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,CAAC;AAAA,CAAC;AAEF,MAAM,UAAU,GAAG,SAAS,EAAE,CAAC,SAAS,CAAC;AAEzC,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/ws.js b/lib.esm/providers/ws.js new file mode 100644 index 000000000..3fcc8f78b --- /dev/null +++ b/lib.esm/providers/ws.js @@ -0,0 +1,2 @@ +export { WebSocket } from "ws"; +//# sourceMappingURL=ws.js.map \ No newline at end of file diff --git a/lib.esm/providers/ws.js.map b/lib.esm/providers/ws.js.map new file mode 100644 index 000000000..717e091c5 --- /dev/null +++ b/lib.esm/providers/ws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../src.ts/providers/ws.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC"} \ No newline at end of file diff --git a/lib.esm/transaction/accesslist.js b/lib.esm/transaction/accesslist.js new file mode 100644 index 000000000..a60bbe6a7 --- /dev/null +++ b/lib.esm/transaction/accesslist.js @@ -0,0 +1,38 @@ +import { getAddress } from "../address/index.js"; +import { dataLength } from "../utils/index.js"; +function accessSetify(addr, storageKeys) { + return { + address: getAddress(addr), + storageKeys: (storageKeys || []).map((storageKey, index) => { + if (dataLength(storageKey) !== 32) { + //logger.throwArgumentError("invalid access list storageKey", `accessList[${ addr }> + throw new Error(""); + } + return storageKey.toLowerCase(); + }) + }; +} +export function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index) => { + if (Array.isArray(set)) { + if (set.length > 2) { + //logger.throwArgumentError("access list expected to be [ address, storageKeys[> + throw new Error(""); + } + return accessSetify(set[0], set[1]); + } + return accessSetify(set.address, set.storageKeys); + }); + } + const result = Object.keys(value).map((addr) => { + const storageKeys = value[addr].reduce((accum, storageKey) => { + accum[storageKey] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); + }); + result.sort((a, b) => (a.address.localeCompare(b.address))); + return result; +} +//# sourceMappingURL=accesslist.js.map \ No newline at end of file diff --git a/lib.esm/transaction/accesslist.js.map b/lib.esm/transaction/accesslist.js.map new file mode 100644 index 000000000..0f214e8e3 --- /dev/null +++ b/lib.esm/transaction/accesslist.js.map @@ -0,0 +1 @@ +{"version":3,"file":"accesslist.js","sourceRoot":"","sources":["../../src.ts/transaction/accesslist.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,SAAS,YAAY,CAAC,IAAY,EAAE,WAA0B;IAC1D,OAAO;QACH,OAAO,EAAE,UAAU,CAAC,IAAI,CAAC;QACzB,WAAW,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE;YACvD,IAAI,UAAU,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE;gBAC/B,oFAAoF;gBACpF,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;aACvB;YACD,OAAO,UAAU,CAAC,WAAW,EAAE,CAAC;QACpC,CAAC,CAAC;KACL,CAAC;AACN,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAAoB;IAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACtB,OAA0F,KAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YAChH,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;gBACpB,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE;oBAChB,gFAAgF;oBAChF,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;iBACvB;gBACD,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;aACtC;YACD,OAAO,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;KACN;IAED,MAAM,MAAM,GAA2D,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACnG,MAAM,WAAW,GAAyB,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE;YAC/E,KAAK,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;YACzB,OAAO,KAAK,CAAC;QACjB,CAAC,EAAwB,EAAG,CAAC,CAAC;QAC9B,OAAO,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;IAC9D,CAAC,CAAC,CAAC;IACH,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/lib.esm/transaction/address.js b/lib.esm/transaction/address.js new file mode 100644 index 000000000..c824563dc --- /dev/null +++ b/lib.esm/transaction/address.js @@ -0,0 +1,10 @@ +import { getAddress } from "../address/index.js"; +import { keccak256, SigningKey } from "../crypto/index.js"; +export function computeAddress(key) { + const publicKey = SigningKey.computePublicKey(key, false); + return getAddress(keccak256("0x" + publicKey.substring(4)).substring(26)); +} +export function recoverAddress(digest, signature) { + return computeAddress(SigningKey.recoverPublicKey(digest, signature)); +} +//# sourceMappingURL=address.js.map \ No newline at end of file diff --git a/lib.esm/transaction/address.js.map b/lib.esm/transaction/address.js.map new file mode 100644 index 000000000..43ce1ccf7 --- /dev/null +++ b/lib.esm/transaction/address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"address.js","sourceRoot":"","sources":["../../src.ts/transaction/address.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAM3D,MAAM,UAAU,cAAc,CAAC,GAAW;IACtC,MAAM,SAAS,GAAG,UAAU,CAAC,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAC1D,OAAO,UAAU,CAAC,SAAS,CAAC,IAAI,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;AAC9E,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,MAAiB,EAAE,SAAwB;IACtE,OAAO,cAAc,CAAC,UAAU,CAAC,gBAAgB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/lib.esm/transaction/index.js b/lib.esm/transaction/index.js new file mode 100644 index 000000000..5b1d3d3d6 --- /dev/null +++ b/lib.esm/transaction/index.js @@ -0,0 +1,4 @@ +export { accessListify } from "./accesslist.js"; +export { computeAddress, recoverAddress } from "./address.js"; +export { Transaction } from "./transaction.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/transaction/index.js.map b/lib.esm/transaction/index.js.map new file mode 100644 index 000000000..0807c24ae --- /dev/null +++ b/lib.esm/transaction/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/transaction/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"} \ 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 000000000..e1e4919a5 --- /dev/null +++ b/lib.esm/transaction/transaction.js @@ -0,0 +1,575 @@ +import { getAddress } from "../address/index.js"; +import { keccak256, Signature } from "../crypto/index.js"; +import { concat, decodeRlp, encodeRlp, getStore, hexlify, logger, setStore, toArray, zeroPadValue } from "../utils/index.js"; +import { accessListify } from "./accesslist.js"; +import { recoverAddress } from "./address.js"; +const BN_0 = BigInt(0); +const BN_2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +function handleAddress(value) { + if (value === "0x") { + return null; + } + return getAddress(value); +} +function handleData(value, param) { + try { + return hexlify(value); + } + catch (error) { + return logger.throwArgumentError("invalid data", param, value); + } +} +function handleAccessList(value, param) { + try { + return accessListify(value); + } + catch (error) { + return logger.throwArgumentError("invalid accessList", param, value); + } +} +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; + } + return logger.getNumber(_value, param); +} +function handleUint(_value, param) { + if (_value === "0x") { + return BN_0; + } + const value = logger.getBigInt(_value, param); + if (value > BN_MAX_UINT) { + logger.throwArgumentError("value exceeds uint size", param, value); + } + return value; +} +function formatNumber(_value, name) { + const value = logger.getBigInt(_value, "value"); + const result = toArray(value); + if (result.length > 32) { + logger.throwArgumentError(`value too large`, `tx.${name}`, value); + } + return result; +} +function formatAccessList(value) { + return accessListify(value).map((set) => [set.address, set.storageKeys]); +} +function _parseLegacy(data) { + const fields = decodeRlp(data); + if (!Array.isArray(fields) || (fields.length !== 9 && fields.length !== 6)) { + return logger.throwArgumentError("invalid field count for legacy transaction", "data", data); + } + const tx = { + type: 0, + nonce: handleNumber(fields[0], "nonce"), + gasPrice: handleUint(fields[1], "gasPrice"), + gasLimit: handleUint(fields[2], "gasLimit"), + to: handleAddress(fields[3]), + value: handleUint(fields[4], "value"), + data: handleData(fields[5], "dta"), + chainId: BN_0 + }; + // Legacy unsigned transaction + if (fields.length === 6) { + return tx; + } + const v = handleUint(fields[6], "v"); + const r = handleUint(fields[7], "r"); + const s = handleUint(fields[8], "s"); + if (r === BN_0 && s === BN_0) { + // EIP-155 unsigned transaction + tx.chainId = v; + } + else { + // Compute the EIP-155 chain ID (or 0 for legacy) + let chainId = (v - BN_35) / BN_2; + if (chainId < BN_0) { + chainId = BN_0; + } + tx.chainId = chainId; + // Signed Legacy Transaction + if (chainId === BN_0 && (v < BN_27 || v > BN_28)) { + logger.throwArgumentError("non-canonical legacy v", "v", fields[6]); + } + tx.signature = Signature.from({ + r: zeroPadValue(fields[7], 32), + s: zeroPadValue(fields[8], 32), + v + }); + tx.hash = keccak256(data); + } + return tx; +} +function _serializeLegacy(tx, sig) { + const fields = [ + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? getAddress(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + ]; + let chainId = BN_0; + if (tx.chainId != null) { + // A chainId was provided; if non-zero we'll use EIP-155 + chainId = logger.getBigInt(tx.chainId, "tx.chainId"); + // We have a chainId in the tx and an EIP-155 v in the signature, + // make sure they agree with each other + if (sig && sig.networkV != null && sig.legacyChainId !== chainId) { + logger.throwArgumentError("tx.chainId/sig.v mismatch", "sig", sig); + } + } + else if (sig) { + // No chainId provided, but the signature is signing with EIP-155; derive chainId + const legacy = sig.legacyChainId; + if (legacy != null) { + chainId = legacy; + } + } + // Requesting an unsigned transaction + if (!sig) { + // We have an EIP-155 transaction (chainId was specified and non-zero) + if (chainId !== BN_0) { + fields.push(toArray(chainId)); + fields.push("0x"); + fields.push("0x"); + } + return encodeRlp(fields); + } + // We pushed a chainId and null r, s on for hashing only; remove those + let v = BigInt(27 + sig.yParity); + if (chainId !== BN_0) { + v = Signature.getChainIdV(chainId, sig.v); + } + else if (BigInt(sig.v) !== v) { + logger.throwArgumentError("tx.chainId/sig.v mismatch", "sig", sig); + } + fields.push(toArray(v)); + fields.push(toArray(sig.r)); + fields.push(toArray(sig.s)); + return encodeRlp(fields); +} +function _parseEipSignature(tx, fields, serialize) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } + catch (error) { + return logger.throwArgumentError("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 _parseEip1559(data) { + const fields = decodeRlp(logger.getBytes(data).slice(1)); + if (!Array.isArray(fields) || (fields.length !== 9 && fields.length !== 12)) { + logger.throwArgumentError("invalid field count for transaction type: 2", "data", hexlify(data)); + } + const maxPriorityFeePerGas = handleUint(fields[2], "maxPriorityFeePerGas"); + const maxFeePerGas = handleUint(fields[3], "maxFeePerGas"); + const tx = { + type: 2, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: maxPriorityFeePerGas, + maxFeePerGas: maxFeePerGas, + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: handleData(fields[7], "data"), + accessList: handleAccessList(fields[8], "accessList"), + }; + // Unsigned EIP-1559 Transaction + if (fields.length === 9) { + return tx; + } + tx.hash = keccak256(data); + _parseEipSignature(tx, fields.slice(9), _serializeEip1559); + return tx; +} +function _serializeEip1559(tx, sig) { + const fields = [ + formatNumber(tx.chainId || 0, "chainId"), + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? getAddress(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + (formatAccessList(tx.accessList || [])) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push(toArray(sig.r)); + fields.push(toArray(sig.s)); + } + return concat(["0x02", encodeRlp(fields)]); +} +function _parseEip2930(data) { + const fields = decodeRlp(logger.getBytes(data).slice(1)); + if (!Array.isArray(fields) || (fields.length !== 8 && fields.length !== 11)) { + logger.throwArgumentError("invalid field count for transaction type: 1", "data", hexlify(data)); + } + const tx = { + type: 1, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + gasPrice: handleUint(fields[2], "gasPrice"), + gasLimit: handleUint(fields[3], "gasLimit"), + to: handleAddress(fields[4]), + value: handleUint(fields[5], "value"), + data: handleData(fields[6], "data"), + accessList: handleAccessList(fields[7], "accessList") + }; + // Unsigned EIP-2930 Transaction + if (fields.length === 8) { + return tx; + } + tx.hash = keccak256(data); + _parseEipSignature(tx, fields.slice(8), _serializeEip2930); + return tx; +} +function _serializeEip2930(tx, sig) { + const fields = [ + formatNumber(tx.chainId || 0, "chainId"), + formatNumber(tx.nonce || 0, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit || 0, "gasLimit"), + ((tx.to != null) ? getAddress(tx.to) : "0x"), + formatNumber(tx.value || 0, "value"), + (tx.data || "0x"), + (formatAccessList(tx.accessList || [])) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "recoveryParam")); + fields.push(toArray(sig.r)); + fields.push(toArray(sig.s)); + } + return concat(["0x01", encodeRlp(fields)]); +} +export class Transaction { + #props; + // A type of null indicates the type will be populated automatically + get type() { return getStore(this.#props, "type"); } + get typeName() { + switch (this.type) { + case 0: return "legacy"; + case 1: return "eip-2930"; + case 2: return "eip-1559"; + } + return null; + } + set type(value) { + switch (value) { + case null: + setStore(this.#props, "type", null); + break; + case 0: + case "legacy": + setStore(this.#props, "type", 0); + break; + case 1: + case "berlin": + case "eip-2930": + setStore(this.#props, "type", 1); + break; + case 2: + case "london": + case "eip-1559": + setStore(this.#props, "type", 2); + break; + default: + throw new Error(`unsupported transaction type`); + } + } + get to() { return getStore(this.#props, "to"); } + set to(value) { + setStore(this.#props, "to", (value == null) ? null : getAddress(value)); + } + get nonce() { return getStore(this.#props, "nonce"); } + set nonce(value) { setStore(this.#props, "nonce", logger.getNumber(value, "value")); } + get gasLimit() { return getStore(this.#props, "gasLimit"); } + set gasLimit(value) { setStore(this.#props, "gasLimit", logger.getBigInt(value)); } + get gasPrice() { + const value = getStore(this.#props, "gasPrice"); + if (value == null && (this.type === 0 || this.type === 1)) { + return BN_0; + } + return value; + } + set gasPrice(value) { + setStore(this.#props, "gasPrice", (value == null) ? null : logger.getBigInt(value, "gasPrice")); + } + get maxPriorityFeePerGas() { + const value = getStore(this.#props, "maxPriorityFeePerGas"); + if (value == null && this.type === 2) { + return BN_0; + } + return value; + } + set maxPriorityFeePerGas(value) { + setStore(this.#props, "maxPriorityFeePerGas", (value == null) ? null : logger.getBigInt(value, "maxPriorityFeePerGas")); + } + get maxFeePerGas() { + const value = getStore(this.#props, "maxFeePerGas"); + if (value == null && this.type === 2) { + return BN_0; + } + return value; + } + set maxFeePerGas(value) { + setStore(this.#props, "maxFeePerGas", (value == null) ? null : logger.getBigInt(value, "maxFeePerGas")); + } + get data() { return getStore(this.#props, "data"); } + set data(value) { setStore(this.#props, "data", hexlify(value)); } + get value() { return getStore(this.#props, "value"); } + set value(value) { + setStore(this.#props, "value", logger.getBigInt(value, "value")); + } + get chainId() { return getStore(this.#props, "chainId"); } + set chainId(value) { setStore(this.#props, "chainId", logger.getBigInt(value)); } + get signature() { return getStore(this.#props, "sig") || null; } + set signature(value) { + setStore(this.#props, "sig", (value == null) ? null : Signature.from(value)); + } + get accessList() { + const value = getStore(this.#props, "accessList") || null; + if (value == null && (this.type === 1 || this.type === 2)) { + return []; + } + return value; + } + set accessList(value) { + setStore(this.#props, "accessList", (value == null) ? null : accessListify(value)); + } + constructor() { + this.#props = { + type: null, + to: null, + nonce: 0, + gasLimit: BigInt(0), + gasPrice: null, + maxPriorityFeePerGas: null, + maxFeePerGas: null, + data: "0x", + value: BigInt(0), + chainId: BigInt(0), + sig: null, + accessList: null + }; + } + get hash() { + if (this.signature == null) { + throw new Error("cannot hash unsigned transaction; maybe you meant .unsignedHash"); + } + return keccak256(this.serialized); + } + get unsignedHash() { + return keccak256(this.unsignedSerialized); + } + get from() { + if (this.signature == null) { + return null; + } + return recoverAddress(this.unsignedSerialized, this.signature); + } + get fromPublicKey() { + if (this.signature == null) { + return null; + } + // use ecrecover + return ""; + } + isSigned() { + return this.signature != null; + } + get serialized() { + if (this.signature == null) { + throw new Error("cannot serialize unsigned transaction; maybe you meant .unsignedSerialized"); + } + const types = this.inferTypes(); + if (types.length !== 1) { + throw new Error("cannot determine transaction type; specify type manually"); + } + switch (types[0]) { + case 0: + return _serializeLegacy(this, this.signature); + case 1: + return _serializeEip2930(this, this.signature); + case 2: + return _serializeEip1559(this, this.signature); + } + throw new Error("unsupported type"); + } + get unsignedSerialized() { + const types = this.inferTypes(); + if (types.length !== 1) { + throw new Error("cannot determine transaction type; specify type manually"); + } + switch (types[0]) { + case 0: + return _serializeLegacy(this); + case 1: + return _serializeEip2930(this); + case 2: + return _serializeEip1559(this); + } + throw new Error("unsupported type"); + } + // Validates properties and lists possible types this transaction adheres to + inferTypes() { + // Checks that there are no conflicting properties set + const hasGasPrice = this.gasPrice != null; + const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != 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) { + if (this.maxFeePerGas < this.maxPriorityFeePerGas) { + throw new Error("priorityFee cannot be more than maxFee"); + } + } + //if (this.type === 2 && hasGasPrice) { + // throw new Error("eip-1559 transaction cannot have gasPrice"); + //} + if ((this.type === 0 || this.type === 1) && hasFee) { + throw new Error("transaction type cannot have maxFeePerGas or maxPriorityFeePerGas"); + } + if (this.type === 0 && hasAccessList) { + throw new Error("legacy transaction cannot have accessList"); + } + const types = []; + // Explicit type + if (this.type != null) { + types.push(this.type); + } + else { + if (hasFee) { + types.push(2); + } + else if (hasGasPrice) { + types.push(1); + if (!hasAccessList) { + types.push(0); + } + } + else if (hasAccessList) { + types.push(1); + types.push(2); + } + else { + types.push(0); + types.push(1); + types.push(2); + } + } + types.sort(); + return types; + } + isLegacy() { return (this.type === 0); } + isBerlin() { return (this.type === 1); } + isLondon() { return (this.type === 2); } + clone() { + return Transaction.from(this); + } + freeze() { + if (this.#props.sig) { + this.#props.sig = (this.#props.sig.clone().freeze()); + } + if (this.#props.accessList) { + this.#props.accessList = Object.freeze(this.#props.accessList.map((set) => { + Object.freeze(set.storageKeys); + return Object.freeze(set); + })); + } + Object.freeze(this.#props); + return this; + } + isFrozen() { + return Object.isFrozen(this.#props); + } + static from(tx) { + if (typeof (tx) === "string") { + const payload = logger.getBytes(tx); + if (payload[0] >= 0x7f) { // @TODO: > vs >= ?? + return Transaction.from(_parseLegacy(payload)); + } + switch (payload[0]) { + case 1: return Transaction.from(_parseEip2930(payload)); + case 2: return Transaction.from(_parseEip1559(payload)); + } + throw new Error("unsupported transaction type"); + } + const result = new Transaction(); + 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.gasPrice != null) { + result.gasPrice = tx.gasPrice; + } + 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.hash != null) { + if (result.isSigned()) { + if (result.hash !== tx.hash) { + throw new Error("hash mismatch"); + } + } + else { + throw new Error("unsigned transaction cannot have a hashs"); + } + } + if (tx.from != null) { + if (result.isSigned()) { + if (result.from.toLowerCase() !== (tx.from || "").toLowerCase()) { + throw new Error("from mismatch"); + } + } + else { + throw new Error("unsigned transaction cannot have a from"); + } + } + 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 000000000..cfb75ea20 --- /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,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EACH,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAC3F,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAQ9C,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAA;AACxB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAA;AACxB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,WAAW,GAAG,MAAM,CAAC,oEAAoE,CAAC,CAAC;AA2BjG,SAAS,aAAa,CAAC,KAAa;IAChC,IAAI,KAAK,KAAK,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IACpC,OAAO,UAAU,CAAC,KAAK,CAAC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AK,CAAC,eAAe,CAAC,CAAC;iBAAE;aACrE;iBAAM;gBACH,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;aAC/D;SACJ;QAED,IAAI,EAAE,CAAC,IAAI,IAAI,IAAI,EAAE;YACjB,IAAI,MAAM,CAAC,QAAQ,EAAE,EAAE;gBACnB,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE;oBAAE,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;iBAAE;aACzG;iBAAM;gBACH,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;aAC9D;SACJ;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/utils/base58.js b/lib.esm/utils/base58.js new file mode 100644 index 000000000..ef45e8109 --- /dev/null +++ b/lib.esm/utils/base58.js @@ -0,0 +1,43 @@ +import { logger } from "./logger.js"; +import { toBigInt, toHex } from "./maths.js"; +const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +let Lookup = null; +function getAlpha(letter) { + if (Lookup == null) { + Lookup = {}; + for (let i = 0; i < Alphabet.length; i++) { + Lookup[Alphabet[i]] = BigInt(i); + } + } + const result = Lookup[letter]; + if (result == null) { + logger.throwArgumentError(`invalid base58 value`, "letter", letter); + } + return result; +} +const BN_0 = BigInt(0); +const BN_58 = BigInt(58); +/** + * Encode %%value%% as Base58-encoded data. + */ +export function encodeBase58(_value) { + let value = toBigInt(logger.getBytes(_value)); + let result = ""; + while (value) { + result = Alphabet[Number(value % BN_58)] + result; + value /= BN_58; + } + return result; +} +/** + * Decode the Base58-encoded %%value%%. + */ +export function decodeBase58(value) { + let result = BN_0; + for (let i = 0; i < value.length; i++) { + result *= BN_58; + result += getAlpha(value[i]); + } + return toHex(result); +} +//# sourceMappingURL=base58.js.map \ No newline at end of file diff --git a/lib.esm/utils/base58.js.map b/lib.esm/utils/base58.js.map new file mode 100644 index 000000000..1f653df40 --- /dev/null +++ b/lib.esm/utils/base58.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base58.js","sourceRoot":"","sources":["../../src.ts/utils/base58.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAK7C,MAAM,QAAQ,GAAG,4DAA4D,CAAC;AAC9E,IAAI,MAAM,GAAkC,IAAI,CAAC;AAEjD,SAAS,QAAQ,CAAC,MAAc;IAC5B,IAAI,MAAM,IAAI,IAAI,EAAE;QAChB,MAAM,GAAG,EAAG,CAAC;QACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;SACnC;KACJ;IACD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9B,IAAI,MAAM,IAAI,IAAI,EAAE;QAChB,MAAM,CAAC,kBAAkB,CAAC,sBAAsB,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;KACvE;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAGD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,KAAK,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzB;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC1C,IAAI,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC9C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,OAAO,KAAK,EAAE;QACV,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC;QAClD,KAAK,IAAI,KAAK,CAAC;KAClB;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa;IACtC,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,MAAM,IAAI,KAAK,CAAC;QAChB,MAAM,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KAChC;IACD,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/base64-browser.js b/lib.esm/utils/base64-browser.js new file mode 100644 index 000000000..66bf24a47 --- /dev/null +++ b/lib.esm/utils/base64-browser.js @@ -0,0 +1,19 @@ +// utils/base64-browser +import { logger } from "./logger.js"; +export function decodeBase64(textData) { + textData = atob(textData); + const data = new Uint8Array(textData.length); + for (let i = 0; i < textData.length; i++) { + data[i] = textData.charCodeAt(i); + } + return logger.getBytes(data); +} +export function encodeBase64(_data) { + const data = logger.getBytes(_data); + let textData = ""; + for (let i = 0; i < data.length; i++) { + textData += String.fromCharCode(data[i]); + } + return btoa(textData); +} +//# sourceMappingURL=base64-browser.js.map \ No newline at end of file diff --git a/lib.esm/utils/base64-browser.js.map b/lib.esm/utils/base64-browser.js.map new file mode 100644 index 000000000..31e3e11c4 --- /dev/null +++ b/lib.esm/utils/base64-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64-browser.js","sourceRoot":"","sources":["../../src.ts/utils/base64-browser.ts"],"names":[],"mappings":"AACA,uBAAuB;AAEvB,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,MAAM,UAAU,YAAY,CAAC,QAAgB;IACzC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1B,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,IAAI,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;KACpC;IACD,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,KAAgB;IACzC,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAClC,QAAQ,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;KAC5C;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/base64.js b/lib.esm/utils/base64.js new file mode 100644 index 000000000..7bcb3ae67 --- /dev/null +++ b/lib.esm/utils/base64.js @@ -0,0 +1,9 @@ +import { logger } from "./logger.js"; +export function decodeBase64(textData) { + return logger.getBytesCopy(Buffer.from(textData, "base64")); +} +; +export function encodeBase64(data) { + return Buffer.from(logger.getBytes(data)).toString("base64"); +} +//# sourceMappingURL=base64.js.map \ No newline at end of file diff --git a/lib.esm/utils/base64.js.map b/lib.esm/utils/base64.js.map new file mode 100644 index 000000000..6ef991f5c --- /dev/null +++ b/lib.esm/utils/base64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64.js","sourceRoot":"","sources":["../../src.ts/utils/base64.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,MAAM,UAAU,YAAY,CAAC,QAAgB;IACzC,OAAO,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AAChE,CAAC;AAAA,CAAC;AAEF,MAAM,UAAU,YAAY,CAAC,IAAe;IACxC,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AACjE,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/data.js b/lib.esm/utils/data.js new file mode 100644 index 000000000..07df908a9 --- /dev/null +++ b/lib.esm/utils/data.js @@ -0,0 +1,77 @@ +import { logger } from "./logger.js"; +export function isHexString(value, length) { + if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (typeof (length) === "number" && value.length !== 2 + 2 * length) { + return false; + } + if (length === true && (value.length % 2) !== 0) { + return false; + } + return true; +} +export function isBytesLike(value) { + return (isHexString(value, true) || (value instanceof Uint8Array)); +} +const HexCharacters = "0123456789abcdef"; +export function hexlify(data) { + const bytes = logger.getBytes(data); + let result = "0x"; + for (let i = 0; i < bytes.length; i++) { + const v = bytes[i]; + result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; + } + return result; +} +export function concat(datas) { + return "0x" + datas.map((d) => hexlify(d).substring(2)).join(""); +} +export function dataLength(data) { + if (isHexString(data, true)) { + return (data.length - 2) / 2; + } + return logger.getBytes(data).length; +} +export function dataSlice(data, start, end) { + const bytes = logger.getBytes(data); + if (end != null && end > bytes.length) { + logger.throwError("cannot slice beyond data bounds", "BUFFER_OVERRUN", { + buffer: bytes, length: bytes.length, offset: end + }); + } + return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end)); +} +export function stripZerosLeft(data) { + let bytes = hexlify(data).substring(2); + while (bytes.substring(0, 2) == "00") { + bytes = bytes.substring(2); + } + return "0x" + bytes; +} +function zeroPad(data, length, left) { + const bytes = logger.getBytes(data); + if (length < bytes.length) { + logger.throwError("padding exceeds data length", "BUFFER_OVERRUN", { + buffer: new Uint8Array(bytes), + length: length, + offset: length + 1 + }); + } + const result = new Uint8Array(length); + result.fill(0); + if (left) { + result.set(bytes, length - bytes.length); + } + else { + result.set(bytes, 0); + } + return hexlify(result); +} +export function zeroPadValue(data, length) { + return zeroPad(data, length, true); +} +export function zeroPadBytes(data, length) { + return zeroPad(data, length, false); +} +//# sourceMappingURL=data.js.map \ No newline at end of file diff --git a/lib.esm/utils/data.js.map b/lib.esm/utils/data.js.map new file mode 100644 index 000000000..02492fd6e --- /dev/null +++ b/lib.esm/utils/data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"data.js","sourceRoot":"","sources":["../../src.ts/utils/data.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,MAAM,UAAU,WAAW,CAAC,KAAU,EAAE,MAAyB;IAC7D,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE;QAChE,OAAO,KAAK,CAAA;KACf;IAED,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE;QAAE,OAAO,KAAK,CAAC;KAAE;IACrF,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;KAAE;IAElE,OAAO,IAAI,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,KAAU;IAClC,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,YAAY,UAAU,CAAC,CAAC,CAAC;AACvE,CAAC;A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C,CAAC;KAC5C;SAAM;QACH,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;KACxB;IAED,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAe,EAAE,MAAc;IACxD,OAAO,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAe,EAAE,MAAc;IACxD,OAAO,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/errors.js b/lib.esm/utils/errors.js new file mode 100644 index 000000000..ccade6ab2 --- /dev/null +++ b/lib.esm/utils/errors.js @@ -0,0 +1,18 @@ +//export type TransactionReceipt { +//} +/** + * try { + * // code.... + * } catch (e) { + * if (isError(e, errors.CALL_EXCEPTION)) { + * console.log(e.data); + * } + * } + */ +export function isError(error, code) { + return (error && error.code === code); +} +export function isCallException(error) { + return isError(error, "CALL_EXCEPTION"); +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/lib.esm/utils/errors.js.map b/lib.esm/utils/errors.js.map new file mode 100644 index 000000000..01d195907 --- /dev/null +++ b/lib.esm/utils/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src.ts/utils/errors.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,GAAG;AA4QH;;;;;;;;GAQG;AACH,MAAM,UAAU,OAAO,CAAqD,KAAU,EAAE,IAAO;IAC3F,OAAO,CAAC,KAAK,IAAkB,KAAM,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAU;IACtC,OAAO,OAAO,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;AAC5C,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/events.js b/lib.esm/utils/events.js new file mode 100644 index 000000000..96240808c --- /dev/null +++ b/lib.esm/utils/events.js @@ -0,0 +1,17 @@ +import { defineProperties } from "./properties.js"; +export class EventPayload { + filter; + emitter; + #listener; + constructor(emitter, listener, filter) { + this.#listener = listener; + defineProperties(this, { emitter, filter }); + } + async removeListener() { + if (this.#listener == null) { + return; + } + await this.emitter.off(this.filter, this.#listener); + } +} +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/lib.esm/utils/events.js.map b/lib.esm/utils/events.js.map new file mode 100644 index 000000000..5074ebe92 --- /dev/null +++ b/lib.esm/utils/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src.ts/utils/events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAoBnD,MAAM,OAAO,YAAY;IACZ,MAAM,CAAK;IAEX,OAAO,CAAuB;IAC9B,SAAS,CAAkB;IAEpC,YAAY,OAA4B,EAAE,QAAyB,EAAE,MAAS;QAC1E,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,gBAAgB,CAAoB,IAAI,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IACnE,CAAC;IAED,KAAK,CAAC,cAAc;QAChB,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE;YAAE,OAAO;SAAE;QACvC,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/utils/fetch.js b/lib.esm/utils/fetch.js new file mode 100644 index 000000000..0d01a737b --- /dev/null +++ b/lib.esm/utils/fetch.js @@ -0,0 +1,562 @@ +import { decodeBase64, encodeBase64 } from "./base64.js"; +import { hexlify } from "./data.js"; +import { assertArgument, logger } from "./logger.js"; +import { defineProperties } from "./properties.js"; +import { toUtf8Bytes, toUtf8String } from "./utf8.js"; +import { getUrl } from "./geturl.js"; +const MAX_ATTEMPTS = 12; +const SLOT_INTERVAL = 250; +// The global FetchGetUrlFunc implementation. +let getUrlFunc = getUrl; +const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); +const reIpfs = new RegExp("^ipfs:/\/(ipfs/)?(.*)$", "i"); +// If locked, new Gateways cannot be added +let locked = false; +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs +async function gatewayData(url, signal) { + try { + const match = url.match(reData); + if (!match) { + throw new Error("invalid data"); + } + return new FetchResponse(200, "OK", { + "content-type": (match[1] || "text/plain"), + }, (match[1] ? decodeBase64(match[3]) : unpercent(match[3]))); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); + } +} +export function getIpfsGatewayFunc(base) { + async function gatewayIpfs(url, signal) { + try { + const match = url.match(reIpfs); + if (!match) { + throw new Error("invalid link"); + } + return new FetchRequest(`${base}${match[2]}`); + } + catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); + } + } + return gatewayIpfs; +} +const Gateways = { + "data": gatewayData, + "ipfs": getIpfsGatewayFunc("https:/\/gateway.ipfs.io/ipfs/") +}; +const fetchSignals = new WeakMap(); +export class FetchCancelSignal { + #listeners; + #cancelled; + constructor(request) { + this.#listeners = []; + this.#cancelled = false; + fetchSignals.set(request, () => { + if (this.#cancelled) { + return; + } + this.#cancelled = true; + for (const listener of this.#listeners) { + setTimeout(() => { listener(); }, 0); + } + this.#listeners = []; + }); + } + addListener(listener) { + if (this.#cancelled) { + logger.throwError("singal already cancelled", "UNSUPPORTED_OPERATION", { + operation: "fetchCancelSignal.addCancelListener" + }); + } + this.#listeners.push(listener); + } + get cancelled() { return this.cancelled; } + checkSignal() { + if (!this.cancelled) { + return; + } + logger.throwError("cancelled", "CANCELLED", {}); + } +} +// Check the signal, throwing if it is cancelled +function checkSignal(signal) { + if (signal == null) { + throw new Error("missing signal; should not happen"); + } + signal.checkSignal(); + return signal; +} +export class FetchRequest { + #allowInsecure; + #gzip; + #headers; + #method; + #timeout; + #url; + #body; + #bodyType; + #creds; + // Hooks + #preflight; + #process; + #retry; + #signal; + // URL + get url() { return this.#url; } + set url(url) { + this.#url = String(url); + } + // Body + get body() { + if (this.#body == null) { + return null; + } + return new Uint8Array(this.#body); + } + set body(body) { + if (body == null) { + this.#body = undefined; + this.#bodyType = undefined; + } + else if (typeof (body) === "string") { + this.#body = toUtf8Bytes(body); + this.#bodyType = "text/plain"; + } + else if (body instanceof Uint8Array) { + this.#body = body; + this.#bodyType = "application/octet-stream"; + } + else if (typeof (body) === "object") { + this.#body = toUtf8Bytes(JSON.stringify(body)); + this.#bodyType = "application/json"; + } + else { + throw new Error("invalid body"); + } + } + hasBody() { + return (this.#body != null); + } + // Method (default: GET with no body, POST with a body) + get method() { + if (this.#method) { + return this.#method; + } + if (this.hasBody()) { + return "POST"; + } + return "GET"; + } + set method(method) { + if (method == null) { + method = ""; + } + this.#method = String(method).toUpperCase(); + } + // Headers (automatically fills content-type if not explicitly set) + get headers() { + const headers = Object.assign({}, this.#headers); + if (this.#creds) { + headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`; + } + ; + if (this.allowGzip) { + headers["accept-encoding"] = "gzip"; + } + if (headers["content-type"] == null && this.#bodyType) { + headers["content-type"] = this.#bodyType; + } + if (this.body) { + headers["content-length"] = String(this.body.length); + } + return Object.freeze(headers); + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + setHeader(key, value) { + this.#headers[String(key).toLowerCase()] = String(value); + } + clearHeaders() { + this.#headers = {}; + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + // Configure an Authorization header + get credentials() { + return this.#creds || null; + } + setCredentials(username, password) { + if (username.match(/:/)) { + logger.throwArgumentError("invalid basic authentication username", "username", "[REDACTED]"); + } + this.#creds = `${username}:${password}`; + } + // Configure the request to allow gzipped responses + get allowGzip() { + return this.#gzip; + } + set allowGzip(value) { + this.#gzip = !!value; + } + // Allow credentials to be sent over an insecure (non-HTTPS) channel + get allowInsecureAuthentication() { + return !!this.#allowInsecure; + } + set allowInsecureAuthentication(value) { + this.#allowInsecure = !!value; + } + // Timeout (milliseconds) + get timeout() { return this.#timeout; } + set timeout(timeout) { + assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout); + this.#timeout = timeout; + } + // Preflight called before each request is sent + get preflightFunc() { + return this.#preflight || null; + } + set preflightFunc(preflight) { + this.#preflight = preflight; + } + // Preflight called before each request is sent + get processFunc() { + return this.#process || null; + } + set processFunc(process) { + this.#process = process; + } + // Preflight called before each request is sent + get retryFunc() { + return this.#retry || null; + } + set retryFunc(retry) { + this.#retry = retry; + } + constructor(url) { + this.#url = String(url); + this.#allowInsecure = false; + this.#gzip = false; + this.#headers = {}; + this.#method = ""; + this.#timeout = 300; + } + async #send(attempt, expires, delay, _request, _response) { + if (attempt >= MAX_ATTEMPTS) { + return _response.makeServerError("exceeded maximum retry limit"); + } + if (getTime() > expires) { + return logger.throwError("timeout", "TIMEOUT", { + operation: "request.send", reason: "timeout", request: _request + }); + } + if (delay > 0) { + await wait(delay); + } + let req = this.clone(); + const scheme = (req.url.split(":")[0] || "").toLowerCase(); + // Process any Gateways + if (scheme in Gateways) { + const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); + if (result instanceof FetchResponse) { + let response = result; + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Ignore throttling + } + } + return response; + } + req = result; + } + // We have a preflight function; update the request + if (this.preflightFunc) { + req = await this.preflightFunc(req); + } + const resp = await getUrlFunc(req, checkSignal(_request.#signal)); + let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); + if (response.statusCode === 301 || response.statusCode === 302) { + // Redirect + try { + const location = response.headers.location || ""; + return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); + } + catch (error) { } + // Things won't get any better on another attempt; abort + return response; + } + else if (response.statusCode === 429) { + // Throttle + if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) { + const retryAfter = response.headers["retry-after"]; + let delay = SLOT_INTERVAL * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + delay = parseInt(retryAfter); + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } + catch (error) { + // Something went wrong during processing; throw a 5xx server error + if (error.throttle == null || typeof (error.stall) !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } + // Throttle + let delay = SLOT_INTERVAL * Math.trunc(Math.random() * Math.pow(2, attempt)); + ; + if (error.stall >= 0) { + delay = error.stall; + } + return req.clone().#send(attempt + 1, expires, delay, _request, response); + } + } + return response; + } + send() { + if (this.#signal != null) { + return logger.throwError("request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); + } + this.#signal = new FetchCancelSignal(this); + return this.#send(0, getTime() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + } + cancel() { + if (this.#signal == null) { + return logger.throwError("request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); + } + const signal = fetchSignals.get(this); + if (!signal) { + throw new Error("missing signal; should not happen"); + } + signal(); + } + /** + * Returns a new [[FetchRequest]] that represents the redirection + * to %%location%%. + */ + redirect(location) { + // Redirection; for now we only support absolute locataions + const current = this.url.split(":")[0].toLowerCase(); + const target = location.split(":")[0].toLowerCase(); + // Don't allow redirecting: + // - non-GET requests + // - downgrading the security (e.g. https => http) + // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?] + if (this.method !== "GET" || (current === "https" && target === "http") || !location.match(/^https?:/)) { + return logger.throwError(`unsupported redirect`, "UNSUPPORTED_OPERATION", { + operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})` + }); + } + // Create a copy of this request, with a new URL + const req = new FetchRequest(location); + req.method = "GET"; + req.allowGzip = this.allowGzip; + req.timeout = this.timeout; + req.#headers = Object.assign({}, this.#headers); + if (this.#body) { + req.#body = new Uint8Array(this.#body); + } + req.#bodyType = this.#bodyType; + // Do not forward credentials unless on the same domain; only absolute + //req.allowInsecure = false; + // paths are currently supported; may want a way to specify to forward? + //setStore(req.#props, "creds", getStore(this.#pros, "creds")); + return req; + } + clone() { + const clone = new FetchRequest(this.url); + // Preserve "default method" (i.e. null) + clone.#method = this.#method; + // Preserve "default body" with type, copying the Uint8Array is present + if (this.#body) { + clone.#body = this.#body; + } + clone.#bodyType = this.#bodyType; + // Preserve "default headers" + clone.#headers = Object.assign({}, this.#headers); + // Credentials is readonly, so we copy internally + clone.#creds = this.#creds; + if (this.allowGzip) { + clone.allowGzip = true; + } + clone.timeout = this.timeout; + if (this.allowInsecureAuthentication) { + clone.allowInsecureAuthentication = true; + } + clone.#preflight = this.#preflight; + clone.#process = this.#process; + clone.#retry = this.#retry; + return clone; + } + static lockConfig() { + locked = true; + } + static getGateway(scheme) { + return Gateways[scheme.toLowerCase()] || null; + } + static registerGateway(scheme, func) { + scheme = scheme.toLowerCase(); + if (scheme === "http" || scheme === "https") { + throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); + } + if (locked) { + throw new Error("gateways locked"); + } + Gateways[scheme] = func; + } + static registerGetUrl(getUrl) { + if (locked) { + throw new Error("gateways locked"); + } + getUrlFunc = getUrl; + } +} +; +export class FetchResponse { + #statusCode; + #statusMessage; + #headers; + #body; + #request; + #error; + toString() { + return ``; + } + get statusCode() { return this.#statusCode; } + get statusMessage() { return this.#statusMessage; } + get headers() { return this.#headers; } + get body() { + return (this.#body == null) ? null : new Uint8Array(this.#body); + } + get bodyText() { + try { + return (this.#body == null) ? "" : toUtf8String(this.#body); + } + catch (error) { + return logger.throwError("response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { + operation: "bodyText", info: { response: this } + }); + } + } + get bodyJson() { + try { + return JSON.parse(this.bodyText); + } + catch (error) { + return logger.throwError("response body is not valid JSON", "UNSUPPORTED_OPERATION", { + operation: "bodyJson", info: { response: this } + }); + } + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: () => { + if (index < keys.length) { + const key = keys[index++]; + return { + value: [key, headers[key]], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + constructor(statusCode, statusMessage, headers, body, request) { + this.#statusCode = statusCode; + this.#statusMessage = statusMessage; + this.#headers = Object.freeze(Object.assign({}, Object.keys(headers).reduce((accum, k) => { + accum[k.toLowerCase()] = String(headers[k]); + return accum; + }, {}))); + this.#body = ((body == null) ? null : new Uint8Array(body)); + this.#request = (request || null); + this.#error = { message: "" }; + } + makeServerError(message, error) { + let statusMessage; + if (!message) { + message = `${this.statusCode} ${this.statusMessage}`; + statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; + } + else { + statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; + } + const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); + response.#error = { message, error }; + return response; + } + throwThrottleError(message, stall) { + if (stall == null) { + stall = -1; + } + else if (typeof (stall) !== "number" || !Number.isInteger(stall) || stall < 0) { + return logger.throwArgumentError("invalid stall timeout", "stall", stall); + } + const error = new Error(message || "throttling requests"); + defineProperties(error, { stall, throttle: true }); + throw error; + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + hasBody() { + return (this.#body != null); + } + get request() { return this.#request; } + ok() { + return (this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300); + } + assertOk() { + if (this.ok()) { + return; + } + let { message, error } = this.#error; + if (message === "") { + message = `server response ${this.statusCode} ${this.statusMessage}`; + } + logger.throwError(message, "SERVER_ERROR", { + request: (this.request || "unknown request"), response: this, error + }); + } +} +function getTime() { return (new Date()).getTime(); } +function unpercent(value) { + return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => { + return String.fromCharCode(parseInt(code, 16)); + })); +} +function wait(delay) { + return new Promise((resolve) => setTimeout(resolve, delay)); +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/lib.esm/utils/fetch.js.map b/lib.esm/utils/fetch.js.map new file mode 100644 index 000000000..e4672f7e2 --- /dev/null +++ b/lib.esm/utils/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src.ts/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAErD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA2CrC,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B,6CAA6C;AAC7C,IAAI,UAAU,GAAoB,MAAM,CAAC;AAEzC,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;AAClE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;AAEzD,0CAA0C;AAC1C,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB,6EAA6E;A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dev/null +++ b/lib.esm/utils/fixednumber.js @@ -0,0 +1,340 @@ +import { logger } from "./logger.js"; +import { fromTwos, toBigInt, toHex, toTwos } from "./maths.js"; +const _constructorGuard = {}; +const NegativeOne = BigInt(-1); +function throwFault(message, fault, operation, value) { + const params = { fault: fault, operation: operation }; + if (value !== undefined) { + params.value = value; + } + return logger.throwError(message, "NUMERIC_FAULT", params); +} +// Constant to pull zeros from for multipliers +let zeros = "0"; +while (zeros.length < 256) { + zeros += zeros; +} +// Returns a string "1" followed by decimal "0"s +function getMultiplier(decimals) { + if (typeof (decimals) !== "number" || decimals < 0 || decimals > 256 || decimals % 1) { + logger.throwArgumentError("invalid decimal length", "decimals", decimals); + } + return BigInt("1" + zeros.substring(0, decimals)); +} +export function formatFixed(_value, _decimals) { + if (_decimals == null) { + _decimals = 18; + } + let value = logger.getBigInt(_value, "value"); + const decimals = logger.getNumber(_decimals, "decimals"); + const multiplier = getMultiplier(decimals); + const multiplierStr = String(multiplier); + const negative = (value < 0); + if (negative) { + value *= NegativeOne; + } + let fraction = String(value % multiplier); + // Make sure there are enough place-holders + while (fraction.length < multiplierStr.length - 1) { + fraction = "0" + fraction; + } + // Strip training 0 + while (fraction.length > 1 && fraction.substring(fraction.length - 1) === "0") { + fraction = fraction.substring(0, fraction.length - 1); + } + let result = String(value / multiplier); + if (multiplierStr.length !== 1) { + result += "." + fraction; + } + if (negative) { + result = "-" + result; + } + return result; +} +export function parseFixed(value, _decimals) { + if (_decimals == null) { + _decimals = 18; + } + const decimals = logger.getNumber(_decimals, "decimals"); + const multiplier = getMultiplier(decimals); + if (typeof (value) !== "string" || !value.match(/^-?[0-9.]+$/)) { + logger.throwArgumentError("invalid decimal value", "value", value); + } + // Is it negative? + const negative = (value.substring(0, 1) === "-"); + if (negative) { + value = value.substring(1); + } + if (value === ".") { + logger.throwArgumentError("missing value", "value", value); + } + // Split it into a whole and fractional part + const comps = value.split("."); + if (comps.length > 2) { + logger.throwArgumentError("too many decimal points", "value", value); + } + let whole = (comps[0] || "0"), fraction = (comps[1] || "0"); + // Trim trialing zeros + while (fraction[fraction.length - 1] === "0") { + fraction = fraction.substring(0, fraction.length - 1); + } + // Check the fraction doesn't exceed our decimals size + if (fraction.length > String(multiplier).length - 1) { + throwFault("fractional component exceeds decimals", "underflow", "parseFixed"); + } + // If decimals is 0, we have an empty string for fraction + if (fraction === "") { + fraction = "0"; + } + // Fully pad the string with zeros to get to wei + while (fraction.length < String(multiplier).length - 1) { + fraction += "0"; + } + const wholeValue = BigInt(whole); + const fractionValue = BigInt(fraction); + let wei = (wholeValue * multiplier) + fractionValue; + if (negative) { + wei *= NegativeOne; + } + return wei; +} +export class FixedFormat { + signed; + width; + decimals; + name; + _multiplier; + constructor(constructorGuard, signed, width, decimals) { + if (constructorGuard !== _constructorGuard) { + logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", "UNSUPPORTED_OPERATION", { + operation: "new FixedFormat" + }); + } + this.signed = signed; + this.width = width; + this.decimals = decimals; + this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + this._multiplier = getMultiplier(decimals); + Object.freeze(this); + } + static from(value) { + if (value instanceof FixedFormat) { + return value; + } + if (typeof (value) === "number") { + value = `fixed128x${value}`; + } + let signed = true; + let width = 128; + let decimals = 18; + if (typeof (value) === "string") { + if (value === "fixed") { + // defaults... + } + else if (value === "ufixed") { + signed = false; + } + else { + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + if (!match) { + return logger.throwArgumentError("invalid fixed format", "format", value); + } + signed = (match[1] !== "u"); + width = parseInt(match[2]); + decimals = parseInt(match[3]); + } + } + else if (value) { + const check = (key, type, defaultValue) => { + if (value[key] == null) { + return defaultValue; + } + if (typeof (value[key]) !== type) { + logger.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]); + } + return value[key]; + }; + signed = check("signed", "boolean", signed); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); + } + if (width % 8) { + logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); + } + if (decimals > 80) { + logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); + } + return new FixedFormat(_constructorGuard, signed, width, decimals); + } +} +export class FixedNumber { + format; + _isFixedNumber; + //#hex: string; + #value; + constructor(constructorGuard, hex, value, format) { + if (constructorGuard !== _constructorGuard) { + logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", "UNSUPPORTED_OPERATION", { + operation: "new FixedFormat" + }); + } + this.format = FixedFormat.from(format); + //this.#hex = hex; + this.#value = value; + this._isFixedNumber = true; + Object.freeze(this); + } + #checkFormat(other) { + if (this.format.name !== other.format.name) { + logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other); + } + } + addUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue(a + b, this.format.decimals, this.format); + } + subUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue(a - b, this.format.decimals, this.format); + } + mulUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue((a * b) / this.format._multiplier, this.format.decimals, this.format); + } + divUnsafe(other) { + this.#checkFormat(other); + const a = parseFixed(this.#value, this.format.decimals); + const b = parseFixed(other.#value, other.format.decimals); + return FixedNumber.fromValue((a * this.format._multiplier) / b, this.format.decimals, this.format); + } + floor() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (this.isNegative() && hasFraction) { + result = result.subUnsafe(ONE.toFormat(result.format)); + } + return result; + } + ceiling() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (!this.isNegative() && hasFraction) { + result = result.addUnsafe(ONE.toFormat(result.format)); + } + return result; + } + // @TODO: Support other rounding algorithms + round(decimals) { + if (decimals == null) { + decimals = 0; + } + // If we are already in range, we're done + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + if (decimals < 0 || decimals > 80 || (decimals % 1)) { + logger.throwArgumentError("invalid decimal count", "decimals", decimals); + } + if (comps[1].length <= decimals) { + return this; + } + const factor = FixedNumber.from("1" + zeros.substring(0, decimals), this.format); + const bump = BUMP.toFormat(this.format); + return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor); + } + isZero() { + return (this.#value === "0.0" || this.#value === "0"); + } + isNegative() { + return (this.#value[0] === "-"); + } + toString() { return this.#value; } + toHexString(_width) { + throw new Error("TODO"); + /* + return toHex(); + if (width == null) { return this.#hex; } + + const width = logger.getNumeric(_width); + if (width % 8) { logger.throwArgumentError("invalid byte width", "width", width); } + + const hex = BigNumber.from(this.#hex).fromTwos(this.format.width).toTwos(width).toHexString(); + return zeroPadLeft(hex, width / 8); + */ + } + toUnsafeFloat() { return parseFloat(this.toString()); } + toFormat(format) { + return FixedNumber.fromString(this.#value, format); + } + static fromValue(value, decimals = 0, format = "fixed") { + return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format)); + } + static fromString(value, format = "fixed") { + const fixedFormat = FixedFormat.from(format); + const numeric = parseFixed(value, fixedFormat.decimals); + if (!fixedFormat.signed && numeric < 0) { + throwFault("unsigned value cannot be negative", "overflow", "value", value); + } + const hex = (function () { + if (fixedFormat.signed) { + return toHex(toTwos(numeric, fixedFormat.width)); + } + return toHex(numeric, fixedFormat.width / 8); + })(); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); + } + static fromBytes(_value, format = "fixed") { + const value = logger.getBytes(_value, "value"); + const fixedFormat = FixedFormat.from(format); + if (value.length > fixedFormat.width / 8) { + throw new Error("overflow"); + } + let numeric = toBigInt(value); + if (fixedFormat.signed) { + numeric = fromTwos(numeric, fixedFormat.width); + } + const hex = toHex(toTwos(numeric, (fixedFormat.signed ? 0 : 1) + fixedFormat.width)); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); + } + static from(value, format) { + if (typeof (value) === "string") { + return FixedNumber.fromString(value, format); + } + if (value instanceof Uint8Array) { + return FixedNumber.fromBytes(value, format); + } + try { + return FixedNumber.fromValue(value, 0, format); + } + catch (error) { + // Allow NUMERIC_FAULT to bubble up + if (error.code !== "INVALID_ARGUMENT") { + throw error; + } + } + return logger.throwArgumentError("invalid FixedNumber value", "value", value); + } + static isFixedNumber(value) { + return !!(value && value._isFixedNumber); + } +} +const ONE = FixedNumber.from(1); +const BUMP = FixedNumber.from("0.5"); +//# sourceMappingURL=fixednumber.js.map \ No newline at end of file diff --git a/lib.esm/utils/fixednumber.js.map b/lib.esm/utils/fixednumber.js.map new file mode 100644 index 000000000..4befc67c4 --- /dev/null +++ b/lib.esm/utils/fixednumber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fixednumber.js","sourceRoot":"","sources":["../../src.ts/utils/fixednumber.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAK/D,MAAM,iBAAiB,GAAG,EAAG,CAAC;AAE9B,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAE/B,SAAS,UAAU,CAAC,OAAe,EAAE,KAAa,EAAE,SAAiB,EAAE,KAAW;IAC9E,MAAM,MAAM,GAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;IAC3D,IAAI,KAAK,KAAK,SAAS,EAAE;QAAE,MAAM,CAAC,KAAK,GAAG,KAAK,C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AAC,CAAC,CAAC,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;QACpF,MAAM,OAAO,GAAG,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;QAE3D,OAAO,IAAI,WAAW,CAAC,iBAAiB,EAAE,GAAG,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IACzE,CAAC;IAED,MAAM,CAAC,IAAI,CAAC,KAAU,EAAE,MAAsC;QAC1D,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;YAC5B,OAAO,WAAW,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;SAChD;QAED,IAAI,KAAK,YAAY,UAAU,EAAE;YAC7B,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;SAC/C;QAED,IAAI;YACA,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;SAClD;QAAC,OAAO,KAAU,EAAE;YACjB,mCAAmC;YACnC,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAkB,EAAE;gBACnC,MAAM,KAAK,CAAC;aACf;SACJ;QAED,OAAO,MAAM,CAAC,kBAAkB,CAAC,2BAA2B,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,CAAC,aAAa,CAAC,KAAU;QAC3B,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;IAC7C,CAAC;CACJ;AAED,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/geturl-browser.js b/lib.esm/utils/geturl-browser.js new file mode 100644 index 000000000..a5bd077ec --- /dev/null +++ b/lib.esm/utils/geturl-browser.js @@ -0,0 +1,41 @@ +import { logger } from "./logger.js"; +// @TODO: timeout is completely ignored; start a Promise.any with a reject? +export async function getUrl(req, _signal) { + const protocol = req.url.split(":")[0].toLowerCase(); + if (protocol !== "http" && protocol !== "https") { + logger.throwError(`unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" + }); + } + if (req.credentials && !req.allowInsecureAuthentication) { + logger.throwError("insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + } + let signal = undefined; + if (_signal) { + const controller = new AbortController(); + signal = controller.signal; + _signal.addListener(() => { controller.abort(); }); + } + const init = { + method: req.method, + headers: new Headers(Array.from(req)), + body: req.body || undefined, + signal + }; + const resp = await fetch(req.url, init); + const headers = {}; + resp.headers.forEach((value, key) => { + headers[key.toLowerCase()] = value; + }); + const respBody = await resp.arrayBuffer(); + const body = (respBody == null) ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers, body + }; +} +//# sourceMappingURL=geturl-browser.js.map \ No newline at end of file diff --git a/lib.esm/utils/geturl-browser.js.map b/lib.esm/utils/geturl-browser.js.map new file mode 100644 index 000000000..bac4cb528 --- /dev/null +++ b/lib.esm/utils/geturl-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"geturl-browser.js","sourceRoot":"","sources":["../../src.ts/utils/geturl-browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA2BrC,2EAA2E;AAE3E,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,GAAiB,EAAE,OAA2B;IACvE,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IAErD,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,OAAO,EAAE;QAC7C,MAAM,CAAC,UAAU,CAAC,wBAAyB,QAAS,EAAE,EAAE,uBAAuB,EA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ACH,UAAU,EAAE,IAAI,CAAC,MAAM;QACvB,aAAa,EAAE,IAAI,CAAC,UAAU;QAC9B,OAAO,EAAE,IAAI;KAChB,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/geturl.js b/lib.esm/utils/geturl.js new file mode 100644 index 000000000..dea4b420d --- /dev/null +++ b/lib.esm/utils/geturl.js @@ -0,0 +1,78 @@ +import http from "http"; +import https from "https"; +import { gunzipSync } from "zlib"; +import { logger } from "./logger.js"; +export async function getUrl(req, signal) { + const protocol = req.url.split(":")[0].toLowerCase(); + if (protocol !== "http" && protocol !== "https") { + logger.throwError(`unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { protocol }, + operation: "request" + }); + } + if (req.credentials && !req.allowInsecureAuthentication) { + logger.throwError("insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + } + const method = req.method; + const headers = Object.assign({}, req.headers); + const options = { method, headers }; + const request = ((protocol === "http") ? http : https).request(req.url, options); + request.setTimeout(req.timeout); + const body = req.body; + if (body) { + request.write(Buffer.from(body)); + } + request.end(); + return new Promise((resolve, reject) => { + // @TODO: Node 15 added AbortSignal; once we drop support for + // Node14, we can add that in here too + request.once("response", (resp) => { + const statusCode = resp.statusCode || 0; + const statusMessage = resp.statusMessage || ""; + const headers = Object.keys(resp.headers || {}).reduce((accum, name) => { + let value = resp.headers[name] || ""; + if (Array.isArray(value)) { + value = value.join(", "); + } + accum[name] = value; + return accum; + }, {}); + let body = null; + //resp.setEncoding("utf8"); + resp.on("data", (chunk) => { + if (signal) { + try { + signal.checkSignal(); + } + catch (error) { + return reject(error); + } + } + if (body == null) { + body = chunk; + } + else { + const newBody = new Uint8Array(body.length + chunk.length); + newBody.set(body, 0); + newBody.set(chunk, body.length); + body = newBody; + } + }); + resp.on("end", () => { + if (headers["content-encoding"] === "gzip" && body) { + body = logger.getBytes(gunzipSync(body)); + } + resolve({ statusCode, statusMessage, headers, body }); + }); + resp.on("error", (error) => { + //@TODO: Should this just return nornal response with a server error? + error.response = { statusCode, statusMessage, headers, body }; + reject(error); + }); + }); + request.on("error", (error) => { reject(error); }); + }); +} +//# sourceMappingURL=geturl.js.map \ No newline at end of file diff --git a/lib.esm/utils/geturl.js.map b/lib.esm/utils/geturl.js.map new file mode 100644 index 000000000..c84858fe4 --- /dev/null +++ b/lib.esm/utils/geturl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"geturl.js","sourceRoot":"","sources":["../../src.ts/utils/geturl.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAElC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,GAAiB,EAAE,MAA0B;IAEtE,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IAErD,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,OAAO,EAAE;QAC7C,MAAM,CAAC,UAAU,CAAC,wBAAyB,QAAS,EAAE,EAAE,uBAAuB,EAAE;YAC7E,IAAI,EAAE,EAAE,QAAQ,EAAE;YAClB,SAAS,EAAE,SAAS;SACvB,CAAC,CAAC;KACN;IAED,IAAI,GAAG,CAAC,WAAW,IAAI,CAAC,GAAG,CAAC,2BAA2B,EAAE;QACrD,MAAM,CAAC,UAAU,CAAC,6CAA6C,EAAE,uBAAuB,EAAE;YACtF,SAAS,EAAE,SAAS;SACvB,CAAC,CAAC;KACN;IAED,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAC1B,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAG,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IAEhD,MAAM,OAAO,GAA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AO,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACP,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/index.js b/lib.esm/utils/index.js new file mode 100644 index 000000000..7fcbaedc0 --- /dev/null +++ b/lib.esm/utils/index.js @@ -0,0 +1,17 @@ +//// +export { decodeBase58, encodeBase58 } from "./base58.js"; +export { decodeBase64, encodeBase64 } from "./base64.js"; +export { isHexString, isBytesLike, hexlify, concat, dataLength, dataSlice, stripZerosLeft, zeroPadValue, zeroPadBytes } from "./data.js"; +export { isCallException, isError } from "./errors.js"; +export { EventPayload } from "./events.js"; +export { FetchRequest, FetchResponse } from "./fetch.js"; +export { FixedFormat, FixedNumber, formatFixed, parseFixed } from "./fixednumber.js"; +export { assertArgument, Logger, logger } from "./logger.js"; +export { fromTwos, toTwos, mask, toBigInt, toNumber, toHex, toArray, toQuantity } from "./maths.js"; +export { resolveProperties, defineReadOnly, defineProperties } from "./properties.js"; +export { decodeRlp } from "./rlp-decode.js"; +export { encodeRlp } from "./rlp-encode.js"; +export { getStore, setStore } from "./storage.js"; +export { formatEther, parseEther, formatUnits, parseUnits } from "./units.js"; +export { _toEscapedUtf8String, toUtf8Bytes, toUtf8CodePoints, toUtf8String, Utf8ErrorFuncs, } from "./utf8.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/utils/index.js.map b/lib.esm/utils/index.js.map new file mode 100644 index 000000000..0123ebd4e --- /dev/null +++ b/lib.esm/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/utils/index.ts"],"names":[],"mappings":"AACA,IAAI;AAeJ,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EACH,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAChE,cAAc,EAAE,YAAY,EAAE,YAAY,EAC7C,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAEtD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAEpF,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE7D,OAAO,EACH,QAAQ,EAAE,MAAM,EAAE,IAAI,EACtB,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,EACjD,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AAErF,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAC,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE9E,OAAO,EACH,oBAAoB,EACpB,WAAW,EACX,gBAAgB,EAChB,YAAY,EAEZ,cAAc,GACjB,MAAM,WAAW,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/logger.js b/lib.esm/utils/logger.js new file mode 100644 index 000000000..6e364159f --- /dev/null +++ b/lib.esm/utils/logger.js @@ -0,0 +1,226 @@ +import { version } from "../_version.js"; +const LogLevels = ["debug", "info", "warning", "error", "off"]; +const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { + try { + // General test for normalize + /* c8 ignore start */ + if ("test".normalize(form) !== "test") { + throw new Error("bad"); + } + ; + /* c8 ignore stop */ + if (form === "NFD") { + const check = String.fromCharCode(0xe9).normalize("NFD"); + const expected = String.fromCharCode(0x65, 0x0301); + /* c8 ignore start */ + if (check !== expected) { + throw new Error("broken"); + } + /* c8 ignore stop */ + } + accum.push(form); + } + catch (error) { } + return accum; +}, []); +function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, writable: false, value, + }); +} +// IEEE 754 support 53-bits of mantissa +const maxValue = 0x1fffffffffffff; +// The type of error to use for various error codes +const ErrorConstructors = {}; +ErrorConstructors.INVALID_ARGUMENT = TypeError; +ErrorConstructors.NUMERIC_FAULT = RangeError; +ErrorConstructors.BUFFER_OVERRUN = RangeError; +export class Logger { + version; + #logLevel; + constructor(version) { + defineReadOnly(this, "version", version || "_"); + this.#logLevel = 1; + } + get logLevel() { + return LogLevels[this.#logLevel]; + } + set logLevel(value) { + const logLevel = LogLevels.indexOf(value); + if (logLevel == null) { + this.throwArgumentError("invalid logLevel", "logLevel", value); + } + this.#logLevel = logLevel; + } + makeError(message, code, info) { + { + const details = []; + if (info) { + for (const key in info) { + const value = (info[key]); + try { + details.push(key + "=" + JSON.stringify(value)); + } + catch (error) { + details.push(key + "=[could not serialize object]"); + } + } + } + details.push(`code=${code}`); + details.push(`version=${this.version}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; + } + } + const create = ErrorConstructors[code] || Error; + const error = (new create(message)); + defineReadOnly(error, "code", code); + if (info) { + for (const key in info) { + defineReadOnly(error, key, (info[key])); + } + } + return error; + } + throwError(message, code, info) { + throw this.makeError(message, code, info); + } + throwArgumentError(message, name, value) { + return this.throwError(message, "INVALID_ARGUMENT", { + argument: name, + value: value + }); + } + assertNormalize(form) { + if (_normalizeForms.indexOf(form) === -1) { + this.throwError("platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", info: { form } + }); + } + } + assertPrivate(givenGuard, guard, className = "") { + if (givenGuard !== guard) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; + } + this.throwError(`private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation + }); + } + } + assertArgumentCount(count, expectedCount, message = "") { + if (message) { + message = ": " + message; + } + if (count < expectedCount) { + this.throwError("missing arguemnt" + message, "MISSING_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + if (count > expectedCount) { + this.throwError("too many arguemnts" + message, "UNEXPECTED_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + } + } + #getBytes(value, name, copy) { + if (value instanceof Uint8Array) { + if (copy) { + return new Uint8Array(value); + } + return value; + } + if (typeof (value) === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset = 2; + for (let i = 0; i < result.length; i++) { + result[i] = parseInt(value.substring(offset, offset + 2), 16); + offset += 2; + } + return result; + } + return this.throwArgumentError("invalid BytesLike value", name || "value", value); + } + getBytes(value, name) { + return this.#getBytes(value, name, false); + } + getBytesCopy(value, name) { + return this.#getBytes(value, name, true); + } + getNumber(value, name) { + switch (typeof (value)) { + case "bigint": + if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return Number(value); + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return value; + case "string": + try { + return this.getNumber(BigInt(value), name); + } + catch (e) { + this.throwArgumentError(`invalid numeric string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid numeric value", name || "value", value); + } + getBigInt(value, name) { + switch (typeof (value)) { + case "bigint": return value; + case "number": + if (!Number.isInteger(value)) { + this.throwArgumentError("underflow", name || "value", value); + } + else if (value < -maxValue || value > maxValue) { + this.throwArgumentError("overflow", name || "value", value); + } + return BigInt(value); + case "string": + try { + return BigInt(value); + } + catch (e) { + this.throwArgumentError(`invalid BigNumberish string: ${e.message}`, name || "value", value); + } + } + return this.throwArgumentError("invalid BigNumberish value", name || "value", value); + } + #log(_logLevel, args) { + const logLevel = LogLevels.indexOf(_logLevel); + if (logLevel === -1) { + this.throwArgumentError("invalid log level name", "logLevel", _logLevel); + } + if (this.#logLevel > logLevel) { + return; + } + console.log.apply(console, args); + } + debug(...args) { + this.#log("debug", args); + } + info(...args) { + this.#log("info", args); + } + warn(...args) { + this.#log("warning", args); + } +} +export const logger = new Logger(version); +export function assertArgument(check, message, name, value) { + if (!check) { + logger.throwArgumentError(message, name, value); + } +} +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/lib.esm/utils/logger.js.map b/lib.esm/utils/logger.js.map new file mode 100644 index 000000000..d216357a1 --- /dev/null +++ b/lib.esm/utils/logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src.ts/utils/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAWzC,MAAM,SAAS,GAAoB,CAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,CAAE,CAAC;AAElF,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;IAC1E,IAAI;QACA,6BAA6B;QAC7B,qBAAqB;QACrB,IAAI,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,MAAM,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;SAAE;QAAA,CAAC;QACnE,oBAAoB;QAEpB,IAAI,IAAI,KAAK,KAAK,EAAE;YAChB,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,KA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G,IAAgB;QACrB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,GAAG,IAAgB;QACpB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,IAAI,CAAC,GAAG,IAAgB;QACpB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;CACJ;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AAE1C,MAAM,UAAU,cAAc,CAAC,KAAc,EAAE,OAAe,EAAE,IAAY,EAAE,KAAc;IACxF,IAAI,CAAC,KAAK,EAAE;QAAE,MAAM,CAAC,kBAAkB,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;KAAE;AACpE,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/maths.js b/lib.esm/utils/maths.js new file mode 100644 index 000000000..7eaaca584 --- /dev/null +++ b/lib.esm/utils/maths.js @@ -0,0 +1,122 @@ +import { hexlify, isBytesLike } from "./data.js"; +import { logger } from "./logger.js"; +const BN_0 = BigInt(0); +const BN_1 = BigInt(1); +/** + * Convert %%value%% from a twos-compliment value of %%width%% bits. + */ +export function fromTwos(_value, _width) { + const value = logger.getBigInt(_value, "value"); + const width = BigInt(logger.getNumber(_width, "width")); + // Top bit set; treat as a negative value + if (value >> (width - BN_1)) { + const mask = (BN_1 << width) - BN_1; + return -(((~value) & mask) + BN_1); + } + return value; +} +/** + * Convert %%value%% to a twos-compliment value of %%width%% bits. + */ +export function toTwos(_value, _width) { + const value = logger.getBigInt(_value, "value"); + const width = BigInt(logger.getNumber(_width, "width")); + if (value < BN_0) { + const mask = (BN_1 << width) - BN_1; + return ((~(-value)) & mask) + BN_1; + } + return value; +} +/** + * Mask %%value%% with a bitmask of %%bits%% ones. + */ +export function mask(_value, _bits) { + const value = logger.getBigInt(_value, "value"); + const bits = BigInt(logger.getNumber(_bits, "bits")); + return value & ((BN_1 << bits) - BN_1); +} +/* + * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. + */ +const Nibbles = "0123456789abcdef"; +export function toBigInt(value) { + if (value instanceof Uint8Array) { + let result = "0x0"; + for (const v of value) { + result += Nibbles[v >> 4]; + result += Nibbles[v & 0x0f]; + } + return BigInt(result); + } + return logger.getBigInt(value); +} +/* + * Converts %%value%% to a number. If %%value%% is a Uint8Array, it + * is treated as Big Endian data. Throws if the value is not safe. + */ +export function toNumber(value) { + return logger.getNumber(toBigInt(value)); +} +/** + * Converts %%value%% to a Big Endian hexstring, optionally padded to + * %%width%% bytes. + */ +// Converts value to hex, optionally padding on the left to width bytes +export function toHex(_value, _width) { + const value = logger.getBigInt(_value, "value"); + if (value < 0) { + throw new Error("cannot convert negative value to hex"); + } + let result = value.toString(16); + if (_width == null) { + // Ensure the value is of even length + if (result.length % 2) { + result = "0" + result; + } + } + else { + const width = logger.getNumber(_width, "width"); + if (width * 2 < result.length) { + throw new Error(`value ${value} exceeds width ${width}`); + } + // Pad the value to the required width + while (result.length < (width * 2)) { + result = "0" + result; + } + } + return "0x" + result; +} +/** + * Converts %%value%% to a Big Endian Uint8Array. + */ +export function toArray(_value) { + const value = logger.getBigInt(_value, "value"); + if (value < 0) { + throw new Error("cannot convert negative value to hex"); + } + if (value === BN_0) { + return new Uint8Array([]); + } + let hex = value.toString(16); + if (hex.length % 2) { + hex = "0" + hex; + } + const result = new Uint8Array(hex.length / 2); + for (let i = 0; i < result.length; i++) { + const offset = i * 2; + result[i] = parseInt(hex.substring(offset, offset + 2), 16); + } + return result; +} +export function toQuantity(value) { + let result = hexlify(isBytesLike(value) ? value : toArray(value)).substring(2); + while (result.substring(0, 1) === "0") { + result = result.substring(1); + } + if (result === "") { + result = "0"; + } + return "0x" + result; +} +//# sourceMappingURL=maths.js.map \ No newline at end of file diff --git a/lib.esm/utils/maths.js.map b/lib.esm/utils/maths.js.map new file mode 100644 index 000000000..e2a04da44 --- /dev/null +++ b/lib.esm/utils/maths.js.map @@ -0,0 +1 @@ +{"version":3,"file":"maths.js","sourceRoot":"","sources":["../../src.ts/utils/maths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AASrC,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAEvB;;GAEG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAoB,EAAE,MAAe;IAC1D,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAExD,yCAAyC;IACzC,IAAI,KAAK,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,EAAE;QACzB,MAAM,IAAI,GAAG,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC;QACpC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;KACtC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,MAAM,CAAC,MAAoB,EAAE,MAAe;IACxD,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAExD,IAAI,KAAK,GAAG,IAAI,EAAE;QACd,MAAM,IAAI,GAAG,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,I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,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC9C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACpC,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;QACrB,MAAM,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;KAC/D;IAED,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,KAA+B;IACtD,IAAI,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAC9E,OAAO,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;QAAE,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KAAE;IACxE,IAAI,MAAM,KAAK,EAAE,EAAE;QAAE,MAAM,GAAG,GAAG,CAAC;KAAE;IACpC,OAAO,IAAI,GAAG,MAAM,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/properties.js b/lib.esm/utils/properties.js new file mode 100644 index 000000000..1fb13997a --- /dev/null +++ b/lib.esm/utils/properties.js @@ -0,0 +1,106 @@ +export async function resolveProperties(value) { + const keys = Object.keys(value); + const results = await Promise.all(keys.map((k) => Promise.resolve(value[k]))); + return results.reduce((accum, v, index) => { + accum[keys[index]] = v; + return accum; + }, {}); +} +export function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + value: value, + writable: false, + }); +} +/* +export interface CancellablePromise extends Promise { + cancel(): Promise; +} +export type IsCancelled = () => Promise; + +export function createPromise(resolve: (isCancelled: IsCancelled, (result: T) => void) => void, reject: (error: Error) => void, isCancelled: IsCancelled): CancellablePromise { + let cancelled = false; + + const promise = new Promise((resolve, reject) => { + + }); + + (>promise).cancel = function() { + cancelled = true; + }; + + return (>promise); +} +*/ +/* +export class A implements Freezable { + foo: number; + constructor(foo: number) { + this.foo = foo; + } + freeze(): Frozen { + Object.freeze(this); + return this; + } + clone(): A { + return new A(this.foo); + } +} + +export class B implements Freezable { + a: A; + constructor(a: A) { + this.a = a; + } + freeze(): Frozen { + this.a.freeze(); + Object.freeze(this); + return this; + } + clone(): B { + return new B(this.a); + } +} + +export function test() { + const a = new A(123); + const b = new B(a); + b.a = new A(234); + const b2 = b.freeze(); + b2.a.foo = 123; // = a; +} +*/ +function checkType(value, type) { + const types = type.split("|").map(t => t.trim()); + for (let i = 0; i < types.length; i++) { + switch (type) { + case "any": + return; + case "boolean": + case "number": + case "string": + if (typeof (value) === type) { + return; + } + } + } + throw new Error("invalid value for type"); +} +export function defineProperties(target, values, types, defaults) { + for (let key in values) { + let value = values[key]; + const fallback = (defaults ? defaults[key] : undefined); + if (fallback !== undefined) { + value = fallback; + } + else { + const type = (types ? types[key] : null); + if (type) { + checkType(value, type); + } + } + Object.defineProperty(target, key, { enumerable: true, value, writable: false }); + } +} +//# sourceMappingURL=properties.js.map \ No newline at end of file diff --git a/lib.esm/utils/properties.js.map b/lib.esm/utils/properties.js.map new file mode 100644 index 000000000..eb10a8487 --- /dev/null +++ b/lib.esm/utils/properties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"properties.js","sourceRoot":"","sources":["../../src.ts/utils/properties.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAI,KAAgD;IACvF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAChC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAA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EnC,KAAK,IAAI,GAAG,IAAI,MAAM,EAAE;QACpB,IAAI,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAExB,MAAM,QAAQ,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA,CAAC,CAAC,SAAS,CAAC,CAAC;QACvD,IAAI,QAAQ,KAAK,SAAS,EAAE;YACxB,KAAK,GAAG,QAAQ,CAAC;SACpB;aAAM;YACH,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA,CAAC,CAAC,IAAI,CAAC,CAAC;YACxC,IAAI,IAAI,EAAE;gBAAE,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;aAAE;SACxC;QACD,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;KACpF;AACL,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/rlp-decode.js b/lib.esm/utils/rlp-decode.js new file mode 100644 index 000000000..9b6734aa0 --- /dev/null +++ b/lib.esm/utils/rlp-decode.js @@ -0,0 +1,83 @@ +//See: https://github.com/ethereum/wiki/wiki/RLP +import { hexlify } from "./data.js"; +import { logger } from "./logger.js"; +function hexlifyByte(value) { + let result = value.toString(16); + while (result.length < 2) { + result = "0" + result; + } + return "0x" + result; +} +function unarrayifyInteger(data, offset, length) { + let result = 0; + for (let i = 0; i < length; i++) { + result = (result * 256) + data[offset + i]; + } + return result; +} +function _decodeChildren(data, offset, childOffset, length) { + const result = []; + while (childOffset < offset + 1 + length) { + const decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + if (childOffset > offset + 1 + length) { + logger.throwError("child data too short", "BUFFER_OVERRUN", { + buffer: data, length, offset + }); + } + } + return { consumed: (1 + length), result: result }; +} +// returns { consumed: number, result: Object } +function _decode(data, offset) { + if (data.length === 0) { + logger.throwError("data too short", "BUFFER_OVERRUN", { + buffer: data, length: 0, offset: 1 + }); + } + const checkOffset = (offset) => { + if (offset > data.length) { + logger.throwError("data short segment too short", "BUFFER_OVERRUN", { + buffer: data, length: data.length, offset + }); + } + }; + // Array with extra length prefix + if (data[offset] >= 0xf8) { + const lengthLength = data[offset] - 0xf7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } + else if (data[offset] >= 0xc0) { + const length = data[offset] - 0xc0; + checkOffset(offset + 1 + length); + return _decodeChildren(data, offset, offset + 1, length); + } + else if (data[offset] >= 0xb8) { + const lengthLength = data[offset] - 0xb7; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { consumed: (1 + lengthLength + length), result: result }; + } + else if (data[offset] >= 0x80) { + const length = data[offset] - 0x80; + checkOffset(offset + 1 + length); + const result = hexlify(data.slice(offset + 1, offset + 1 + length)); + return { consumed: (1 + length), result: result }; + } + return { consumed: 1, result: hexlifyByte(data[offset]) }; +} +export function decodeRlp(_data) { + const data = logger.getBytes(_data, "data"); + const decoded = _decode(data, 0); + if (decoded.consumed !== data.length) { + logger.throwArgumentError("unexpected junk after rlp payload", "data", _data); + } + return decoded.result; +} +//# sourceMappingURL=rlp-decode.js.map \ No newline at end of file diff --git a/lib.esm/utils/rlp-decode.js.map b/lib.esm/utils/rlp-decode.js.map new file mode 100644 index 000000000..35302571f --- /dev/null +++ b/lib.esm/utils/rlp-decode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp-decode.js","sourceRoot":"","sources":["../../src.ts/utils/rlp-decode.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAEhD,OAAO,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AAC,MAAM,CAAC,CAAC,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,KAAgB;IACtC,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACjC,IAAI,OAAO,CAAC,QAAQ,KAAK,IAAI,CAAC,MAAM,EAAE;QAClC,MAAM,CAAC,kBAAkB,CAAC,mCAAmC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;KACjF;IACD,OAAO,OAAO,CAAC,MAAM,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/rlp-encode.js b/lib.esm/utils/rlp-encode.js new file mode 100644 index 000000000..e077feedd --- /dev/null +++ b/lib.esm/utils/rlp-encode.js @@ -0,0 +1,46 @@ +//See: https://github.com/ethereum/wiki/wiki/RLP +import { logger } from "./logger.js"; +function arrayifyInteger(value) { + const result = []; + while (value) { + result.unshift(value & 0xff); + value >>= 8; + } + return result; +} +function _encode(object) { + if (Array.isArray(object)) { + let payload = []; + object.forEach(function (child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(0xc0 + payload.length); + return payload; + } + const length = arrayifyInteger(payload.length); + length.unshift(0xf7 + length.length); + return length.concat(payload); + } + const data = Array.prototype.slice.call(logger.getBytes(object, "object")); + if (data.length === 1 && data[0] <= 0x7f) { + return data; + } + else if (data.length <= 55) { + data.unshift(0x80 + data.length); + return data; + } + const length = arrayifyInteger(data.length); + length.unshift(0xb7 + length.length); + return length.concat(data); +} +const nibbles = "0123456789abcdef"; +export function encodeRlp(object) { + let result = "0x"; + for (const v of _encode(object)) { + result += nibbles[v >> 4]; + result += nibbles[v & 0xf]; + } + return result; +} +//# sourceMappingURL=rlp-encode.js.map \ No newline at end of file diff --git a/lib.esm/utils/rlp-encode.js.map b/lib.esm/utils/rlp-encode.js.map new file mode 100644 index 000000000..e159be120 --- /dev/null +++ b/lib.esm/utils/rlp-encode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp-encode.js","sourceRoot":"","sources":["../../src.ts/utils/rlp-encode.ts"],"names":[],"mappings":"AAAA,gDAAgD;AAEhD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,SAAS,eAAe,CAAC,KAAa;IAClC,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,OAAO,KAAK,EAAE;QACV,MAAM,CAAC,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;QAC7B,KAAK,KAAK,CAAC,CAAC;KACf;IACD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,SAAS,OAAO,CAAC,MAA2B;IACxC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QACvB,IAAI,OAAO,GAAkB,EAAE,CAAC;QAChC,MAAM,CAAC,OAAO,CAAC,UAAS,KAAK;YACzB,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;QAEH,IAAI,OAAO,CAAC,MAAM,IAAI,EAAE,EAAE;YACtB,OAAO,CAAC,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;YACtC,OAAO,OAAO,CAAC;SAClB;QAED,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC/C,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;QAErC,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;KAEjC;IAED,MAAM,IAAI,GAAkB,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IAE1F,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE;QACtC,OAAO,IAAI,CAAC;KAEf;SAAM,IAAI,IAAI,CAAC,MAAM,IAAI,EAAE,EAAE;QAC1B,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;KACf;IAED,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5C,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAErC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAED,MAAM,OAAO,GAAG,kBAAkB,CAAC;AAEnC,MAAM,UAAU,SAAS,CAAC,MAAyB;IAC/C,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,EAAE;QAC7B,MAAM,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1B,MAAM,IAAI,OAAO,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;KAC9B;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/rlp.js b/lib.esm/utils/rlp.js new file mode 100644 index 000000000..625da8186 --- /dev/null +++ b/lib.esm/utils/rlp.js @@ -0,0 +1,3 @@ +export { decodeRlp } from "./rlp-decode.js"; +export { encodeRlp } from "./rlp-encode.js"; +//# sourceMappingURL=rlp.js.map \ No newline at end of file diff --git a/lib.esm/utils/rlp.js.map b/lib.esm/utils/rlp.js.map new file mode 100644 index 000000000..6ce568a15 --- /dev/null +++ b/lib.esm/utils/rlp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp.js","sourceRoot":"","sources":["../../src.ts/utils/rlp.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/storage.js b/lib.esm/utils/storage.js new file mode 100644 index 000000000..5400e17ed --- /dev/null +++ b/lib.esm/utils/storage.js @@ -0,0 +1,10 @@ +export function getStore(store, key) { + return store[key]; +} +export function setStore(store, key, value) { + if (Object.isFrozen(store)) { + throw new Error(`frozen object is immuatable; cannot set ${String(key)}`); + } + store[key] = value; +} +//# sourceMappingURL=storage.js.map \ No newline at end of file diff --git a/lib.esm/utils/storage.js.map b/lib.esm/utils/storage.js.map new file mode 100644 index 000000000..9e4d2dd81 --- /dev/null +++ b/lib.esm/utils/storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src.ts/utils/storage.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,QAAQ,CAAuB,KAAQ,EAAE,GAAM;IAC3D,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,QAAQ,CAAuB,KAAQ,EAAE,GAAM,EAAE,KAAW;IACxE,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,2CAA4C,MAAM,CAAC,GAAG,CAAE,EAAE,CAAC,CAAC;KAC/E;IACD,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/lib.esm/utils/units.js b/lib.esm/utils/units.js new file mode 100644 index 000000000..afde68df3 --- /dev/null +++ b/lib.esm/utils/units.js @@ -0,0 +1,59 @@ +import { formatFixed, parseFixed } from "./fixednumber.js"; +import { logger } from "./logger.js"; +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether", +]; +/** + * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal + * places. The %%unit%% may be the number of decimal places or the name of + * a unit (e.g. ``"gwei"`` for 9 decimal places). + * + */ +export function formatUnits(value, unit) { + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + if (index === -1) { + logger.throwArgumentError("invalid unit", "unit", unit); + } + unit = 3 * index; + } + return formatFixed(value, (unit != null) ? unit : 18); +} +/** + * Converts the //decimal string// %%value%% to a [[BigInt]], assuming + * %%unit%% decimal places. The %%unit%% may the number of decimal places + * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places). + */ +export function parseUnits(value, unit) { + if (typeof (value) !== "string") { + logger.throwArgumentError("value must be a string", "value", value); + } + if (typeof (unit) === "string") { + const index = names.indexOf(unit); + if (index === -1) { + logger.throwArgumentError("invalid unit", "unit", unit); + } + unit = 3 * index; + } + return parseFixed(value, (unit != null) ? unit : 18); +} +/** + * Converts %%value%% into a //decimal string// using 18 decimal places. + */ +export function formatEther(wei) { + return formatUnits(wei, 18); +} +/** + * Converts the //decimal string// %%ether%% to a [[BigInt]], using 18 + * decimal places. + */ +export function parseEther(ether) { + return parseUnits(ether, 18); +} +//# sourceMappingURL=units.js.map \ No newline at end of file diff --git a/lib.esm/utils/units.js.map b/lib.esm/utils/units.js.map new file mode 100644 index 000000000..8df72c3f3 --- /dev/null +++ b/lib.esm/utils/units.js.map @@ -0,0 +1 @@ +{"version":3,"file":"units.js","sourceRoot":"","sources":["../../src.ts/utils/units.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,MAAM,KAAK,GAAG;IACV,KAAK;IACL,MAAM;IACN,MAAM;IACN,MAAM;IACN,OAAO;IACP,QAAQ;IACR,OAAO;CACV,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,KAAmB,EAAE,IAAuB;IACpE,IAAI,OAAM,CAAC,IAAI,CAAC,KAAK,QAAQ,EAAE;QAC3B,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC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.js new file mode 100644 index 000000000..674d10fa1 --- /dev/null +++ b/lib.esm/utils/utf8.js @@ -0,0 +1,206 @@ +import { logger } from "./logger.js"; +function errorFunc(reason, offset, bytes, output, badCodepoint) { + return logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for (let o = offset + 1; o < bytes.length; o++) { + if (bytes[o] >> 6 !== 0x02) { + break; + } + i++; + } + return i; + } + // This byte runs us past the end of the string, so just jump to the end + // (but the first byte was read already read and therefore skipped) + if (reason === "OVERRUN") { + return bytes.length - offset - 1; + } + // Nothing to skip + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + // Overlong representations are otherwise "valid" code points; just non-deistingtished + if (reason === "OVERLONG") { + output.push((badCodepoint != null) ? badCodepoint : -1); + return 0; + } + // Put the replacement character into the output + output.push(0xfffd); + // Otherwise, process as if ignoring errors + return ignoreFunc(reason, offset, bytes, output, badCodepoint); +} +// Common error handing strategies +export const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + const bytes = logger.getBytes(_bytes, "bytes"); + const result = []; + let i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + const c = bytes[i++]; + // 0xxx xxxx + if (c >> 7 === 0) { + result.push(c); + continue; + } + // Multibyte; how many bytes left for this character? + let extraLength = null; + let overlongMask = null; + // 110x xxxx 10xx xxxx + if ((c & 0xe0) === 0xc0) { + extraLength = 1; + overlongMask = 0x7f; + // 1110 xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf0) === 0xe0) { + extraLength = 2; + overlongMask = 0x7ff; + // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx + } + else if ((c & 0xf8) === 0xf0) { + extraLength = 3; + overlongMask = 0xffff; + } + else { + if ((c & 0xc0) === 0x80) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result); + } + else { + i += onError("BAD_PREFIX", i - 1, bytes, result); + } + continue; + } + // Do we have enough bytes in our data? + if (i - 1 + extraLength >= bytes.length) { + i += onError("OVERRUN", i - 1, bytes, result); + continue; + } + // Remove the length prefix from the char + let res = c & ((1 << (8 - extraLength - 1)) - 1); + for (let j = 0; j < extraLength; j++) { + let nextChar = bytes[i]; + // Invalid continuation byte + if ((nextChar & 0xc0) != 0x80) { + i += onError("MISSING_CONTINUE", i, bytes, result); + res = null; + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + i++; + } + // See above loop for invalid continuation byte + if (res === null) { + continue; + } + // Maximum code point + if (res > 0x10ffff) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Reserved for UTF-16 surrogate halves + if (res >= 0xd800 && res <= 0xdfff) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res); + continue; + } + // Check for overlong sequences (more bytes than needed) + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array +export function toUtf8Bytes(str, form) { + if (form != null) { + logger.assertNormalize(form); + str = str.normalize(form); + } + let result = []; + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c < 0x80) { + result.push(c); + } + else if (c < 0x800) { + result.push((c >> 6) | 0xc0); + result.push((c & 0x3f) | 0x80); + } + else if ((c & 0xfc00) == 0xd800) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { + throw new Error("invalid utf-8 string"); + } + // Surrogate Pair + const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + result.push((pair >> 18) | 0xf0); + result.push(((pair >> 12) & 0x3f) | 0x80); + result.push(((pair >> 6) & 0x3f) | 0x80); + result.push((pair & 0x3f) | 0x80); + } + else { + result.push((c >> 12) | 0xe0); + result.push(((c >> 6) & 0x3f) | 0x80); + result.push((c & 0x3f) | 0x80); + } + } + return new Uint8Array(result); +} +; +function escapeChar(value) { + const hex = ("0000" + value.toString(16)); + return "\\u" + hex.substring(hex.length - 4); +} +export function _toEscapedUtf8String(bytes, onError) { + return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => { + if (codePoint < 256) { + switch (codePoint) { + case 8: return "\\b"; + case 9: return "\\t"; + case 10: return "\\n"; + case 13: return "\\r"; + case 34: return "\\\""; + case 92: return "\\\\"; + } + if (codePoint >= 32 && codePoint < 127) { + return String.fromCharCode(codePoint); + } + } + if (codePoint <= 0xffff) { + return escapeChar(codePoint); + } + codePoint -= 0x10000; + return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00); + }).join("") + '"'; +} +export function _toUtf8String(codePoints) { + return codePoints.map((codePoint) => { + if (codePoint <= 0xffff) { + return String.fromCharCode(codePoint); + } + codePoint -= 0x10000; + return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); + }).join(""); +} +export function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +export function toUtf8CodePoints(str, form) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +//# sourceMappingURL=utf8.js.map \ No newline at end of file diff --git a/lib.esm/utils/utf8.js.map b/lib.esm/utils/utf8.js.map new file mode 100644 index 000000000..169b670b9 --- /dev/null +++ b/lib.esm/utils/utf8.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utf8.js","sourceRoot":"","sources":["../../src.ts/utils/utf8.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,a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E,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,SAAS,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,CAAC;IACvG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,UAAyB;IACnD,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE;QAChC,IAAI,SAAS,IAAI,MAAM,EAAE;YACrB,OAAO,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;SACzC;QACD,SAAS,IAAI,OAAO,CAAC;QACrB,OAAO,MAAM,CAAC,YAAY,CACtB,CAAC,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,EACtC,CAAC,CAAC,SAAS,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,CACjC,CAAC;IACN,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,KAAgB,EAAE,OAAuB;IAClE,OAAO,aAAa,CAAC,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,GAAW,EAAE,IAA+B;IACzE,OAAO,iBAAiB,CAAC,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;AACrD,CAAC"} \ 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 000000000..372b6adcb --- /dev/null +++ b/lib.esm/wallet/base-wallet.js @@ -0,0 +1,62 @@ +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 { defineProperties, logger, resolveProperties } from "../utils/index.js"; +export class BaseWallet extends AbstractSigner { + address; + #signingKey; + constructor(privateKey, provider) { + super(provider); + this.#signingKey = privateKey; + const address = computeAddress(this.signingKey.publicKey); + defineProperties(this, { address }); + } + // Store these in getters to reduce visibility in console.log + get signingKey() { return this.#signingKey; } + 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 tx = Object.assign({}, _tx, await resolveProperties({ + to: (_tx.to ? resolveAddress(_tx.to, this.provider) : undefined), + from: (_tx.from ? resolveAddress(_tx.from, this.provider) : undefined) + })); + if (tx.from != null) { + if (getAddress(tx.from) !== this.address) { + logger.throwArgumentError("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.signingKey.sign(hashMessage(message)).serialized; + } + async signTypedData(domain, types, value) { + // Populate any ENS names + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => { + if (this.provider == null) { + return logger.throwError("cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name } + }); + } + const address = await this.provider.resolveName(name); + if (address == null) { + return logger.throwError("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 000000000..8c3083362 --- /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,qBAAq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AAC;aACN;YAED,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;YACtD,IAAI,OAAO,IAAI,IAAI,EAAE;gBACjB,OAAO,MAAM,CAAC,UAAU,CAAC,uBAAuB,EAAE,mBAAmB,EAAE;oBACnE,KAAK,EAAE,IAAI;iBACd,CAAC,CAAC;aACN;YAED,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/lib.esm/wallet/hdwallet.js b/lib.esm/wallet/hdwallet.js new file mode 100644 index 000000000..89742b1ac --- /dev/null +++ b/lib.esm/wallet/hdwallet.js @@ -0,0 +1,284 @@ +import { computeHmac, randomBytes, ripemd160, SigningKey, sha256 } from "../crypto/index.js"; +import { VoidSigner } from "../providers/index.js"; +import { computeAddress } from "../transaction/index.js"; +import { concat, dataSlice, decodeBase58, defineProperties, encodeBase58, hexlify, logger, toBigInt, toHex } from "../utils/index.js"; +import { langEn } from "../wordlists/lang-en.js"; +import { Mnemonic } from "./mnemonic.js"; +import { BaseWallet } from "./base-wallet.js"; +export const defaultPath = "m/44'/60'/0'/0/0"; +// "Bitcoin seed" +const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); +const HardenedBit = 0x80000000; +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const Nibbles = "0123456789abcdef"; +function zpad(value, length) { + let result = ""; + while (value) { + result = Nibbles[value % 16] + result; + value = Math.trunc(value / 16); + } + while (result.length < length * 2) { + result = "0" + result; + } + return "0x" + result; +} +function encodeBase58Check(_value) { + const value = logger.getBytes(_value); + const check = dataSlice(sha256(sha256(value)), 0, 4); + const bytes = concat([value, check]); + return encodeBase58(bytes); +} +const _guard = {}; +function ser_I(index, chainCode, publicKey, privateKey) { + const data = new Uint8Array(37); + if (index & HardenedBit) { + if (privateKey == null) { + return logger.throwError("cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { + operation: "deriveChild" + }); + } + // Data = 0x00 || ser_256(k_par) + data.set(logger.getBytes(privateKey), 1); + } + else { + // Data = ser_p(point(k_par)) + data.set(logger.getBytes(publicKey)); + } + // Data += ser_32(i) + for (let i = 24; i >= 0; i -= 8) { + data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); + } + const I = logger.getBytes(computeHmac("sha512", chainCode, data)); + return { IL: I.slice(0, 32), IR: I.slice(32) }; +} +function derivePath(node, path) { + const components = path.split("/"); + if (components.length === 0 || (components[0] === "m" && node.depth !== 0)) { + throw new Error("invalid path - " + path); + } + if (components[0] === "m") { + components.shift(); + } + let result = node; + for (let i = 0; i < components.length; i++) { + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index = parseInt(component.substring(0, component.length - 1)); + if (index >= HardenedBit) { + throw new Error("invalid path index - " + component); + } + result = result.deriveChild(HardenedBit + index); + } + else if (component.match(/^[0-9]+$/)) { + const index = parseInt(component); + if (index >= HardenedBit) { + throw new Error("invalid path index - " + component); + } + result = result.deriveChild(index); + } + else { + throw new Error("invalid path component - " + component); + } + } + return result; +} +export class HDNodeWallet extends BaseWallet { + publicKey; + fingerprint; + parentFingerprint; + mnemonic; + chainCode; + path; + index; + depth; + constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) { + super(signingKey, provider); + logger.assertPrivate(guard, _guard, "HDNodeWallet"); + defineProperties(this, { publicKey: signingKey.compressedPublicKey }); + const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4); + defineProperties(this, { + parentFingerprint, fingerprint, + chainCode, path, index, depth + }); + defineProperties(this, { mnemonic }); + } + connect(provider) { + return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); + } + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return encodeBase58Check(concat([ + "0x0488ADE4", zpad(this.depth, 1), this.parentFingerprint, + zpad(this.index, 4), this.chainCode, + concat(["0x00", this.privateKey]) + ])); + } + hasPath() { return (this.path != null); } + neuter() { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); + } + deriveChild(_index) { + const index = logger.getNumber(_index, "index"); + if (index > 0xffffffff) { + throw new Error("invalid index - " + String(index)); + } + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); + const ki = new SigningKey(toHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); + return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider); + } + derivePath(path) { + return derivePath(this, path); + } + static #fromSeed(_seed, mnemonic) { + const seed = logger.getBytes(_seed, "seed"); + if (seed.length < 16 || seed.length > 64) { + throw new Error("invalid seed"); + } + const I = logger.getBytes(computeHmac("sha512", MasterSecret, seed)); + const signingKey = new SigningKey(hexlify(I.slice(0, 32))); + return new HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I.slice(32)), "m", 0, 0, mnemonic, null); + } + static fromSeed(seed) { + return HDNodeWallet.#fromSeed(seed, null); + } + static fromPhrase(phrase, password = "", path = defaultPath, wordlist = langEn) { + if (!path) { + path = defaultPath; + } + const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromMnemonic(mnemonic, path = defaultPath) { + if (!path) { + path = defaultPath; + } + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromExtendedKey(extendedKey) { + const bytes = logger.getBytes(decodeBase58(extendedKey)); // @TODO: redact + if (bytes.length !== 82 || encodeBase58Check(bytes.slice(0, 78)) !== extendedKey) { + logger.throwArgumentError("invalid extended key", "extendedKey", "[ REDACTED ]"); + } + const depth = bytes[4]; + const parentFingerprint = hexlify(bytes.slice(5, 9)); + const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16); + const chainCode = hexlify(bytes.slice(13, 45)); + const key = bytes.slice(45, 78); + switch (hexlify(bytes.slice(0, 4))) { + // Public Key + case "0x0488b21e": + case "0x043587cf": { + const publicKey = hexlify(key); + return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); + } + // Private Key + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); + } + return logger.throwArgumentError("invalid extended key prefix", "extendedKey", "[ REDACTED ]"); + } + static createRandom(password = "", path = defaultPath, wordlist = langEn) { + if (!path) { + path = defaultPath; + } + const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } +} +export class HDNodeVoidWallet extends VoidSigner { + publicKey; + fingerprint; + parentFingerprint; + chainCode; + path; + index; + depth; + constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) { + super(address, provider); + logger.assertPrivate(guard, _guard, "HDNodeVoidWallet"); + defineProperties(this, { publicKey }); + const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4); + defineProperties(this, { + publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth + }); + } + connect(provider) { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); + } + get extendedKey() { + // We only support the mainnet values for now, but if anyone needs + // testnet values, let me know. I believe current sentiment is that + // we should always use mainnet, and use BIP-44 to derive the network + // - Mainnet: public=0x0488B21E, private=0x0488ADE4 + // - Testnet: public=0x043587CF, private=0x04358394 + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return encodeBase58Check(concat([ + "0x0488B21E", + zpad(this.depth, 1), + this.parentFingerprint, + zpad(this.index, 4), + this.chainCode, + this.publicKey, + ])); + } + hasPath() { return (this.path != null); } + deriveChild(_index) { + const index = logger.getNumber(_index, "index"); + if (index > 0xffffffff) { + throw new Error("invalid index - " + String(index)); + } + // Base path + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & HardenedBit) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); + const Ki = SigningKey._addPoints(IL, this.publicKey, true); + const address = computeAddress(Ki); + return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider); + } + derivePath(path) { + return derivePath(this, path); + } +} +export class HDNodeWalletManager { + #root; + constructor(phrase, password = "", path = "m/44'/60'/0'/0", locale = langEn) { + this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale); + } + getSigner(index = 0) { + return this.#root.deriveChild(index); + } +} +export function getAccountPath(_index) { + const index = logger.getNumber(_index, "index"); + if (index < 0 || index >= HardenedBit) { + logger.throwArgumentError("invalid account index", "index", index); + } + return `m/44'/60'/${index}'/0/0`; +} +//# sourceMappingURL=hdwallet.js.map \ No newline at end of file diff --git a/lib.esm/wallet/hdwallet.js.map b/lib.esm/wallet/hdwallet.js.map new file mode 100644 index 000000000..a4035f3fa --- /dev/null +++ b/lib.esm/wallet/hdwallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hdwallet.js","sourceRoot":"","sources":["../../src.ts/wallet/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EAAE,SAAmB,MAAM;QACzF,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACzE,CAAC;IAED,SAAS,CAAC,KAAK,GAAG,CAAC;QACf,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;CACJ;AAED,MAAM,UAAU,cAAc,CAAC,MAAe;IAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChD,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,WAAW,EAAE;QACnC,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;KACtE;IACD,OAAO,aAAc,KAAM,OAAO,CAAC;AACvC,CAAC"} \ No newline at end of file diff --git a/lib.esm/wallet/index.js b/lib.esm/wallet/index.js new file mode 100644 index 000000000..847b094ac --- /dev/null +++ b/lib.esm/wallet/index.js @@ -0,0 +1,6 @@ +export { defaultPath, getAccountPath, HDNodeWallet, HDNodeVoidWallet, HDNodeWalletManager, } from "./hdwallet.js"; +export { isCrowdsaleJson, decryptCrowdsaleJson } from "./json-crowdsale.js"; +export { isKeystoreJson, decryptKeystoreJsonSync, decryptKeystoreJson, encryptKeystoreJson } from "./json-keystore.js"; +export { Mnemonic } from "./mnemonic.js"; +export { Wallet } from "./wallet.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/wallet/index.js.map b/lib.esm/wallet/index.js.map new file mode 100644 index 000000000..52505fa26 --- /dev/null +++ b/lib.esm/wallet/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,WAAW,EAEX,cAAc,EAEd,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,GACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EACH,cAAc,EACd,uBAAuB,EAAE,mBAAmB,EAC5C,mBAAmB,EACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/lib.esm/wallet/json-crowdsale.js b/lib.esm/wallet/json-crowdsale.js new file mode 100644 index 000000000..f14a0bc84 --- /dev/null +++ b/lib.esm/wallet/json-crowdsale.js @@ -0,0 +1,41 @@ +import { CBC, pkcs7Strip } from "aes-js"; +import { getAddress } from "../address/index.js"; +import { pbkdf2 } from "../crypto/index.js"; +import { id } from "../hash/id.js"; +import { logger } from "../utils/index.js"; +import { getPassword, looseArrayify, spelunk } from "./utils.js"; +export function isCrowdsaleJson(json) { + try { + const data = JSON.parse(json); + if (data.encseed) { + return true; + } + } + catch (error) { } + return false; +} +// See: https://github.com/ethereum/pyethsaletool +export function decryptCrowdsaleJson(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + // Ethereum Address + const address = getAddress(spelunk(data, "ethaddr:string!")); + // Encrypted Seed + const encseed = looseArrayify(spelunk(data, "encseed:string!")); + if (!encseed || (encseed.length % 16) !== 0) { + logger.throwArgumentError("invalid encseed", "json", json); + } + const key = logger.getBytes(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + // Decrypt the seed + const aesCbc = new CBC(key, iv); + const seed = pkcs7Strip(logger.getBytes(aesCbc.decrypt(encryptedSeed))); + // This wallet format is weird... Convert the binary encoded hex to a string. + let seedHex = ""; + for (let i = 0; i < seed.length; i++) { + seedHex += String.fromCharCode(seed[i]); + } + return { address, privateKey: id(seedHex) }; +} +//# sourceMappingURL=json-crowdsale.js.map \ No newline at end of file diff --git a/lib.esm/wallet/json-crowdsale.js.map b/lib.esm/wallet/json-crowdsale.js.map new file mode 100644 index 000000000..0df1a503c --- /dev/null +++ b/lib.esm/wallet/json-crowdsale.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json-crowdsale.js","sourceRoot":"","sources":["../../src.ts/wallet/json-crowdsale.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEzC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,EAAE,EAAE,MAAM,eAAe,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAQjE,MAAM,UAAU,eAAe,CAAC,IAAY;IACxC,IAAI;QACA,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,IAAI,CAAC,OAAO,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;KACrC;IAAC,OAAO,KAAK,EAAE,GAAG;IACnB,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,iDAAiD;AACjD,MAAM,UAAU,oBAAoB,CAAC,IAAY,EAAE,SAA8B;IAC7E,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,QAAQ,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;IAExC,mBAAmB;IACnB,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;IAE7D,iBAAiB;IACjB,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC,CAAC;IAChE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE;QACzC,MAAM,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;KAC9D;IAED,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAEzF,MAAM,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAChC,MAAM,aAAa,GAAG,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAExC,mBAAmB;IACnB,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAChC,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;IAExE,6EAA6E;IAC7E,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAClC,OAAO,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;KAC3C;IAED,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/lib.esm/wallet/json-keystore.js b/lib.esm/wallet/json-keystore.js new file mode 100644 index 000000000..51d0f5cb7 --- /dev/null +++ b/lib.esm/wallet/json-keystore.js @@ -0,0 +1,279 @@ +import { CTR } from "aes-js"; +import { getAddress } from "../address/index.js"; +import { keccak256, pbkdf2, randomBytes, scrypt, scryptSync } from "../crypto/index.js"; +import { computeAddress } from "../transaction/index.js"; +import { concat, hexlify, logger } from "../utils/index.js"; +import { getPassword, spelunk, uuidV4, zpad } from "./utils.js"; +import { version } from "../_version.js"; +const defaultPath = "m/44'/60'/0'/0/0"; +export function isKeystoreJson(json) { + try { + const data = JSON.parse(json); + const version = ((data.version != null) ? parseInt(data.version) : 0); + if (version === 3) { + return true; + } + } + catch (error) { } + return false; +} +function decrypt(data, key, ciphertext) { + const cipher = spelunk(data, "crypto.cipher:string"); + if (cipher === "aes-128-ctr") { + const iv = spelunk(data, "crypto.cipherparams.iv:data!"); + const aesCtr = new CTR(key, iv); + return hexlify(aesCtr.decrypt(ciphertext)); + } + return logger.throwError("unsupported cipher", "UNSUPPORTED_OPERATION", { + operation: "decrypt" + }); +} +function getAccount(data, _key) { + const key = logger.getBytes(_key); + const ciphertext = spelunk(data, "crypto.ciphertext:data!"); + const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2); + if (computedMAC !== spelunk(data, "crypto.mac:string!").toLowerCase()) { + return logger.throwArgumentError("incorrect password", "password", "[ REDACTED ]"); + } + const privateKey = decrypt(data, key.slice(0, 16), ciphertext); + const address = computeAddress(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (check.substring(0, 2) !== "0x") { + check = "0x" + check; + } + if (getAddress(check) !== address) { + logger.throwArgumentError("keystore address/privateKey mismatch", "address", data.address); + } + } + const account = { address, privateKey }; + // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase + const version = spelunk(data, "x-ethers.version:string"); + if (version === "0.1") { + const mnemonicKey = key.slice(32, 64); + const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!"); + const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!"); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + account.mnemonic = { + path: (spelunk(data, "x-ethers.path:string") || defaultPath), + locale: (spelunk(data, "x-ethers.locale:string") || "en"), + entropy: hexlify(logger.getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))) + }; + } + return account; +} +function getKdfParams(data) { + const kdf = spelunk(data, "crypto.kdf:string"); + if (kdf && typeof (kdf) === "string") { + const throwError = function (name, value) { + return logger.throwArgumentError("invalid key-derivation function parameters", name, value); + }; + if (kdf.toLowerCase() === "scrypt") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const N = spelunk(data, "crypto.kdfparams.n:int!"); + const r = spelunk(data, "crypto.kdfparams.r:int!"); + const p = spelunk(data, "crypto.kdfparams.p:int!"); + // Check for all required parameters + if (!N || !r || !p) { + return throwError("kdf", kdf); + } + // Make sure N is a power of 2 + if ((N & (N - 1)) !== 0) { + return throwError("N", N); + } + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + if (dkLen !== 32) { + return throwError("dklen", dkLen); + } + return { name: "scrypt", salt, N, r, p, dkLen: 64 }; + } + else if (kdf.toLowerCase() === "pbkdf2") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const prf = spelunk(data, "crypto.kdfparams.prf:string!"); + const algorithm = prf.split("-").pop(); + if (algorithm !== "sha256" && algorithm !== "sha512") { + return throwError("prf", prf); + } + const count = spelunk(data, "crypto.kdfparams.c:int!"); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + if (dkLen !== 32) { + throwError("dklen", dkLen); + } + return { name: "pbkdf2", salt, count, dkLen, algorithm }; + } + } + return logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf); +} +export function decryptKeystoreJsonSync(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getKdfParams(data); + if (params.name === "pbkdf2") { + const { salt, count, dkLen, algorithm } = params; + const key = pbkdf2(password, salt, count, dkLen, algorithm); + return getAccount(data, key); + } + else if (params.name === "scrypt") { + const { salt, N, r, p, dkLen } = params; + const key = scryptSync(password, salt, N, r, p, dkLen); + return getAccount(data, key); + } + throw new Error("unreachable"); +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +export async function decryptKeystoreJson(json, _password, progress) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getKdfParams(data); + if (params.name === "pbkdf2") { + if (progress) { + progress(0); + await stall(0); + } + const { salt, count, dkLen, algorithm } = params; + const key = pbkdf2(password, salt, count, dkLen, algorithm); + if (progress) { + progress(1); + await stall(0); + } + return getAccount(data, key); + } + else if (params.name === "scrypt") { + const { salt, N, r, p, dkLen } = params; + const key = await scrypt(password, salt, N, r, p, dkLen, progress); + return getAccount(data, key); + } + throw new Error("unreachable"); +} +export async function encryptKeystoreJson(account, password, options, progressCallback) { + // Check the address matches the private key + //if (getAddress(account.address) !== computeAddress(account.privateKey)) { + // throw new Error("address/privateKey mismatch"); + //} + // Check the mnemonic (if any) matches the private key + /* + if (hasMnemonic(account)) { + const mnemonic = account.mnemonic; + const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath); + + if (node.privateKey != account.privateKey) { + throw new Error("mnemonic mismatch"); + } + } + */ + // The options are optional, so adjust the call as needed + if (typeof (options) === "function" && !progressCallback) { + progressCallback = options; + options = {}; + } + if (!options) { + options = {}; + } + const privateKey = logger.getBytes(account.privateKey, "privateKey"); + const passwordBytes = getPassword(password); + /* + let mnemonic: null | Mnemonic = null; + let entropy: Uint8Array = null + let path: string = null; + let locale: string = null; + if (hasMnemonic(account)) { + const srcMnemonic = account.mnemonic; + entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en")); + path = srcMnemonic.path || defaultPath; + locale = srcMnemonic.locale || "en"; + mnemonic = Mnemonic.from( + } + */ + // Check/generate the salt + const salt = (options.salt != null) ? logger.getBytes(options.salt, "options.slat") : randomBytes(32); + // Override initialization vector + const iv = (options.iv != null) ? logger.getBytes(options.iv, "options.iv") : randomBytes(16); + if (iv.length !== 16) { + logger.throwArgumentError("invalid options.iv", "options.iv", options.iv); + } + // Override the uuid + const uuidRandom = (options.uuid != null) ? logger.getBytes(options.uuid, "options.uuid") : randomBytes(16); + if (uuidRandom.length !== 16) { + logger.throwArgumentError("invalid options.uuid", "options.uuid", options.iv); + } + if (uuidRandom.length !== 16) { + throw new Error("invalid uuid"); + } + // Override the scrypt password-based key derivation function parameters + let N = (1 << 17), r = 8, p = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N = options.scrypt.N; + } + if (options.scrypt.r) { + r = options.scrypt.r; + } + if (options.scrypt.p) { + p = options.scrypt.p; + } + } + // We take 64 bytes: + // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) + // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet) + const _key = await scrypt(passwordBytes, salt, N, r, p, 64, progressCallback); + const key = logger.getBytes(_key); + // This will be used to encrypt the wallet (as per Web3 secret storage) + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + // Encrypt the private key + const aesCtr = new CTR(derivedKey, iv); + const ciphertext = logger.getBytes(aesCtr.encrypt(privateKey)); + // Compute the message authentication code, used to check the password + const mac = keccak256(concat([macPrefix, ciphertext])); + // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition + const data = { + address: account.address.substring(2).toLowerCase(), + id: uuidV4(uuidRandom), + version: 3, + Crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: hexlify(iv).substring(2), + }, + ciphertext: hexlify(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: hexlify(salt).substring(2), + n: N, + dklen: 32, + p: p, + r: r + }, + mac: mac.substring(2) + } + }; + // If we have a mnemonic, encrypt it into the JSON wallet + if (account.mnemonic) { + const client = (options.client != null) ? options.client : `ethers/${version}`; + const path = account.mnemonic.path || defaultPath; + const locale = account.mnemonic.locale || "en"; + const mnemonicKey = key.slice(32, 64); + const entropy = logger.getBytes(account.mnemonic.entropy, "account.mnemonic.entropy"); + const mnemonicIv = randomBytes(16); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + const mnemonicCiphertext = logger.getBytes(mnemonicAesCtr.encrypt(entropy)); + const now = new Date(); + const timestamp = (now.getUTCFullYear() + "-" + + zpad(now.getUTCMonth() + 1, 2) + "-" + + zpad(now.getUTCDate(), 2) + "T" + + zpad(now.getUTCHours(), 2) + "-" + + zpad(now.getUTCMinutes(), 2) + "-" + + zpad(now.getUTCSeconds(), 2) + ".0Z"); + const gethFilename = ("UTC--" + timestamp + "--" + data.address); + data["x-ethers"] = { + client, gethFilename, path, locale, + mnemonicCounter: hexlify(mnemonicIv).substring(2), + mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), + version: "0.1" + }; + } + return JSON.stringify(data); +} +//# sourceMappingURL=json-keystore.js.map \ No newline at end of file diff --git a/lib.esm/wallet/json-keystore.js.map b/lib.esm/wallet/json-keystore.js.map new file mode 100644 index 000000000..8ac7b5e58 --- /dev/null +++ b/lib.esm/wallet/json-keystore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json-keystore.js","sourceRoot":"","sources":["../../src.ts/wallet/json-keystore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAE7B,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAKhE,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAEzC,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAoCvC,MAAM,UAAU,cAAc,CAAC,IAAY;IACvC,IAAI;QACA,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAA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AAC"} \ No newline at end of file diff --git a/lib.esm/wallet/mnemonic.js b/lib.esm/wallet/mnemonic.js new file mode 100644 index 000000000..d364fc2ad --- /dev/null +++ b/lib.esm/wallet/mnemonic.js @@ -0,0 +1,124 @@ +import { pbkdf2, sha256 } from "../crypto/index.js"; +import { defineProperties, hexlify, logger, toUtf8Bytes } from "../utils/index.js"; +import { langEn } from "../wordlists/lang-en.js"; +// Returns a byte with the MSB bits set +function getUpperMask(bits) { + return ((1 << bits) - 1) << (8 - bits) & 0xff; +} +// Returns a byte with the LSB bits set +function getLowerMask(bits) { + return ((1 << bits) - 1) & 0xff; +} +function mnemonicToEntropy(mnemonic, wordlist = langEn) { + logger.assertNormalize("NFKD"); + if (wordlist == null) { + wordlist = langEn; + } + const words = wordlist.split(mnemonic); + if ((words.length % 3) !== 0 || words.length < 12 || words.length > 24) { + logger.throwArgumentError("invalid mnemonic length", "mnemonic", "[ REDACTED ]"); + } + const entropy = new Uint8Array(Math.ceil(11 * words.length / 8)); + let offset = 0; + for (let i = 0; i < words.length; i++) { + let index = wordlist.getWordIndex(words[i].normalize("NFKD")); + if (index === -1) { + logger.throwArgumentError(`invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); + } + for (let bit = 0; bit < 11; bit++) { + if (index & (1 << (10 - bit))) { + entropy[offset >> 3] |= (1 << (7 - (offset % 8))); + } + offset++; + } + } + const entropyBits = 32 * words.length / 3; + const checksumBits = words.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum = logger.getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { + logger.throwArgumentError("invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); + } + return hexlify(entropy.slice(0, entropyBits / 8)); +} +function entropyToMnemonic(entropy, wordlist = langEn) { + if ((entropy.length % 4) || entropy.length < 16 || entropy.length > 32) { + logger.throwArgumentError("invalid entropy size", "entropy", "[ REDACTED ]"); + } + if (wordlist == null) { + wordlist = langEn; + } + const indices = [0]; + let remainingBits = 11; + for (let i = 0; i < entropy.length; i++) { + // Consume the whole byte (with still more to go) + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + // This byte will complete an 11-bit index + } + else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); + // Start the next word + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; + } + } + // Compute the checksum bits + const checksumBits = entropy.length / 4; + const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); + // Shift the checksum into the word indices + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= (checksum >> (8 - checksumBits)); + return wordlist.join(indices.map((index) => wordlist.getWord(index))); +} +const _guard = {}; +export class Mnemonic { + phrase; + password; + wordlist; + entropy; + constructor(guard, entropy, phrase, password, wordlist) { + if (password == null) { + password = ""; + } + if (wordlist == null) { + wordlist = langEn; + } + logger.assertPrivate(guard, _guard, "Mnemonic"); + defineProperties(this, { phrase, password, wordlist, entropy }); + } + computeSeed() { + const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD"); + return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); + } + static fromPhrase(phrase, password, wordlist) { + // Normalize the case and space; throws if invalid + const entropy = mnemonicToEntropy(phrase, wordlist); + phrase = entropyToMnemonic(logger.getBytes(entropy), wordlist); + return new Mnemonic(_guard, entropy, phrase, password, wordlist); + } + static fromEntropy(_entropy, password, wordlist) { + const entropy = logger.getBytes(_entropy, "entropy"); + const phrase = entropyToMnemonic(entropy, wordlist); + return new Mnemonic(_guard, hexlify(entropy), phrase, password, wordlist); + } + static entropyToPhrase(_entropy, wordlist) { + const entropy = logger.getBytes(_entropy, "entropy"); + return entropyToMnemonic(entropy, wordlist); + } + static phraseToEntropy(phrase, wordlist) { + return mnemonicToEntropy(phrase, wordlist); + } + static isValidMnemonic(phrase, wordlist) { + try { + mnemonicToEntropy(phrase, wordlist); + return true; + } + catch (error) { } + return false; + } +} +//# sourceMappingURL=mnemonic.js.map \ No newline at end of file diff --git a/lib.esm/wallet/mnemonic.js.map b/lib.esm/wallet/mnemonic.js.map new file mode 100644 index 000000000..e4ec250b8 --- /dev/null +++ b/lib.esm/wallet/mnemonic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mnemonic.js","sourceRoot":"","sources":["../../src.ts/wallet/mnemonic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAMjD,uCAAuC;AACvC,SAAS,YAAY,CAAC,IAAY;IAC/B,OAAO,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;AACjD,CAAC;AAED,uCAAuC;AACvC,SAAS,YAAY,CAAC,IAAY;IAC/B,OAAO,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC;AACnC,CAAC;AAGD,SAAS,iBAAiB,CAAC,QAAgB,EAAE,WAA4B,MAAM;IAC3E,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAE/B,IAAI,QAAQ,IAAI,IAAI,EAAE;QAAE,QAAQ,GAAG,MAAM,CAAC;KAAE;IAE5C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,EAAE,IAAI,KAAK,CAAC,MAAM,GAA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,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QACrD,OAAO,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,MAAc,EAAE,QAA0B;QAC7D,OAAO,iBAAiB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,MAAc,EAAE,QAA0B;QAC7D,IAAI;YACA,iBAAiB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YACpC,OAAO,IAAI,CAAC;SACf;QAAC,OAAO,KAAK,EAAE,GAAG;QACnB,OAAO,KAAK,CAAC;IACjB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/wallet/utils.js b/lib.esm/wallet/utils.js new file mode 100644 index 000000000..75b899404 --- /dev/null +++ b/lib.esm/wallet/utils.js @@ -0,0 +1,137 @@ +import { hexlify, logger, toUtf8Bytes } from "../utils/index.js"; +export function looseArrayify(hexString) { + if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') { + hexString = '0x' + hexString; + } + return logger.getBytesCopy(hexString); +} +export function zpad(value, length) { + value = String(value); + while (value.length < length) { + value = '0' + value; + } + return value; +} +export function getPassword(password) { + if (typeof (password) === 'string') { + return toUtf8Bytes(password, "NFKC"); + } + return logger.getBytesCopy(password); +} +export function spelunk(object, _path) { + const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); + if (match == null) { + return logger.throwArgumentError("invalid path", "path", _path); + } + const path = match[1]; + const type = match[3]; + const reqd = (match[4] === "!"); + let cur = object; + for (const comp of path.toLowerCase().split('.')) { + // Search for a child object with a case-insensitive matching key + if (Array.isArray(cur)) { + if (!comp.match(/^[0-9]+$/)) { + break; + } + cur = cur[parseInt(comp)]; + } + else if (typeof (cur) === "object") { + let found = null; + for (const key in cur) { + if (key.toLowerCase() === comp) { + found = cur[key]; + break; + } + } + cur = found; + } + else { + cur = null; + } + if (cur == null) { + break; + } + } + if (reqd && cur == null) { + logger.throwArgumentError("missing required value", "path", path); + } + if (type && cur != null) { + if (type === "int") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9]+$/)) { + return parseInt(cur); + } + else if (Number.isSafeInteger(cur)) { + return cur; + } + } + if (type === "number") { + if (typeof (cur) === "string" && cur.match(/^-?[0-9.]*$/)) { + return parseFloat(cur); + } + } + if (type === "data") { + if (typeof (cur) === "string") { + return looseArrayify(cur); + } + } + if (type === "array" && Array.isArray(cur)) { + return cur; + } + if (type === typeof (cur)) { + return cur; + } + logger.throwArgumentError(`wrong type found for ${type} `, "path", path); + } + return cur; +} +/* +export function follow(object: any, path: string): null | string { + let currentChild = object; + + for (const comp of path.toLowerCase().split('/')) { + + // Search for a child object with a case-insensitive matching key + let matchingChild = null; + for (const key in currentChild) { + if (key.toLowerCase() === comp) { + matchingChild = currentChild[key]; + break; + } + } + + if (matchingChild === null) { return null; } + + currentChild = matchingChild; + } + + return currentChild; +} + +// "path/to/something:type!" +export function followRequired(data: any, path: string): string { + const value = follow(data, path); + if (value != null) { return value; } + return logger.throwArgumentError("invalid value", `data:${ path }`, + JSON.stringify(data)); +} +*/ +// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4) +export function uuidV4(randomBytes) { + const bytes = logger.getBytes(randomBytes, "randomBytes"); + // Section: 4.1.3: + // - time_hi_and_version[12:16] = 0b0100 + bytes[6] = (bytes[6] & 0x0f) | 0x40; + // Section 4.4 + // - clock_seq_hi_and_reserved[6] = 0b0 + // - clock_seq_hi_and_reserved[7] = 0b1 + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const value = hexlify(bytes); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34), + ].join("-"); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib.esm/wallet/utils.js.map b/lib.esm/wallet/utils.js.map new file mode 100644 index 000000000..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,OAAO,CAAC,KAAK,CAAC,CAAC;IAE7B,OAAO;QACJ,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;QACtB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QACvB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QACvB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;QACvB,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC;KACzB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/lib.esm/wallet/wallet.js b/lib.esm/wallet/wallet.js new file mode 100644 index 000000000..192189dc9 --- /dev/null +++ b/lib.esm/wallet/wallet.js @@ -0,0 +1,165 @@ +import { randomBytes, SigningKey } from "../crypto/index.js"; +import { computeAddress } from "../transaction/index.js"; +import { isHexString, logger } from "../utils/index.js"; +import { BaseWallet } from "./base-wallet.js"; +import { HDNodeWallet } from "./hdwallet.js"; +import { decryptCrowdsaleJson, isCrowdsaleJson } from "./json-crowdsale.js"; +import { decryptKeystoreJson, decryptKeystoreJsonSync, isKeystoreJson } from "./json-keystore.js"; +import { Mnemonic } from "./mnemonic.js"; +function tryWallet(value) { + try { + if (!value || !value.signingKey) { + return null; + } + const key = trySigningKey(value.signingKey); + if (key == null || computeAddress(key.publicKey) !== value.address) { + return null; + } + if (value.mnemonic) { + const wallet = HDNodeWallet.fromMnemonic(value.mnemonic); + if (wallet.privateKey !== key.privateKey) { + return null; + } + } + return value; + } + catch (e) { + console.log(e); + } + return null; +} +// Try using value as mnemonic to derive the defaultPath HDodeWallet +function tryMnemonic(value) { + try { + if (value == null || typeof (value.phrase) !== "string" || + typeof (value.password) !== "string" || + value.wordlist == null) { + return null; + } + return HDNodeWallet.fromPhrase(value.phrase, value.password, null, value.wordlist); + } + catch (error) { + console.log(error); + } + return null; +} +function trySigningKey(value) { + try { + if (!value || !isHexString(value.privateKey, 32)) { + return null; + } + const key = value.privateKey; + if (SigningKey.computePublicKey(key) !== value.publicKey) { + return null; + } + return new SigningKey(key); + } + catch (e) { + console.log(e); + } + return null; +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); }); +} +export class Wallet extends BaseWallet { + #mnemonic; + constructor(key, provider) { + let signingKey = null; + let mnemonic = null; + // A normal private key + if (typeof (key) === "string") { + signingKey = new SigningKey(key); + } + // Try Wallet + if (signingKey == null) { + const wallet = tryWallet(key); + if (wallet) { + signingKey = wallet.signingKey; + mnemonic = wallet.mnemonic || null; + } + } + // Try Mnemonic, with the defaultPath wallet + if (signingKey == null) { + const wallet = tryMnemonic(key); + if (wallet) { + signingKey = wallet.signingKey; + mnemonic = wallet.mnemonic || null; + } + } + // A signing key + if (signingKey == null) { + signingKey = trySigningKey(key); + } + if (signingKey == null) { + logger.throwArgumentError("invalid key", "key", "[ REDACTED ]"); + } + super(signingKey, provider); + this.#mnemonic = mnemonic; + } + // Store this in a getter to reduce visibility in console.log + get mnemonic() { return this.#mnemonic; } + connect(provider) { + return new Wallet(this, provider); + } + async encrypt(password, options, progressCallback) { + throw new Error("TODO"); + } + encryptSync(password, options) { + throw new Error("TODO"); + } + static async fromEncryptedJson(json, password, progress) { + let account = null; + if (isKeystoreJson(json)) { + account = await decryptKeystoreJson(json, password, progress); + } + else if (isCrowdsaleJson(json)) { + if (progress) { + progress(0); + await stall(0); + } + account = decryptCrowdsaleJson(json, password); + if (progress) { + progress(1); + await stall(0); + } + } + else { + return logger.throwArgumentError("invalid JSON wallet", "json", "[ REDACTED ]"); + } + const wallet = new Wallet(account.privateKey); + if (wallet.address !== account.address) { + logger.throwArgumentError("address/privateKey mismatch", "json", "[ REDACTED ]"); + } + // @TODO: mnemonic + return wallet; + } + static fromEncryptedJsonSync(json, password) { + let account = null; + if (isKeystoreJson(json)) { + account = decryptKeystoreJsonSync(json, password); + } + else if (isCrowdsaleJson(json)) { + account = decryptCrowdsaleJson(json, password); + } + else { + return logger.throwArgumentError("invalid JSON wallet", "json", "[ REDACTED ]"); + } + const wallet = new Wallet(account.privateKey); + if (wallet.address !== account.address) { + logger.throwArgumentError("address/privateKey mismatch", "json", "[ REDACTED ]"); + } + // @TODO: mnemonic + return wallet; + } + static createRandom(provider, password, wordlist) { + return new Wallet(Mnemonic.fromEntropy(randomBytes(16), password, wordlist), provider); + } + static fromMnemonic(mnemonic, provider) { + return new Wallet(mnemonic, provider); + } + static fromPhrase(phrase, provider, password = "", wordlist) { + return new Wallet(Mnemonic.fromPhrase(phrase, password, wordlist), provider); + } +} +//# sourceMappingURL=wallet.js.map \ No newline at end of file diff --git a/lib.esm/wallet/wallet.js.map b/lib.esm/wallet/wallet.js.map new file mode 100644 index 000000000..37ab75f5b --- /dev/null +++ b/lib.esm/wallet/wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wallet.js","sourceRoot":"","sources":["../../src.ts/wallet/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAG,MAAM,qBAAqB,CAAC;AAC7E,OAAO,EACH,mBAAmB,EAAE,uBAAuB,EAAE,cAAc,EAC/D,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAUzC,SAAS,SAAS,CAAC,KAAU;IACzB,IAAI;QACA,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE;YAAE,OAAO,IAAI,CAAC;SAAE;QACjD,MAAM,GAAG,GAAG,a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B,EAAE,QAAwB,EAAE,QAA0B;QAChG,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;IAC3F,CAAC;IAED,MAAM,CAAC,YAAY,CAAC,QAAkB,EAAE,QAA0B;QAC9D,OAAO,IAAI,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAc,EAAE,QAA0B,EAAE,QAAQ,GAAG,EAAE,EAAE,QAAmB;QAC5F,OAAO,IAAI,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;IACjF,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/wordlists/bit-reader.js b/lib.esm/wordlists/bit-reader.js new file mode 100644 index 000000000..b735dcbdf --- /dev/null +++ b/lib.esm/wordlists/bit-reader.js @@ -0,0 +1,29 @@ +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +export function decodeBits(width, data) { + const maxValue = (1 << width) - 1; + const result = []; + let accum = 0, bits = 0, flood = 0; + for (let i = 0; i < data.length; i++) { + // Accumulate 6 bits of data + accum = ((accum << 6) | Base64.indexOf(data[i])); + bits += 6; + // While we have enough for a word... + while (bits >= width) { + // ...read the word + const value = (accum >> (bits - width)); + accum &= (1 << (bits - width)) - 1; + bits -= width; + // A value of 0 indicates we exceeded maxValue, it + // floods over into the next value + if (value === 0) { + flood += maxValue; + } + else { + result.push(value + flood); + flood = 0; + } + } + } + return result; +} +//# sourceMappingURL=bit-reader.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/bit-reader.js.map b/lib.esm/wordlists/bit-reader.js.map new file mode 100644 index 000000000..ad99187e9 --- /dev/null +++ b/lib.esm/wordlists/bit-reader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bit-reader.js","sourceRoot":"","sources":["../../src.ts/wordlists/bit-reader.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,GAAG,kEAAkE,CAAC;AAElF,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,IAAY;IAClD,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,MAAM,GAAkB,EAAG,CAAC;IAClC,IAAI,KAAK,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;IACnC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAElC,4BAA4B;QAC5B,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACjD,IAAI,IAAI,CAAC,CAAC;QAEV,qCAAqC;QACrC,OAAO,IAAI,IAAI,KAAK,EAAE;YAClB,mBAAmB;YACnB,MAAM,KAAK,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC;YACxC,KAAK,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC;YACnC,IAAI,IAAI,KAAK,CAAC;YAEd,kDAAkD;YAClD,kCAAkC;YAClC,IAAI,KAAK,KAAK,CAAC,EAAE;gBACb,KAAK,IAAI,QAAQ,CAAC;aACrB;iBAAM;gBACH,MAAM,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC;gBAC3B,KAAK,GAAG,CAAC,CAAC;aACb;SACJ;KACJ;IAED,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/decode-owl.js b/lib.esm/wordlists/decode-owl.js new file mode 100644 index 000000000..c0332a243 --- /dev/null +++ b/lib.esm/wordlists/decode-owl.js @@ -0,0 +1,49 @@ +import { assertArgument } from "../utils/logger.js"; +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words, sep) { + let initial = 97; + return words.reduce((accum, word) => { + if (word === sep) { + initial++; + } + else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } + else { + initial = 97; + accum.push(word); + } + return accum; + }, []); +} +export function decode(data, subs) { + // Replace all the substitutions with their expanded form + for (let i = subsChrs.length - 1; i >= 0; i--) { + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); + } + // Get all tle clumps; each suffix, first-increment and second-increment + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { + if (semi) { + for (let i = parseInt(semi); i >= 0; i--) { + clumps.push(";"); + } + } + else { + clumps.push(item.toLowerCase()); + } + return ""; + }); + /* c8 ignore start */ + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); + } + /* c8 ignore stop */ + return unfold(unfold(clumps, ";"), ":"); +} +export function decodeOwl(data) { + assertArgument(data[0] === "0", "unsupported auwl data", "data", data); + return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); +} +//# sourceMappingURL=decode-owl.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/decode-owl.js.map b/lib.esm/wordlists/decode-owl.js.map new file mode 100644 index 000000000..7f67f63ce --- /dev/null +++ b/lib.esm/wordlists/decode-owl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-owl.js","sourceRoot":"","sources":["../../src.ts/wordlists/decode-owl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,MAAM,QAAQ,GAAG,+BAA+B,CAAC;AACjD,MAAM,IAAI,GAAG,WAAW,CA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GAAG,CAAC,CAAC;aAAE;SAClE;aAAM;YACH,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;SACnC;QACD,OAAO,EAAE,CAAC;IACd,CAAC,CAAC,CAAC;IACH,qBAAqB;IACrB,IAAI,QAAQ,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,cAAe,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAE,EAAE,CAAC,CAAC;KAAE;IAC9E,oBAAoB;IAEpB,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,IAAY;IAClC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,uBAAuB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAEvE,OAAO,MAAM,CACT,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EACvC,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AACpD,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/decode-owla.js b/lib.esm/wordlists/decode-owla.js new file mode 100644 index 000000000..e24cc75ee --- /dev/null +++ b/lib.esm/wordlists/decode-owla.js @@ -0,0 +1,25 @@ +import { assertArgument } from "../utils/logger.js"; +import { decodeBits } from "./bit-reader.js"; +import { decodeOwl } from "./decode-owl.js"; +export function decodeOwlA(data, accents) { + let words = decodeOwl(data).join(","); + // Inject the accents + accents.split(/,/g).forEach((accent) => { + const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); + assertArgument(match !== null, "internal error parsing accents", "accents", accents); + let posOffset = 0; + const positions = decodeBits(parseInt(match[3]), match[4]); + const charCode = parseInt(match[2]); + const regex = new RegExp(`([${match[1]}])`, "g"); + words = words.replace(regex, (all, letter) => { + const rem = --positions[posOffset]; + if (rem === 0) { + letter = String.fromCharCode(letter.charCodeAt(0), charCode); + posOffset++; + } + return letter; + }); + }); + return words.split(","); +} +//# sourceMappingURL=decode-owla.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/decode-owla.js.map b/lib.esm/wordlists/decode-owla.js.map new file mode 100644 index 000000000..d932cbd40 --- /dev/null +++ b/lib.esm/wordlists/decode-owla.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-owla.js","sourceRoot":"","sources":["../../src.ts/wordlists/decode-owla.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,OAAe;IACpD,IAAI,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEtC,qBAAqB;IACrB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QAEnC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;QAC5D,cAAc,CAAC,KAAK,KAAK,IAAI,EAAE,gCAAgC,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAErF,IAAI,SAAS,GAAG,CAAC,CAAC;QAClB,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,KAAM,KAAK,CAAC,CAAC,CAAE,IAAI,EAAE,GAAG,CAAC,CAAC;QACnD,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACzC,MAAM,GAAG,GAAG,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;YACnC,IAAI,GAAG,KAAK,CAAC,EAAE;gBACX,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;gBAC7D,SAAS,EAAE,CAAC;aACf;YACD,OAAO,MAAM,CAAC;QAClB,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/generation/encode-latin.js b/lib.esm/wordlists/generation/encode-latin.js new file mode 100644 index 000000000..ecd8dbedc --- /dev/null +++ b/lib.esm/wordlists/generation/encode-latin.js @@ -0,0 +1,344 @@ +// OWL Data Format +// +// The Official WordList data format exported by this encoder +// encodes sorted latin-1 words (letters only) based on the +// fact that sorted words have prefixes with substantial +// overlap. +// +// For example, the words: +// [ Another, Apple, Apricot, Bread ] +// could be folded once with a single special character, such +// as ":" to yield: +// [ nother, pple, pricot, :, read ]. +// The First letter has been removed, but can be inferred by +// starting at A and incrementing to the next letter when ":" +// is encountered. +// +// The fold operation can be repeated for large sets as even within +// each folded set, there is substatial overlap in prefix. With the +// second special symbol ";", we get: +// [ ; x 13, other, :, ple, ricot, :, ; x 18, ead ] +// which can be further compressed by using numbers instead of the +// special character: +// [ 13, other, :, ple, ricot, :, 18, ead ] +// and to keep all values within a single byte, we only allow a +// maximum value of 10 (using 0 through 9 to represent 1 through 10), +// we get: +// [ 9, 2, other, :, ple, ricot, :, 9, 7, ead ] +// and we use camel-case to imply the bounrary, giving the final string: +// "92Other:PleRicot:97Ead" +// +// Once the entire latin-1 set has been collapsed, we use the remaining +// printable characters (except " and \, which require 2 bytes to represent +// in string) to substiture for the most common 2-letter pairs of letters +// in the string. +// +// OWLA Accent Format +// +// OWLA first removes all accents, and encodes that data using the OWL +// data format and encodes the accents as a base-64 series of 6-bit +// packed bits representing the distance from one followed letter to the +// next. +// +// For example, the acute accent in a given language may follow either +// a or e, in which case the follow-set is "ae". Each letter in the entire +// set is indexed, so the set of words with the accents: +// "thisA/ppleDoe/sNotMa/tterToMe/" +// " 1^ 2^ 3^ 4^ 5^ 6^ " <-- follow-set members, ALL a's and e's +// which gives the positions: +// [ 0, 2, 3, 4, 6 ] +// which then reduce to the distances +// [ 0, 2, 1, 1, 2 ] +// each of which fit into a 2-bit value, so this can be encoded as the +// base-64 encoded string: +// 00 10 01 01 10 = 001001 1010xx +// +// The base-64 set used has all number replaced with their +// shifted-counterparts to prevent comflicting with the numbers used in +// the fold operation to indicate the number of ";". +import fs from "fs"; +import { id } from "../../hash/id.js"; +import { decodeOwl } from "../decode-owl.js"; +import { decodeOwlA } from "../decode-owla.js"; +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z'`]*$/i; +function fold(words, sep) { + const output = []; + let initial = 97; + for (const word of words) { + if (word.match(Word)) { + while (initial < word.charCodeAt(0)) { + initial++; + output.push(sep); + } + output.push(word.substring(1)); + } + else { + initial = 97; + output.push(word); + } + } + return output; +} +function camelcase(words) { + return words.map((word) => { + if (word.match(Word)) { + return word[0].toUpperCase() + word.substring(1); + } + else { + return word; + } + }).join(""); +} +//let cc = 0, ce = 0; +/* +function getChar(c: string): string { + //if (c === "e") { ce++; } + if (c >= 'a' && c <= 'z') { return c; } + if (c.charCodeAt(1)) { + throw new Error(`bad char: "${ c }"`); + } + //cc++; + return ""; + if (c.charCodeAt(0) === 768) { return "`"; } + if (c.charCodeAt(0) === 769) { return "'"; } + if (c.charCodeAt(0) === 771) { return "~"; } + throw new Error(`Unsupported character: ${ c } (${ c.charCodeAt(0) }, ${ c.charCodeAt(1) })`); +} +function mangle(text: string): { word: string, special: string } { + const result: Array = [ ]; + for (let i = 0; i < text.length; i++) { + const c = getChar(text[i]); + result.push(c); + } + + const word = result.join(""); + if (word[1] >= 'a' && word[1] <= 'z') { return { word, special: " " }; } + return { word: word[0] + word.substring(2), special: word[1] }; +} +*/ +/* + Store: [ accent ][ targets ][ rle data; base64-tail ] + ` ae 3, 100 = (63, 37), 15 + ~ n 63, 64 = (63, 1), 27 +*/ +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +export class BitWriter { + width; + #data; + #bitLength; + constructor(width) { + this.width = width; + this.#data = []; + this.#bitLength = 0; + } + write(value) { + const maxValue = ((1 << this.width) - 1); + while (value > maxValue) { + this.#data.push(0); + this.#bitLength += this.width; + value -= maxValue; + } + this.#data.push(value); + this.#bitLength += this.width; + } + get length() { + return 1 + Math.trunc((this.#bitLength + 5) / 6); + } + get data() { + let result = String(this.width); + let bits = 0; + let accum = 0; + const data = this.#data.slice(); + let bitMod = this.#bitLength % 6; + while (bitMod !== 0 && bitMod < 6) { + data.push(0); + bitMod += this.width; + } + for (const value of data) { + accum <<= this.width; + accum |= value; + bits += this.width; + if (bits < 6) { + continue; + } + result += Base64[accum >> (bits - 6)]; + bits -= 6; + accum &= ((1 << bits) - 1); + } + if (result.length !== this.length) { + throw new Error(`Hmm: ${this.length} ${result.length} ${result}`); + } + return result; + } +} +; +function sorted(text) { + const letters = text.split(""); + letters.sort(); + return letters.join(""); +} +// if (c.charCodeAt(0) === 768) { return "`"; } +// if (c.charCodeAt(0) === 769) { return "'"; } +// if (c.charCodeAt(0) === 771) { return "~"; } +export function extractAccents(words) { + // Build a list that maps accents to the letters it can follow + const followsMap = new Map(); + for (const word of words) { + for (let i = 0; i < word.length; i++) { + const c = word[i]; + if (c >= 'a' && c <= 'z') { + continue; + } + // Make sure this positions and codepoint make sense + if (c.charCodeAt(1)) { + throw new Error(`unsupported codepoint: "${c}"`); + } + if (i === 0) { + throw new Error(`unmatched accent: ${c}`); + } + const ac = c.charCodeAt(0), lastLetter = word[i - 1]; + ; + const follows = (followsMap.get(ac) || ""); + if (follows.indexOf(lastLetter) === -1) { + followsMap.set(ac, sorted(follows + lastLetter)); + } + } + } + // Build the positions of each follow-set for those accents + const positionsMap = new Map(); + for (const [accent, follows] of followsMap) { + let count = 0; + for (const word of words) { + for (let i = 0; i < word.length; i++) { + const c = word[i], ac = c.charCodeAt(0); + if (follows.indexOf(c) >= 0) { + count++; + } + if (ac === accent) { + const pos = positionsMap.get(ac) || []; + pos.push(count); + positionsMap.set(ac, pos); + } + } + } + } + const accents = []; + for (const [accent, follows] of followsMap) { + let last = -1; + const positions = (positionsMap.get(accent) || []).map((value, index) => { + const delta = value - last; + last = value; + if (index === 0) { + return value; + } + return delta; + }); + // Find the best encoding of the position data + let positionData = ""; + for (let i = 2; i < 7; i++) { + const bitWriter = new BitWriter(i); + for (const p of positions) { + bitWriter.write(p); + } + if (positionData === "" || bitWriter.length < positionData.length) { + positionData = bitWriter.data; + } + } + const positionsLength = positions.length; + const positionDataLength = positionData.length; + accents.push({ accent, follows, positions, positionsLength, positionData, positionDataLength }); + } + words = words.map((word) => { + let result = ""; + for (let i = 0; i < word.length; i++) { + const c = word[i]; + if (c >= 'a' && c <= 'z') { + result += c; + } + } + return result; + }); + return { accents, words }; +} +// Encode Official WordList +export function encodeOwl(words) { + // Fold the sorted words by indicating delta for the first 2 letters + let data = camelcase(fold(fold(words, ":"), ";")); + // Replace semicolons with counts (e.g. ";;;" with "3") + data = data.replace(/(;+)/g, (all, semis) => { + let result = ""; + while (semis.length) { + let count = semis.length; + if (count > 10) { + count = 10; + } + result += String(count - 1); + semis = semis.substring(count); + } + return result; + }); + // Finds the best option for a shortcut replacement using the + // unused ascii7 characters + function findBest() { + const tally = {}; + const l = 2; + for (let i = l; i < data.length; i++) { + const key = data.substring(i - l, i); + tally[key] = (tally[key] || 0) + 1; + } + const sorted = Object.keys(tally).map((text) => { + return { text, count: tally[text], save: (tally[text] * (text.length - 1)) }; + }); + sorted.sort((a, b) => (b.save - a.save)); + return sorted[0].text; + } + // Make substitutions + let subs = ""; + for (let i = 0; i < subsChrs.length; i++) { + const n = subsChrs[i], o = findBest(); + subs += o; + data = data.split(o).join(n); + } + return { data, subs }; +} +// Returns either: +// - OWL data for accent-free latin-1: { data, accentds: "" } +// - OWLA data for accented latin-1: { data, accents } +function encodeWords(_words) { + const { accents, words } = extractAccents(_words); + const { data, subs } = encodeOwl(words); + const accentData = accents.map(({ accent, follows, positionData }) => { + return `${follows}${accent}${positionData}`; + }).join(","); + return { + data: `0${subs}${data}`, + accents: accentData + }; +} +// CLI +const content = fs.readFileSync(process.argv[2]).toString(); +const words = content.split("\n").filter(Boolean); +const { data, accents } = encodeWords(words); +if (accents) { + const rec = decodeOwlA(data, accents); + console.log("DATA: ", JSON.stringify(data)); + console.log("ACCENTS: ", JSON.stringify(accents)); + console.log("LENGTH: ", data.length); + console.log("CHECKSUM: ", id(content)); + console.log("RATIO: ", Math.trunc(100 * data.length / content.length) + "%"); + if (rec.join("\n") !== words.join("\n")) { + throw new Error("no match!"); + } +} +else { + const rec = decodeOwl(data); + console.log("DATA: ", JSON.stringify(data)); + console.log("LENGTH: ", data.length); + console.log("CHECKSUM: ", id(content)); + console.log("RATIO: ", Math.trunc(100 * data.length / content.length) + "%"); + if (rec.join("\n") !== words.join("\n")) { + throw new Error("no match!"); + } +} +//# sourceMappingURL=encode-latin.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/generation/encode-latin.js.map b/lib.esm/wordlists/generation/encode-latin.js.map new file mode 100644 index 000000000..9ed5652c1 --- /dev/null +++ b/lib.esm/wordlists/generation/encode-latin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-latin.js","sourceRoot":"","sources":["../../../src.ts/wordlists/generation/encode-latin.ts"],"names":[],"mappings":"AACA,kBAAkB;AAClB,EAAE;AACF,6DAA6D;AAC7D,2DAA2D;AAC3D,wDAAwD;AACx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IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;KAAE;CAC7E;KAAM;IACH,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC5B,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC;IAChF,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;KAAE;CAC7E"} \ No newline at end of file diff --git a/lib.esm/wordlists/index.js b/lib.esm/wordlists/index.js new file mode 100644 index 000000000..3f066c227 --- /dev/null +++ b/lib.esm/wordlists/index.js @@ -0,0 +1,6 @@ +export { Wordlist } from "./wordlist.js"; +export { langEn, LangEn } from "./lang-en.js"; +export { wordlists } from "./wordlists.js"; +export { WordlistOwl } from "./wordlist-owl.js"; +export { WordlistOwlA } from "./wordlist-owla.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/index.js.map b/lib.esm/wordlists/index.js.map new file mode 100644 index 000000000..591f7e3c0 --- /dev/null +++ b/lib.esm/wordlists/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src.ts/wordlists/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/lang-cz.js b/lib.esm/wordlists/lang-cz.js new file mode 100644 index 000000000..182cd1196 --- /dev/null +++ b/lib.esm/wordlists/lang-cz.js @@ -0,0 +1,8 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +const words = "0itatkastcenaovo$taouleraeki&chor*teci%enbalodaeladet'!Chn=0Di#%E%^1Resa2Rese3CeT'#0EjKohol0Pu)%0A&sDul#Ekdo)Ke)Ti#Ul|3}aOgan%0FaltI$@tPi,%TmaTronom0LasL{i#Ol0Tobus4Yl:B#}R'?TaUb_U/!U^U+Ur!Xer2A^v#Ambo,An#AtrEp)Ike)KoLohOnzOskevUn{#Usin#Z^Zy2Bl.Bn|})D _D#D'aF{Jar(Kv?LdokLvaN^NkrRzaTikVolZola3D+tL.T'#0Ukot:PartRev&3DrDu+J/JnLaLerLkemLn?N.Nn(N'#NtrumNzZ(2O&2KolivUv!4It_N(0Dn(Ke)KrPot0Ak~AlIkRkot2Kli$a:L-oRe[T_Tum1E,1B!a}'#Cib_Fic Fla%KlKr{Mokr!PreseRbyS#T-tiv3Kob,zKt|O^P]mSkSp+jV`]Vo/2AhaOuhoUhopis1Es0BroByt-C@t}ut DnesH+dHo^H,JemJn?Kl`KolaKtAzeDolObn(OgerieOzdSn(T Z(2B@}'noD-HaH'#S SnoT(0Oj?Or>2Nam :9O]gOnomie0EktronIpsa0AilIseO%P!ie2Izo^O/aOpejOs2EjEn%K<)Kymo0Ike)0FR&S]Zky3StOhOup(T!Ub.U/o)0AtO)Yz0IsOjivoOut0Bl.Boj}DinyDl!Dno)D|Jn(KejLin#L#LubMo+N [No,%RalR^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HylaKroL-ulaM@t#Nar/aNoklN$rumNt|NzunSazSkytStTiva%T<#Ty#U/aUdr(Zai#Z-Zol2AmKevTvolaZ{Zut(0T _1DrcF]nL!MieN?S{Ta%ZeumZi#nt3Sliv>0Da:B*r!}yt!Da%Dbyt-DhozDobroDpisHlasHn!Hodi+H,d Iv aJedn*Ji$oJm=K]n Kon>Krm LevoMaz!Mluv Nom{rOkoOpakO$roP`!PevnoPln P~Pos+dPr(oRod RubyRy/]S` S-!S+poSt!TolikV@-Vr/VzdR&Ru[RysSahSluhaS)r!UvVazVin VodVyk+Yv!_Z<0AsElEn Hl` Ho)H,&It~0BojByt}odCiz Ebr!Esl!Evzd!EzvaH`%Hod J{JinudKazK*p LivLu#Ml#Oln(P`PisPl=PLivoLu[Mf+tMls-N@#Ni#N&N|N$voNtof+Pri#Rke)RodieR)Ru#Ry[Se#Siv aSt_#T@tTro&V*kZnehtZ*r-3C#DagogJs-K]LotonNal)Ndr-NzeRiskopRoStr(Tar^T?Tro+jVn.Xeso3Ani$aHaJav?K+KnikL.Ln(Lul#Nze)Pe)S!_Sto+Tev&Vn?V'ar2A%n)Ak!Am@Ane)A$i#At Avid]AzE/Em@oEn)EsEtivoEv_Iv!N NoO/aOd.Om[OutUkYn2Bav Byt}odC Ctiv>D!D%n Deps!Dh+dDiv Dkl`Dman DnikDo[Dpo,D,zD$!aDvodDzimEzieHan#Hnut#H'S*d SpoluS)vaSud-SypTahT#nT+skTom-T,vaTupaTvo,U#zUtoUzdroVahaVidlaVlakVozVr/V$!VykVzde/Zd,vZem-Zn!-ZAp<-AseAv^IncipKnoObud O%ntoOdejOfeseOh,Oj-tO]m Omi+Onik!Op`OrokOs[OtonOut-OvazS#v#St@Udk(UtV-VohOvodTruh0Actvo0Ber)}DlKav>Kl.Kr+LtMpaNcP@SaSin#St.T|Ty#3Rami^SkT_::C-}otDia%Dn?DonFtGbyKe)K'.M@oMp*/NdeRa/R aS'&StrTo+$Zan%Zid]3Ag|Ak%CeptDaktM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ba}o+kH!StvaTu+0Ad T*p Tup0Ip4Bav Br!}|D!D,Fot H+d!H~Hod H,d Hub Jasn J{Jm=K]p Kon!L-!Maz!Mez Miz{Mys+tNe/!Nik!Nut P`!Pl! P,v Pu$ Raz R'n!Rv!Sl' SokoS)v Su~Syp!Tas Tes!Tr! Vi~Vol!Vrh_Zdob Zn!0AduBud }op DJ{Ji$ K+p!K*p Lep Mez Mot!Mys+tNe/!Nik!Pl! Poj Ps!Raz S)v Su~Taj Temn Tk~Ujm=Val Ve+tVin Vol!Vrt!Zvon 0Av RusuUd|Yt-1A+#ArmaAtn(IvoOb RojVihYm`]0L@.ManM.Pt!Z`uZdola2At Lt~Lubo#Ot' Ru[0MaMn?0Emn 0Lam!Oum!R!#Umav#0AtoEh#O[OmO$Ozvyk0Ap|ArAt-IjeIz{Ocn Odr!Rzl.Ut|0AkAl(Am@!Ovu0B,z Tav Ub-Ufa+0Lod Omal RavaR( Rud#Rvu1A^An C`]N (NoOv&Y/l Zav(1I/aR! 0B'.Br0Ed~EnkuEs_aOnR!Uk'odYk"; +const checksum = "0x25f44555f4af25b51a711136e1c7d6e50ce9f8917d39d6b1f076b2bb4d2fac1a"; +export class LangCz extends WordlistOwl { + constructor() { super("cz", words, checksum); } +} +export const langCz = new LangCz(); +//# sourceMappingURL=lang-cz.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/lang-cz.js.map b/lib.esm/wordlists/lang-cz.js.map new file mode 100644 index 000000000..7401b7e42 --- /dev/null +++ b/lib.esm/wordlists/lang-cz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-cz.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-cz.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,KAAK,GAAG,q9NAAq9N,CAAC;AACp+N,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AAEtF,MAAM,OAAO,MAAO,SAAQ,WAAW;IACnC,gBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClD;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/lang-en.js b/lib.esm/wordlists/lang-en.js new file mode 100644 index 000000000..6b0d588a5 --- /dev/null +++ b/lib.esm/wordlists/lang-en.js @@ -0,0 +1,8 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIp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!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; +const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; +export class LangEn extends WordlistOwl { + constructor() { super("en", words, checksum); } +} +export const langEn = new LangEn(); +//# sourceMappingURL=lang-en.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/lang-en.js.map b/lib.esm/wordlists/lang-en.js.map new file mode 100644 index 000000000..f42a907f9 --- /dev/null +++ b/lib.esm/wordlists/lang-en.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-en.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-en.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,KAAK,GAAG,u3LAAu3L,CAAC;AACt4L,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AAEtF,MAAM,OAAO,MAAO,SAAQ,WAAW;IACnC,gBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClD;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/lang-es.js b/lib.esm/wordlists/lang-es.js new file mode 100644 index 000000000..85fb826d0 --- /dev/null +++ b/lib.esm/wordlists/lang-es.js @@ -0,0 +1,9 @@ +import { WordlistOwlA } from "./wordlist-owla.js"; +const words = "0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%Ul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t_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! b) { + return 1; + } + return 0; + } + // Load all the words + for (let length = 3; length <= 9; length++) { + const d = data[length - 3]; + for (let offset = 0; offset < d.length; offset += length) { + const word = []; + for (let i = 0; i < length; i++) { + const k = mapping.indexOf(d[offset + i]); + word.push(227); + word.push((k & 0x40) ? 130 : 129); + word.push((k & 0x3f) + 128); + } + wordlist.push(toString(word)); + } + } + wordlist.sort(sortJapanese); + // For some reason kyoku and kiyoku are flipped in node (!!). + // The order SHOULD be: + // - kyoku + // - kiyoku + // This should ignore "if", but that doesn't work here?? + /* c8 ignore start */ + if (hex(wordlist[442]) === KiYoKu && hex(wordlist[443]) === KyoKu) { + const tmp = wordlist[442]; + wordlist[442] = wordlist[443]; + wordlist[443] = tmp; + } + /* c8 ignore stop */ + // Verify the computed list matches the official list + /* istanbul ignore if */ + const checksum = id(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== "0xcb36b09e6baa935787fd762ce65e80b0c6a8dabdfbc3a7f86ac0e2c4fd111600") { + throw new Error("BIP39 Wordlist for ja (Japanese) FAILED"); + } + /* c8 ignore stop */ + _wordlist = wordlist; + return wordlist; +} +class LangJa extends Wordlist { + constructor() { super("ja"); } + getWord(index) { + const words = loadWords(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords().indexOf(word); + } + split(mnemonic) { + //logger.assertNormalize(); + return mnemonic.split(/(?:\u3000| )+/g); + } + join(words) { + return words.join("\u3000"); + } +} +export const langJa = new LangJa(); +//# sourceMappingURL=lang-ja.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/lang-ja.js.map b/lib.esm/wordlists/lang-ja.js.map new file mode 100644 index 000000000..cac916af1 --- /dev/null +++ b/lib.esm/wordlists/lang-ja.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-ja.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-ja.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,eAAe,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGzC,MAAM,IAAI,GAAG;IAET,eAAe;IACf,orEAAorE;IAEprE,eAAe;IACf,ssGAAssG;IAEtsG,eAAe;IACf,4uDAA4uD;IAE5uD,eAAe;IACf,olBAAolB;IAEplB,eAAe;IACf,4JAA4J;IAE5J,eAAe;IACf,0GAA0G;IAE1G,gBAAgB;IAChB,WAAW;CACd,CAAC;AAEF,sDAAsD;AACtD,MAAM,OAAO,GAAG,6FAA6F,CAAA;AAE7G,IAAI,SAAS,GAAyB,IAAI,CAAC;AAE3C,SAAS,GAAG,CAAC,IAAY;IACrB,OAAO,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,MAAM,GAAG,sBAAsB,CAAC;AACtC,MAAM,KAAK,GAAG,sBAAsB,CAAA;AAEpC,SAAS,QAAQ,CAAC,IAAmB;IACjC,OAAO,Y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I,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;YACpC,MAAM,CAAC,kBAAkB,CAAC,uBAAwB,KAAM,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC/E;QACD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAED,YAAY,CAAC,IAAY;QACrB,OAAO,SAAS,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,QAAgB;QAClB,2BAA2B;QAC3B,OAAO,QAAQ,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC;IAED,IAAI,CAAC,KAAoB;QACrB,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;CACJ;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/lang-ko.js b/lib.esm/wordlists/lang-ko.js new file mode 100644 index 000000000..e43d9b64f --- /dev/null +++ b/lib.esm/wordlists/lang-ko.js @@ -0,0 +1,68 @@ +import { id } from "../hash/id.js"; +import { logger, toUtf8String } from "../utils/index.js"; +import { Wordlist } from "./wordlist.js"; +const data = [ + "OYAa", + "ATAZoATBl3ATCTrATCl8ATDloATGg3ATHT8ATJT8ATJl3ATLlvATLn4ATMT8ATMX8ATMboATMgoAToLbAToMTATrHgATvHnAT3AnAT3JbAT3MTAT8DbAT8JTAT8LmAT8MYAT8MbAT#LnAUHT8AUHZvAUJXrAUJX8AULnrAXJnvAXLUoAXLgvAXMn6AXRg3AXrMbAX3JTAX3QbAYLn3AZLgvAZrSUAZvAcAZ8AaAZ8AbAZ8AnAZ8HnAZ8LgAZ8MYAZ8MgAZ8OnAaAboAaDTrAaFTrAaJTrAaJboAaLVoAaMXvAaOl8AaSeoAbAUoAbAg8AbAl4AbGnrAbMT8AbMXrAbMn4AbQb8AbSV8Ab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rHgLnrAcJYMb8DULc8LTvFgGnCk3Mg8JbAnLX4QYvFYHnMXrRUoJnGnvFnRlvFTJlQnoSTrBXHXrLYSUJgLfoMT8Se8DTrHbDb", + "AbDl8SToJU8An3RbAb8ST8DUSTrGnrAgoLbFU6Db8LTrMg8AaHT8Jb8ObDl8SToJU8Pb3RlvFYoJl" +]; +const codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"; +function getHangul(code) { + if (code >= 40) { + code = code + 168 - 40; + } + else if (code >= 19) { + code = code + 97 - 19; + } + return toUtf8String(new Uint8Array([225, (code >> 6) + 132, (code & 0x3f) + 128])); +} +let _wordlist = null; +function loadWords() { + if (_wordlist != null) { + return _wordlist; + } + const wordlist = []; + data.forEach((data, length) => { + length += 4; + for (let i = 0; i < data.length; i += length) { + let word = ""; + for (let j = 0; j < length; j++) { + word += getHangul(codes.indexOf(data[i + j])); + } + wordlist.push(word); + } + }); + wordlist.sort(); + // Verify the computed list matches the official list + /* istanbul ignore if */ + const checksum = id(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== "0xf9eddeace9c5d3da9c93cf7d3cd38f6a13ed3affb933259ae865714e8a3ae71a") { + throw new Error("BIP39 Wordlist for ko (Korean) FAILED"); + } + /* c8 ignore stop */ + _wordlist = wordlist; + return wordlist; +} +class LangKo extends Wordlist { + constructor() { + super("ko"); + } + getWord(index) { + const words = loadWords(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords().indexOf(word); + } +} +export const langKo = new LangKo(); +//# sourceMappingURL=lang-ko.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/lang-ko.js.map b/lib.esm/wordlists/lang-ko.js.map new file mode 100644 index 000000000..0340f9181 --- /dev/null +++ b/lib.esm/wordlists/lang-ko.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-ko.js","sourceRoot":"","sources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2c2c414 --- /dev/null +++ b/lib.esm/wordlists/lang-pt.js @@ -0,0 +1,8 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +const words = "0arad!ototealirertainrasoent hoandoaR#riareha!aroele'oronul0Aca%AixoAl A%rDuz'El]Er$IsmoO$ Rum S-&T(i&TigoVo[=0F&.Il#P' S?S* So&/Sun$Tr&0Ac#Adu+Al/A[f E End(Er_EuIng'Ir?IvoOl{oRac Revi=RizU&Um0Di$rM-.R>o+TismoT|@Tu 0Ali An%Ar@Ent&Es,I?Is Ul,1Ila1Ar E=Ei%Ulejo:B BosaC&]uCh `C@GagemI+c>~/Se#S)n%Ta)Te=rTidaTomTuc Unil]3B(IjoIr^IsebolLd!eLezaLgaLisc Ndi$Ng&aNz(RimbauRl*d>_Sou_XigaZ(_3CoCu=En&Foc&Furc G|naLhe%Mest[Mo$rOlog@OmboOsf(aPol Rr-$Scoi$Sne$SpoSsex$TolaZ _2Ind#OcoOque 2A$BagemC#CejoChec]Ico.L^LetimL]LoMb{oNdeNecoNi)Rb~h>d>e&R+c]V*oXe?2AncoAsaAvezaEuIgaIl/Inc OaOchu+Onze O$Uxo2C]DismoF LeRacoScaS$Z*a:Bimb Rn{oRpe%R['>)zRv&/SacoScaSeb[S%loS~oT a)Tiv UleUs?U%l V&oV(na3BolaDil]G}]Lebr L~ Nou+N,N%ioRc Rr#R%'oRvejaTimV^2Aco)Al{aAm#Ap^ArmeAticeAveEfeEg^E'oEqueIco%If[In`oOc&/Ov(UmboU.Uva0CatrizCl}eD!eD['aEn%Gcui$Rurg@T 2A[zaE_Ic OneUbe2A=Ag'Ba@B($rBr C^El/Ent_E,Gum`oIb'IfaIo%L L{aLh(Lid'Lme@L}oLunaM<=Mb* M-.MitivaMov(MplexoMumNc]N=rNec.Nfu,Ng` Nhec(Njug Nsum'Nt+$Nvi%Op( P{oPi?PoQue%lRagemRdi&Rne)R}h>p|&R[ioR%joRuj>voSs-oS%laT}e%U_UveVilZ*]2A%+AvoEcheE=rE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+xaTuagemUr*oXativoXis)3Atr&C(Ci=Cl#Dio,IaIm Lef}eLh#Mp(oN-%N,rN.Rm&RnoRr-oSeSou+St#ToXtu+Xugo3A+G`aJoloMbr MidezNgi=N%'oRagemT~ 5Al]C]L( LiceM^Mil/N`Ntu+Pe%R>ci=RneioRqueRr!>$S.UcaUp{aX*a2Ab&/Acej Adu$rAfeg Aje$AmaAnc ApoAs{oAt?Av E*oEm(Epid EvoIagemIboIcicloId-%Ilog@Ind!eIploItur Iunf&Oc Ombe)OvaUnfoUque2B~ CquesaT` T|i&:7V 3Bigo0HaId!eIf|me3Olog@SoTigaUbu0A=InaUfru':C*aDi G o,I=,LaL-%Lid!eLo[sN)gemQu{oRe)Rr(Sc~ Sil]S,u+Z Zio3A=D Ge.Ic~ L{oLhiceLu=Nce=rNdav&N( Nt[Rb&Rd!eRe?Rg}h>m`/RnizRs R%n%SpaSti=T|i&3Adu$AgemAj Atu+Br?D{aDr @ElaGaG-%Gi G| L ejoNcoNhe)NilOle)R!>tudeSi.S$Tr&V{oZ*/5A=rArG&L<%LeibolL)gemLumo,Nt!e5L$Vuz`a::D[zRope3QueRe.Rife3Ng ::Ng#Rp 3BuL?9Mb Olog@5Mbi="; +const checksum = "0x2219000926df7b50d8aa0a3d495826b988287df4657fbd100e6fe596c8f737ac"; +export class LangPt extends WordlistOwl { + constructor() { super("pt", words, checksum); } +} +export const langPt = new LangPt(); +//# sourceMappingURL=lang-pt.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/lang-pt.js.map b/lib.esm/wordlists/lang-pt.js.map new file mode 100644 index 000000000..390d29cea --- /dev/null +++ b/lib.esm/wordlists/lang-pt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-pt.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-pt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,KAAK,GAAG,s0OAAs0O,CAAC;AACr1O,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AAEtF,MAAM,OAAO,MAAO,SAAQ,WAAW;IACnC,gBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClD;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/lang-zh.js b/lib.esm/wordlists/lang-zh.js new file mode 100644 index 000000000..11e79d12b --- /dev/null +++ b/lib.esm/wordlists/lang-zh.js @@ -0,0 +1,66 @@ +import { id } from "../hash/index.js"; +import { toUtf8String, logger } from "../utils/index.js"; +import { Wordlist } from "./wordlist.js"; +const data = "}aE#4A=Yv&co#4N#6G=cJ&SM#66|/Z#4t&kn~46#4K~4q%b9=IR#7l,mB#7W_X2*dl}Uo~7s}Uf&Iw#9c&cw~6O&H6&wx&IG%v5=IQ~8a&Pv#47$PR&50%Ko&QM&3l#5f,D9#4L|/H&tQ;v0~6n]nN> 2), + 128 + codes.indexOf(data[i * 3 + 1]), + 128 + codes.indexOf(data[i * 3 + 2]), + ]; + if (locale === "zh_tw") { + const common = s % 4; + for (let i = common; i < 3; i++) { + bytes[i] = codes.indexOf(deltaData[deltaOffset++]) + ((i == 0) ? 228 : 128); + } + } + wordlist.push(toUtf8String(new Uint8Array(bytes))); + } + // Verify the computed list matches the official list + const checksum = id(wordlist.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== Checks[locale]) { + throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`); + } + /* c8 ignore stop */ + _wordlist[locale] = wordlist; + return wordlist; +} +class LangZh extends Wordlist { + constructor(country) { super("zh_" + country); } + getWord(index) { + const words = loadWords(this.locale); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return loadWords(this.locale).indexOf(word); + } + split(mnemonic) { + mnemonic = mnemonic.replace(/(?:\u3000| )+/g, ""); + return mnemonic.split(""); + } +} +export const langZhCn = new LangZh("cn"); +export const langZhTw = new LangZh("tw"); +//# sourceMappingURL=lang-zh.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/lang-zh.js.map b/lib.esm/wordlists/lang-zh.js.map new file mode 100644 index 000000000..6d3757bed --- /dev/null +++ b/lib.esm/wordlists/lang-zh.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-zh.js","sourceRoot":"","sources":["../../src.ts/wordlists/lang-zh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGzC,MAAM,IAAI,GAAG,kgMAAkgM,CAAC;AAChhM,MAAM,SAAS,GAAG,6lDAA6lD,CAAC;AAGhnD,MAAM,SAAS,GAAyC;IACpD,KAAK,EAAE,IAAI;IACX,KAAK,EAAE,IAAI;CACd,CAAA;AAED,MAAM,MAAM,GAA2B;IACnC,KAAK,EAAE,oEAAoE;IAC3E,KAAK,EAAE,oEAAoE;CAC9E,CAAA;AAED,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,KAAK,GAAG,4BAA4B,CAAA;AAE1C,SAAS,SAAS,CAAC,MAAc;IAC7B,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE;QAAE,OAAO,SAAS,CAAC,MAAM,CAAkB,CAAC;KAAE;IAE7E,MAAM,QAAQ,GAAG,EAAE,CAAC;IAEpB,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;QAC3B,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACrC,MAAM,KAAK,GAA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,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;YACpC,MAAM,CAAC,kBAAkB,CAAC,uBAAwB,KAAM,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC/E;QACD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAED,YAAY,CAAC,IAAY;QACrB,OAAO,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;IAED,KAAK,CAAC,QAAgB;QAClB,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;QAClD,OAAO,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC9B,CAAC;CACJ;AAED,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/wordlist-owl.js b/lib.esm/wordlists/wordlist-owl.js new file mode 100644 index 000000000..7155c3bb8 --- /dev/null +++ b/lib.esm/wordlists/wordlist-owl.js @@ -0,0 +1,46 @@ +// Use the encode-latin.js script to create the necessary +// data files to be consumed by this class +import { id } from "../hash/id.js"; +import { logger } from "../utils/logger.js"; +import { decodeOwl } from "./decode-owl.js"; +import { Wordlist } from "./wordlist.js"; +export class WordlistOwl extends Wordlist { + #data; + #checksum; + constructor(locale, data, checksum) { + super(locale); + this.#data = data; + this.#checksum = checksum; + this.#words = null; + } + get _data() { return this.#data; } + _decodeWords() { + return decodeOwl(this.#data); + } + #words; + #loadWords() { + if (this.#words == null) { + const words = this._decodeWords(); + // Verify the computed list matches the official list + const checksum = id(words.join("\n") + "\n"); + /* c8 ignore start */ + if (checksum !== this.#checksum) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); + } + /* c8 ignore stop */ + this.#words = words; + } + return this.#words; + } + getWord(index) { + const words = this.#loadWords(); + if (index < 0 || index >= words.length) { + logger.throwArgumentError(`invalid word index: ${index}`, "index", index); + } + return words[index]; + } + getWordIndex(word) { + return this.#loadWords().indexOf(word); + } +} +//# sourceMappingURL=wordlist-owl.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/wordlist-owl.js.map b/lib.esm/wordlists/wordlist-owl.js.map new file mode 100644 index 000000000..06782549a --- /dev/null +++ b/lib.esm/wordlists/wordlist-owl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist-owl.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist-owl.ts"],"names":[],"mappings":"AACA,yDAAyD;AACzD,0CAA0C;AAE1C,OAAO,EAAE,EAAE,EAAE,MAAM,eAAe,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,MAAM,OAAO,WAAY,SAAQ,QAAQ;IACrC,KAAK,CAAS;IACd,SAAS,CAAS;IAElB,YAAY,MAAc,EAAE,IAAY,EAAE,QAAgB;QACtD,KAAK,CAAC,MAAM,CAAC,CAAC;QACd,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACvB,CAAC;IAED,IAAI,KAAK,KAAa,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAE1C,YAAY;QACR,OAAO,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,MAAM,CAAuB;IAC7B,UAAU;QACN,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,EAAE;YACrB,MAAM,KAAK,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YAElC,qDAAqD;YACrD,MAAM,QAAQ,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;YAC7C,qBAAqB;YACrB,IAAI,QAAQ,KAAK,IAAI,CAAC,SAAS,EAAE;gBAC7B,MAAM,IAAI,KAAK,CAAC,sBAAuB,IAAI,CAAC,MAAO,SAAS,CAAC,CAAC;aACjE;YACD,oBAAoB;YAEpB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;SACvB;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAED,OAAO,CAAC,KAAa;QACjB,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QAChC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE;YACpC,MAAM,CAAC,kBAAkB,CAAC,uBAAwB,KAAM,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;SAC/E;QACD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IAED,YAAY,CAAC,IAAY;QACrB,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/wordlists/wordlist-owla.js b/lib.esm/wordlists/wordlist-owla.js new file mode 100644 index 000000000..a0f1527dd --- /dev/null +++ b/lib.esm/wordlists/wordlist-owla.js @@ -0,0 +1,14 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +import { decodeOwlA } from "./decode-owla.js"; +export class WordlistOwlA extends WordlistOwl { + #accent; + constructor(locale, data, accent, checksum) { + super(locale, data, checksum); + this.#accent = accent; + } + get _accent() { return this.#accent; } + _decodeWords() { + return decodeOwlA(this._data, this._accent); + } +} +//# sourceMappingURL=wordlist-owla.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/wordlist-owla.js.map b/lib.esm/wordlists/wordlist-owla.js.map new file mode 100644 index 000000000..3d41f315c --- /dev/null +++ b/lib.esm/wordlists/wordlist-owla.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist-owla.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist-owla.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,MAAM,OAAO,YAAa,SAAQ,WAAW;IACzC,OAAO,CAAS;IAEhB,YAAY,MAAc,EAAE,IAAY,EAAE,MAAc,EAAE,QAAgB;QACtE,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,IAAI,OAAO,KAAa,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE9C,YAAY;QACR,OAAO,UAAU,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/wordlists/wordlist.js b/lib.esm/wordlists/wordlist.js new file mode 100644 index 000000000..09ebee751 --- /dev/null +++ b/lib.esm/wordlists/wordlist.js @@ -0,0 +1,16 @@ +import { defineProperties } from "../utils/index.js"; +export class Wordlist { + locale; + constructor(locale) { + defineProperties(this, { locale }); + } + // Subclasses may override this + split(mnemonic) { + return mnemonic.toLowerCase().split(/ +/g); + } + // Subclasses may override this + join(words) { + return words.join(" "); + } +} +//# sourceMappingURL=wordlist.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/wordlist.js.map b/lib.esm/wordlists/wordlist.js.map new file mode 100644 index 000000000..61503abfa --- /dev/null +++ b/lib.esm/wordlists/wordlist.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,MAAM,OAAgB,QAAQ;IAC1B,MAAM,CAAU;IAEhB,YAAY,MAAc;QACtB,gBAAgB,CAAW,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,+BAA+B;IAC/B,KAAK,CAAC,QAAgB;QAClB,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;IAC9C,CAAC;IAED,+BAA+B;IAC/B,IAAI,CAAC,KAAoB;QACrB,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;CAIJ"} \ No newline at end of file diff --git a/lib.esm/wordlists/wordlists-browser.js b/lib.esm/wordlists/wordlists-browser.js new file mode 100644 index 000000000..0f824542f --- /dev/null +++ b/lib.esm/wordlists/wordlists-browser.js @@ -0,0 +1,6 @@ +// wordlists/wordlists-browser.js +import { langEn as en } from "./lang-en.js"; +export const wordlists = Object.freeze({ + en +}); +//# sourceMappingURL=wordlists-browser.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/wordlists-browser.js.map b/lib.esm/wordlists/wordlists-browser.js.map new file mode 100644 index 000000000..ecc147c42 --- /dev/null +++ b/lib.esm/wordlists/wordlists-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists-browser.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists-browser.ts"],"names":[],"mappings":"AACA,iCAAiC;AAEjC,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAI5C,MAAM,CAAC,MAAM,SAAS,GAA6B,MAAM,CAAC,MAAM,CAAC;IAC7D,EAAE;CACL,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/wordlists-extra.js b/lib.esm/wordlists/wordlists-extra.js new file mode 100644 index 000000000..bec93341b --- /dev/null +++ b/lib.esm/wordlists/wordlists-extra.js @@ -0,0 +1,12 @@ +import { langCz as cz } from "./lang-cz.js"; +import { langEs as es } from "./lang-es.js"; +import { langFr as fr } from "./lang-fr.js"; +import { langJa as ja } from "./lang-ja.js"; +import { langKo as ko } from "./lang-ko.js"; +import { langIt as it } from "./lang-it.js"; +import { langPt as pt } from "./lang-pt.js"; +import { langZhCn as zh_cn, langZhTw as zh_tw } from "./lang-zh.js"; +export const wordlists = Object.freeze({ + cz, es, fr, ja, ko, it, pt, zh_cn, zh_tw +}); +//# sourceMappingURL=wordlists-extra.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/wordlists-extra.js.map b/lib.esm/wordlists/wordlists-extra.js.map new file mode 100644 index 000000000..39e894e5a --- /dev/null +++ b/lib.esm/wordlists/wordlists-extra.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists-extra.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists-extra.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,QAAQ,IAAI,KAAK,EAAE,QAAQ,IAAI,KAAK,EAAE,MAAM,cAAc,CAAC;AAIpE,MAAM,CAAC,MAAM,SAAS,GAA6B,MAAM,CAAC,MAAM,CAAC;IAC7D,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK;CAC3C,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/wordlists/wordlists.js b/lib.esm/wordlists/wordlists.js new file mode 100644 index 000000000..0da5c9f88 --- /dev/null +++ b/lib.esm/wordlists/wordlists.js @@ -0,0 +1,13 @@ +import { langCz as cz } from "./lang-cz.js"; +import { langEn as en } from "./lang-en.js"; +import { langEs as es } from "./lang-es.js"; +import { langFr as fr } from "./lang-fr.js"; +import { langJa as ja } from "./lang-ja.js"; +import { langKo as ko } from "./lang-ko.js"; +import { langIt as it } from "./lang-it.js"; +import { langPt as pt } from "./lang-pt.js"; +import { langZhCn as zh_cn, langZhTw as zh_tw } from "./lang-zh.js"; +export const wordlists = Object.freeze({ + cz, en, es, fr, ja, ko, it, pt, zh_cn, zh_tw +}); +//# sourceMappingURL=wordlists.js.map \ No newline at end of file diff --git a/lib.esm/wordlists/wordlists.js.map b/lib.esm/wordlists/wordlists.js.map new file mode 100644 index 000000000..3f2b65c99 --- /dev/null +++ b/lib.esm/wordlists/wordlists.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists.js","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,MAAM,IAAI,EAAE,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,QAAQ,IAAI,KAAK,EAAE,QAAQ,IAAI,KAAK,EAAE,MAAM,cAAc,CAAC;AAIpE,MAAM,CAAC,MAAM,SAAS,GAA6B,MAAM,CAAC,MAAM,CAAC;IAC7D,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK;CAC/C,CAAC,CAAC"} \ No newline at end of file diff --git a/tsconfig.types.json b/tsconfig.types.json index e36ecd691..b4efdc956 100644 --- a/tsconfig.types.json +++ b/tsconfig.types.json @@ -1,6 +1,7 @@ { "exclude": [ - "src.ts/_admin/**" + "src.ts/_admin/**", + "src.ts/_tests/**" ], "extends": "./tsconfig.base.json", "compilerOptions": { diff --git a/types/_version.d.ts b/types/_version.d.ts new file mode 100644 index 000000000..0aa837604 --- /dev/null +++ b/types/_version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "6.0.0-beta-exports.0"; +//# sourceMappingURL=_version.d.ts.map \ No newline at end of file diff --git a/types/_version.d.ts.map b/types/_version.d.ts.map new file mode 100644 index 000000000..da3a8d95c --- /dev/null +++ b/types/_version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_version.d.ts","sourceRoot":"","sources":["../src.ts/_version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,yBAAyB,CAAC"} \ No newline at end of file diff --git a/types/abi/abi-coder.d.ts b/types/abi/abi-coder.d.ts new file mode 100644 index 000000000..902f3edbd --- /dev/null +++ b/types/abi/abi-coder.d.ts @@ -0,0 +1,11 @@ +import { Result } from "./coders/abstract-coder.js"; +import { ParamType } from "./fragments.js"; +import type { BytesLike } from "../utils/index.js"; +export declare class AbiCoder { + #private; + getDefaultValue(types: ReadonlyArray): Result; + encode(types: ReadonlyArray, values: ReadonlyArray): string; + decode(types: ReadonlyArray, data: BytesLike, loose?: boolean): Result; +} +export declare const defaultAbiCoder: AbiCoder; +//# sourceMappingURL=abi-coder.d.ts.map \ No newline at end of file diff --git a/types/abi/abi-coder.d.ts.map b/types/abi/abi-coder.d.ts.map new file mode 100644 index 000000000..2cafde052 --- /dev/null +++ b/types/abi/abi-coder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abi-coder.d.ts","sourceRoot":"","sources":["../../src.ts/abi/abi-coder.ts"],"names":[],"mappings":"AAIA,OAAO,EAAiB,MAAM,EAAU,MAAM,4BAA4B,CAAC;AAU3E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAMnD,qBAAa,QAAQ;;IA+CjB,eAAe,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM;IAMjE,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,GAAG,MAAM;IAWpF,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM;CAK7F;AAGD,eAAO,MAAM,eAAe,EAAE,QAAyB,CAAC"} \ No newline at end of file diff --git a/types/abi/bytes32.d.ts b/types/abi/bytes32.d.ts new file mode 100644 index 000000000..3040da1e0 --- /dev/null +++ b/types/abi/bytes32.d.ts @@ -0,0 +1,4 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function formatBytes32String(text: string): string; +export declare function parseBytes32String(_bytes: BytesLike): string; +//# sourceMappingURL=bytes32.d.ts.map \ No newline at end of file diff --git a/types/abi/bytes32.d.ts.map b/types/abi/bytes32.d.ts.map new file mode 100644 index 000000000..907330cfc --- /dev/null +++ b/types/abi/bytes32.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes32.d.ts","sourceRoot":"","sources":["../../src.ts/abi/bytes32.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAGnD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAUxD;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAa5D"} \ No newline at end of file diff --git a/types/abi/coders/abstract-coder.d.ts b/types/abi/coders/abstract-coder.d.ts new file mode 100644 index 000000000..b004e4665 --- /dev/null +++ b/types/abi/coders/abstract-coder.d.ts @@ -0,0 +1,49 @@ +import type { BigNumberish, BytesLike } from "../../utils/index.js"; +export declare const WordSize = 32; +export declare class Result extends Array { + #private; + [K: string | number]: any; + constructor(guard: any, items: Array, keys?: Array); + slice(start?: number | undefined, end?: number | undefined): Array; + getValue(name: string): any; + static fromItems(items: Array, keys?: Array): Result; +} +export declare function checkResultErrors(result: Result): Array<{ + path: Array; + error: Error; +}>; +export declare abstract class Coder { + readonly name: string; + readonly type: string; + readonly localName: string; + readonly dynamic: boolean; + constructor(name: string, type: string, localName: string, dynamic: boolean); + _throwError(message: string, value: any): never; + abstract encode(writer: Writer, value: any): number; + abstract decode(reader: Reader): any; + abstract defaultValue(): any; +} +export declare class Writer { + #private; + constructor(); + get data(): string; + get length(): number; + appendWriter(writer: Writer): number; + writeBytes(value: BytesLike): number; + writeValue(value: BigNumberish): number; + writeUpdatableValue(): (value: BigNumberish) => void; +} +export declare class Reader { + #private; + readonly allowLoose: boolean; + constructor(data: BytesLike, allowLoose?: boolean); + get data(): string; + get dataLength(): number; + get consumed(): number; + get bytes(): Uint8Array; + subReader(offset: number): Reader; + readBytes(length: number, loose?: boolean): Uint8Array; + readValue(): bigint; + readIndex(): number; +} +//# sourceMappingURL=abstract-coder.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/abstract-coder.d.ts.map b/types/abi/coders/abstract-coder.d.ts.map new file mode 100644 index 000000000..647fc8ca2 --- /dev/null +++ b/types/abi/coders/abstract-coder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-coder.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/abstract-coder.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEpE,eAAO,MAAM,QAAQ,KAAK,CAAC;AAS3B,qBAAa,MAAO,SAAQ,KAAK,CAAC,GAAG,CAAC;;IAGlC,CAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAI,GAAG,CAAA;gBAEf,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,EAAE,KAAK,CAAC,IAAI,GAAG,MAAM,CAAC;IAgEtE,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC;IAuBvE,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG;IAa3B,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,EAAE,KAAK,CAAC,IAAI,GAAG,MAAM,CAAC;CAGlE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,CAAC,CAqBvG;AAqBD,8BAAsB,KAAK;IAIvB,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;IAIvB,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;IAIvB,QAAQ,CAAC,SAAS,EAAG,MAAM,CAAC;IAK5B,QAAQ,CAAC,OAAO,EAAG,OAAO,CAAC;gBAEf,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO;IAM3E,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,KAAK;IAI/C,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,MAAM;IACnD,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;IAEpC,QAAQ,CAAC,YAAY,IAAI,GAAG;CAC/B;AAED,qBAAa,MAAM;;;IAUf,IAAI,IAAI,IAAI,MAAM,CAEjB;IACD,IAAI,MAAM,IAAI,MAAM,CAA6B;IAQjD,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAKpC,UAAU,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM;IAUpC,UAAU,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM;IAMvC,mBAAmB,IAAI,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI;CAQvD;AAED,qBAAa,MAAM;;IAKf,QAAQ,CAAC,UAAU,EAAG,OAAO,CAAC;gBAKlB,IAAI,EAAE,SAAS,EAAE,UAAU,CAAC,EAAE,OAAO;IAQjD,IAAI,IAAI,IAAI,MAAM,CAAgC;IAClD,IAAI,UAAU,IAAI,MAAM,CAA8B;IACtD,IAAI,QAAQ,IAAI,MAAM,CAAyB;IAC/C,IAAI,KAAK,IAAI,UAAU,CAAuC;IAmB9D,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAKjC,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,UAAU;IAQtD,SAAS,IAAI,MAAM;IAInB,SAAS,IAAI,MAAM;CAGtB"} \ No newline at end of file diff --git a/types/abi/coders/address.d.ts b/types/abi/coders/address.d.ts new file mode 100644 index 000000000..7174469bc --- /dev/null +++ b/types/abi/coders/address.d.ts @@ -0,0 +1,10 @@ +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class AddressCoder extends Coder { + constructor(localName: string); + defaultValue(): string; + encode(writer: Writer, _value: string | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=address.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/address.d.ts.map b/types/abi/coders/address.d.ts.map new file mode 100644 index 000000000..a4c45e577 --- /dev/null +++ b/types/abi/coders/address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/address.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG1D,qBAAa,YAAa,SAAQ,KAAK;gBAEvB,SAAS,EAAE,MAAM;IAI7B,YAAY,IAAI,MAAM;IAItB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,MAAM;IAUtD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/coders/anonymous.d.ts b/types/abi/coders/anonymous.d.ts new file mode 100644 index 000000000..2c648d96d --- /dev/null +++ b/types/abi/coders/anonymous.d.ts @@ -0,0 +1,10 @@ +import { Coder } from "./abstract-coder.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class AnonymousCoder extends Coder { + private coder; + constructor(coder: Coder); + defaultValue(): any; + encode(writer: Writer, value: any): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=anonymous.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/anonymous.d.ts.map b/types/abi/coders/anonymous.d.ts.map new file mode 100644 index 000000000..ac5870003 --- /dev/null +++ b/types/abi/coders/anonymous.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"anonymous.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/anonymous.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG1D,qBAAa,cAAe,SAAQ,KAAK;IACrC,OAAO,CAAC,KAAK,CAAQ;gBAET,KAAK,EAAE,KAAK;IAKxB,YAAY,IAAI,GAAG;IAInB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,MAAM;IAI1C,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/coders/array.d.ts b/types/abi/coders/array.d.ts new file mode 100644 index 000000000..7f054b6f3 --- /dev/null +++ b/types/abi/coders/array.d.ts @@ -0,0 +1,16 @@ +import { Typed } from "../typed.js"; +import { Coder, Result, Writer } from "./abstract-coder.js"; +import type { Reader } from "./abstract-coder.js"; +export declare function pack(writer: Writer, coders: ReadonlyArray, values: Array | { + [name: string]: any; +}): number; +export declare function unpack(reader: Reader, coders: ReadonlyArray): Result; +export declare class ArrayCoder extends Coder { + readonly coder: Coder; + readonly length: number; + constructor(coder: Coder, length: number, localName: string); + defaultValue(): Array; + encode(writer: Writer, _value: Array | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=array.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/array.d.ts.map b/types/abi/coders/array.d.ts.map new file mode 100644 index 000000000..63256dd76 --- /dev/null +++ b/types/abi/coders/array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/array.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAY,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGtE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,wBAAgB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG;IAAE,CAAE,IAAI,EAAE,MAAM,GAAI,GAAG,CAAA;CAAE,GAAG,MAAM,CAuEzH;AAED,wBAAgB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,CAAC,KAAK,CAAC,GAAG,MAAM,CAoD3E;AAGD,qBAAa,UAAW,SAAQ,KAAK;IACjC,QAAQ,CAAC,KAAK,EAAG,KAAK,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAG,MAAM,CAAC;gBAEb,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAO3D,YAAY,IAAI,KAAK,CAAC,GAAG,CAAC;IAW1B,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,GAAG,MAAM;IAsB1D,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAuB9B"} \ No newline at end of file diff --git a/types/abi/coders/boolean.d.ts b/types/abi/coders/boolean.d.ts new file mode 100644 index 000000000..cdd4e3eb6 --- /dev/null +++ b/types/abi/coders/boolean.d.ts @@ -0,0 +1,10 @@ +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class BooleanCoder extends Coder { + constructor(localName: string); + defaultValue(): boolean; + encode(writer: Writer, _value: boolean | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=boolean.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/boolean.d.ts.map b/types/abi/coders/boolean.d.ts.map new file mode 100644 index 000000000..b8bacce85 --- /dev/null +++ b/types/abi/coders/boolean.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/boolean.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG1D,qBAAa,YAAa,SAAQ,KAAK;gBAEvB,SAAS,EAAE,MAAM;IAI7B,YAAY,IAAI,OAAO;IAIvB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,KAAK,GAAG,MAAM;IAKvD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/coders/bytes.d.ts b/types/abi/coders/bytes.d.ts new file mode 100644 index 000000000..bf5fc1dcd --- /dev/null +++ b/types/abi/coders/bytes.d.ts @@ -0,0 +1,13 @@ +import { Coder } from "./abstract-coder.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class DynamicBytesCoder extends Coder { + constructor(type: string, localName: string); + defaultValue(): string; + encode(writer: Writer, value: any): number; + decode(reader: Reader): any; +} +export declare class BytesCoder extends DynamicBytesCoder { + constructor(localName: string); + decode(reader: Reader): any; +} +//# sourceMappingURL=bytes.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/bytes.d.ts.map b/types/abi/coders/bytes.d.ts.map new file mode 100644 index 000000000..1e03a5145 --- /dev/null +++ b/types/abi/coders/bytes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bytes.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/bytes.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG1D,qBAAa,iBAAkB,SAAQ,KAAK;gBAC5B,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAI3C,YAAY,IAAI,MAAM;IAItB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,MAAM;IAO1C,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B;AAED,qBAAa,UAAW,SAAQ,iBAAiB;gBACjC,SAAS,EAAE,MAAM;IAI7B,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/coders/fixed-bytes.d.ts b/types/abi/coders/fixed-bytes.d.ts new file mode 100644 index 000000000..9036a4631 --- /dev/null +++ b/types/abi/coders/fixed-bytes.d.ts @@ -0,0 +1,12 @@ +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +import type { BytesLike } from "../../utils/index.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class FixedBytesCoder extends Coder { + readonly size: number; + constructor(size: number, localName: string); + defaultValue(): string; + encode(writer: Writer, _value: BytesLike | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=fixed-bytes.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/fixed-bytes.d.ts.map b/types/abi/coders/fixed-bytes.d.ts.map new file mode 100644 index 000000000..5b54744cf --- /dev/null +++ b/types/abi/coders/fixed-bytes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fixed-bytes.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/fixed-bytes.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG1D,qBAAa,eAAgB,SAAQ,KAAK;IACtC,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;gBAEX,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAM3C,YAAY,IAAI,MAAM;IAItB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,GAAG,KAAK,GAAG,MAAM;IAMzD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/coders/null.d.ts b/types/abi/coders/null.d.ts new file mode 100644 index 000000000..067997374 --- /dev/null +++ b/types/abi/coders/null.d.ts @@ -0,0 +1,9 @@ +import { Coder } from "./abstract-coder.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class NullCoder extends Coder { + constructor(localName: string); + defaultValue(): null; + encode(writer: Writer, value: any): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=null.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/null.d.ts.map b/types/abi/coders/null.d.ts.map new file mode 100644 index 000000000..bc2a22963 --- /dev/null +++ b/types/abi/coders/null.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"null.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/null.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAI1D,qBAAa,SAAU,SAAQ,KAAK;gBAEpB,SAAS,EAAE,MAAM;IAI7B,YAAY,IAAI,IAAI;IAIpB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,MAAM;IAK1C,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAI9B"} \ No newline at end of file diff --git a/types/abi/coders/number.d.ts b/types/abi/coders/number.d.ts new file mode 100644 index 000000000..dea65fad3 --- /dev/null +++ b/types/abi/coders/number.d.ts @@ -0,0 +1,13 @@ +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +import type { BigNumberish } from "../../utils/index.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class NumberCoder extends Coder { + readonly size: number; + readonly signed: boolean; + constructor(size: number, signed: boolean, localName: string); + defaultValue(): number; + encode(writer: Writer, _value: BigNumberish | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=number.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/number.d.ts.map b/types/abi/coders/number.d.ts.map new file mode 100644 index 000000000..8b5e7cdbe --- /dev/null +++ b/types/abi/coders/number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/number.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAY,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAO1D,qBAAa,WAAY,SAAQ,KAAK;IAClC,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAG,OAAO,CAAC;gBAEd,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM;IAO5D,YAAY,IAAI,MAAM;IAItB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,GAAG,KAAK,GAAG,MAAM;IAuB5D,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAS9B"} \ No newline at end of file diff --git a/types/abi/coders/string.d.ts b/types/abi/coders/string.d.ts new file mode 100644 index 000000000..2db6f33aa --- /dev/null +++ b/types/abi/coders/string.d.ts @@ -0,0 +1,10 @@ +import { Typed } from "../typed.js"; +import { DynamicBytesCoder } from "./bytes.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class StringCoder extends DynamicBytesCoder { + constructor(localName: string); + defaultValue(): string; + encode(writer: Writer, _value: string | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/string.d.ts.map b/types/abi/coders/string.d.ts.map new file mode 100644 index 000000000..048bae2b1 --- /dev/null +++ b/types/abi/coders/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/string.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG1D,qBAAa,WAAY,SAAQ,iBAAiB;gBAElC,SAAS,EAAE,MAAM;IAI7B,YAAY,IAAI,MAAM;IAItB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,MAAM;IAItD,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/coders/tuple.d.ts b/types/abi/coders/tuple.d.ts new file mode 100644 index 000000000..2b9db23d1 --- /dev/null +++ b/types/abi/coders/tuple.d.ts @@ -0,0 +1,13 @@ +import { Typed } from "../typed.js"; +import { Coder } from "./abstract-coder.js"; +import type { Reader, Writer } from "./abstract-coder.js"; +export declare class TupleCoder extends Coder { + readonly coders: ReadonlyArray; + constructor(coders: Array, localName: string); + defaultValue(): any; + encode(writer: Writer, _value: Array | { + [name: string]: any; + } | Typed): number; + decode(reader: Reader): any; +} +//# sourceMappingURL=tuple.d.ts.map \ No newline at end of file diff --git a/types/abi/coders/tuple.d.ts.map b/types/abi/coders/tuple.d.ts.map new file mode 100644 index 000000000..807d196c9 --- /dev/null +++ b/types/abi/coders/tuple.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.d.ts","sourceRoot":"","sources":["../../../src.ts/abi/coders/tuple.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAI5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE1D,qBAAa,UAAW,SAAQ,KAAK;IACjC,QAAQ,CAAC,MAAM,EAAG,aAAa,CAAC,KAAK,CAAC,CAAC;gBAE3B,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,MAAM;IAanD,YAAY,IAAI,GAAG;IA+BnB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG;QAAE,CAAE,IAAI,EAAE,MAAM,GAAI,GAAG,CAAA;KAAE,GAAG,KAAK,GAAG,MAAM;IAKtF,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG;CAG9B"} \ No newline at end of file diff --git a/types/abi/fragments.d.ts b/types/abi/fragments.d.ts new file mode 100644 index 000000000..83b3e3676 --- /dev/null +++ b/types/abi/fragments.d.ts @@ -0,0 +1,153 @@ +export interface JsonFragmentType { + readonly name?: string; + readonly indexed?: boolean; + readonly type?: string; + readonly internalType?: string; + readonly components?: ReadonlyArray; +} +export interface JsonFragment { + readonly name?: string; + readonly type?: string; + readonly anonymous?: boolean; + readonly payable?: boolean; + readonly constant?: boolean; + readonly stateMutability?: string; + readonly inputs?: ReadonlyArray; + readonly outputs?: ReadonlyArray; + readonly gas?: string; +} +export declare enum FormatType { + sighash = "sighash", + minimal = "minimal", + full = "full", + json = "json" +} +export declare type Token = Readonly<{ + type: string; + offset: number; + text: string; + depth: number; + match: number; + linkBack: number; + linkNext: number; + value: number; +}>; +export declare class TokenString { + #private; + get offset(): number; + get length(): number; + constructor(tokens: ReadonlyArray); + clone(): TokenString; + reset(): void; + popKeyword(allowed: ReadonlySet): string; + popType(type: string): string; + popParen(): TokenString; + popParams(): Array; + peek(): Token; + peekKeyword(allowed: ReadonlySet): null | string; + peekType(type: string): null | string; + pop(): Token; + toString(): string; +} +export declare function lex(text: string): TokenString; +export interface ArrayParamType { + readonly arrayLength: number; + readonly arrayChildren: ParamType; +} +export interface TupleParamType extends ParamType { + readonly components: ReadonlyArray; +} +export interface IndexableParamType extends ParamType { + readonly indexed: boolean; +} +export declare type FragmentWalkFunc = (type: string, value: any) => any; +export declare type FragmentWalkAsyncFunc = (type: string, value: any) => any | Promise; +export declare class ParamType { + #private; + readonly name: string; + readonly type: string; + readonly baseType: string; + readonly indexed: null | boolean; + readonly components: null | ReadonlyArray; + readonly arrayLength: null | number; + readonly arrayChildren: null | ParamType; + constructor(guard: any, name: string, type: string, baseType: string, indexed: null | boolean, components: null | ReadonlyArray, arrayLength: null | number, arrayChildren: null | ParamType); + format(format?: FormatType): string; + static isArray(value: any): value is { + arrayChildren: ParamType; + }; + isArray(): this is (ParamType & ArrayParamType); + isTuple(): this is TupleParamType; + isIndexable(): this is IndexableParamType; + walk(value: any, process: FragmentWalkFunc): any; + walkAsync(value: any, process: (type: string, value: any) => any | Promise): Promise; + static from(obj: any, allowIndexed?: boolean): ParamType; + static fromObject(obj: any, allowIndexed?: boolean): ParamType; + static fromTokens(tokens: TokenString, allowIndexed?: boolean): ParamType; + static isParamType(value: any): value is ParamType; +} +export declare enum FragmentType { + "constructor" = "constructor", + "error" = "error", + "event" = "event", + "function" = "function", + "struct" = "struct" +} +export declare abstract class Fragment { + readonly type: FragmentType; + readonly inputs: ReadonlyArray; + constructor(guard: any, type: FragmentType, inputs: ReadonlyArray); + abstract format(format?: FormatType): string; + static from(obj: any): Fragment; + static fromObject(obj: any): Fragment; + static fromString(text: string): Fragment; + static fromTokens(tokens: TokenString): Fragment; + static isConstructor(value: any): value is ConstructorFragment; + static isError(value: any): value is ErrorFragment; + static isEvent(value: any): value is EventFragment; + static isFunction(value: any): value is FunctionFragment; + static isStruct(value: any): value is StructFragment; +} +export declare abstract class NamedFragment extends Fragment { + readonly name: string; + constructor(guard: any, type: FragmentType, name: string, inputs: ReadonlyArray); +} +export declare class ErrorFragment extends NamedFragment { + constructor(guard: any, name: string, inputs: ReadonlyArray); + format(format?: FormatType): string; + static fromString(text: string): ErrorFragment; + static fromTokens(tokens: TokenString): ErrorFragment; +} +export declare class EventFragment extends NamedFragment { + readonly anonymous: boolean; + constructor(guard: any, name: string, inputs: ReadonlyArray, anonymous: boolean); + format(format?: FormatType): string; + static fromString(text: string): EventFragment; + static fromTokens(tokens: TokenString): EventFragment; +} +export declare class ConstructorFragment extends Fragment { + readonly payable: boolean; + readonly gas: null | bigint; + constructor(guard: any, type: FragmentType, inputs: ReadonlyArray, payable: boolean, gas: null | bigint); + format(format?: FormatType): string; + static fromString(text: string): ConstructorFragment; + static fromObject(obj: any): ConstructorFragment; + static fromTokens(tokens: TokenString): ConstructorFragment; +} +export declare class FunctionFragment extends NamedFragment { + readonly constant: boolean; + readonly outputs: ReadonlyArray; + readonly stateMutability: string; + readonly payable: boolean; + readonly gas: null | bigint; + constructor(guard: any, name: string, stateMutability: string, inputs: ReadonlyArray, outputs: ReadonlyArray, gas: null | bigint); + format(format?: FormatType): string; + static fromString(text: string): FunctionFragment; + static fromTokens(tokens: TokenString): FunctionFragment; +} +export declare class StructFragment extends NamedFragment { + format(): string; + static fromString(text: string): StructFragment; + static fromTokens(tokens: TokenString): StructFragment; +} +//# sourceMappingURL=fragments.d.ts.map \ No newline at end of file diff --git a/types/abi/fragments.d.ts.map b/types/abi/fragments.d.ts.map new file mode 100644 index 000000000..55458085b --- /dev/null +++ b/types/abi/fragments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fragments.d.ts","sourceRoot":"","sources":["../../src.ts/abi/fragments.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,gBAAgB;IA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@ +export { AbiCoder, defaultAbiCoder } from "./abi-coder.js"; +export { formatBytes32String, parseBytes32String } from "./bytes32.js"; +export { ConstructorFragment, ErrorFragment, EventFragment, Fragment, FunctionFragment, ParamType } from "./fragments.js"; +export { checkResultErrors, Indexed, Interface, LogDescription, Result, TransactionDescription } from "./interface.js"; +export { Typed } from "./typed.js"; +export type { JsonFragment, JsonFragmentType, } from "./fragments.js"; +export type { InterfaceAbi, } from "./interface.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/abi/index.d.ts.map b/types/abi/index.d.ts.map new file mode 100644 index 000000000..4de003943 --- /dev/null +++ b/types/abi/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/abi/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,QAAQ,EACR,eAAe,EAClB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEvE,OAAO,EACH,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,QAAQ,EACR,gBAAgB,EAChB,SAAS,EACZ,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACH,iBAAiB,EACjB,OAAO,EACP,SAAS,EACT,cAAc,EACd,MAAM,EACN,sBAAsB,EACzB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,YAAY,EACR,YAAY,EACZ,gBAAgB,GACnB,MAAM,gBAAgB,CAAC;AAGxB,YAAY,EACR,YAAY,GACf,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/types/abi/interface.d.ts b/types/abi/interface.d.ts new file mode 100644 index 000000000..c4eb69fbd --- /dev/null +++ b/types/abi/interface.d.ts @@ -0,0 +1,83 @@ +import { AbiCoder } from "./abi-coder.js"; +import { checkResultErrors, Result } from "./coders/abstract-coder.js"; +import { ConstructorFragment, ErrorFragment, EventFragment, FormatType, Fragment, FunctionFragment, ParamType } from "./fragments.js"; +import { Typed } from "./typed.js"; +import type { BigNumberish, BytesLike } from "../utils/index.js"; +import type { JsonFragment } from "./fragments.js"; +export { checkResultErrors, Result }; +export declare class LogDescription { + readonly fragment: EventFragment; + readonly name: string; + readonly signature: string; + readonly topic: string; + readonly args: Result; + constructor(fragment: EventFragment, topic: string, args: Result); +} +export declare class TransactionDescription { + readonly fragment: FunctionFragment; + readonly name: string; + readonly args: Result; + readonly signature: string; + readonly selector: string; + readonly value: bigint; + constructor(fragment: FunctionFragment, selector: string, args: Result, value: bigint); +} +export declare class ErrorDescription { + readonly fragment: ErrorFragment; + readonly name: string; + readonly args: Result; + readonly signature: string; + readonly selector: string; + constructor(fragment: ErrorFragment, selector: string, args: Result); +} +export declare class Indexed { + readonly hash: null | string; + readonly _isIndexed: boolean; + static isIndexed(value: any): value is Indexed; + constructor(hash: null | string); +} +export declare type InterfaceAbi = string | ReadonlyArray; +export declare class Interface { + #private; + readonly fragments: ReadonlyArray; + readonly deploy: ConstructorFragment; + constructor(fragments: InterfaceAbi); + format(format?: FormatType): string | Array; + getAbiCoder(): AbiCoder; + getFunctionName(key: string): string; + getFunction(key: string, values?: Array): FunctionFragment; + getEventName(key: string): string; + getEvent(key: string, values?: Array): EventFragment; + getError(key: string, values?: Array): ErrorFragment; + getSelector(fragment: ErrorFragment | FunctionFragment): string; + getEventTopic(fragment: EventFragment): string; + _decodeParams(params: ReadonlyArray, data: BytesLike): Result; + _encodeParams(params: ReadonlyArray, values: ReadonlyArray): string; + encodeDeploy(values?: ReadonlyArray): string; + decodeErrorResult(fragment: ErrorFragment | string, data: BytesLike): Result; + encodeErrorResult(fragment: ErrorFragment | string, values?: ReadonlyArray): string; + decodeFunctionData(fragment: FunctionFragment | string, data: BytesLike): Result; + encodeFunctionData(fragment: FunctionFragment | string, values?: ReadonlyArray): string; + decodeFunctionResult(fragment: FunctionFragment | string, data: BytesLike): Result; + makeError(fragment: FunctionFragment | string, _data: BytesLike, tx?: { + data: string; + }): Error; + encodeFunctionResult(functionFragment: FunctionFragment | string, values?: ReadonlyArray): string; + encodeFilterTopics(eventFragment: EventFragment, values: ReadonlyArray): Array>; + encodeEventLog(eventFragment: EventFragment, values: ReadonlyArray): { + data: string; + topics: Array; + }; + decodeEventLog(eventFragment: EventFragment | string, data: BytesLike, topics?: ReadonlyArray): Result; + parseTransaction(tx: { + data: string; + value?: BigNumberish; + }): null | TransactionDescription; + parseLog(log: { + topics: Array; + data: string; + }): null | LogDescription; + parseError(data: BytesLike): null | ErrorDescription; + static from(value: ReadonlyArray | string | Interface): Interface; +} +//# sourceMappingURL=interface.d.ts.map \ No newline at end of file diff --git a/types/abi/interface.d.ts.map b/types/abi/interface.d.ts.map new file mode 100644 index 000000000..9177198d5 --- /dev/null +++ b/types/abi/interface.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"interface.d.ts","sourceRoot":"","sources":["../../src.ts/abi/interface.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,QAAQ,EAAmB,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,UAAU,EAAE,QAAQ,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACtI,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,CAAC;AAErC,qBAAa,cAAc;IACvB,QAAQ,CAAC,QAAQ,EAAG,aAAa,CAAC;IAClC,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAG,MAAM,CAAC;IAC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AC,GAAG,EAAE;QAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAC,GAAG,IAAI,GAAG,cAAc;IAa5E,UAAU,CAAC,IAAI,EAAE,SAAS,GAAG,IAAI,GAAG,gBAAgB;IAYpD,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,aAAa,CAAC,QAAQ,GAAG,MAAM,GAAG,YAAY,CAAC,GAAG,MAAM,GAAG,SAAS;CAe1F"} \ No newline at end of file diff --git a/types/abi/typed.d.ts b/types/abi/typed.d.ts new file mode 100644 index 000000000..dc39df204 --- /dev/null +++ b/types/abi/typed.d.ts @@ -0,0 +1,144 @@ +import type { Addressable } from "../address/index.js"; +import type { BigNumberish, BytesLike } from "../utils/index.js"; +import type { Result } from "./coders/abstract-coder.js"; +export interface TypedNumber extends Typed { + defaultValue(): number; + minValue(): number; + maxValue(): number; +} +export interface TypedBigInt extends Typed { + defaultValue(): bigint; + minValue(): bigint; + maxValue(): bigint; +} +export interface TypedData extends Typed { + defaultValue(): string; +} +export interface TypedString extends Typed { + defaultValue(): string; +} +export declare class Typed { + #private; + readonly type: string; + readonly value: any; + readonly _typedSymbol: Symbol; + constructor(gaurd: any, type: string, value: any, options?: any); + format(): string; + defaultValue(): string | number | bigint | Result; + minValue(): string | number | bigint; + maxValue(): string | number | bigint; + isBigInt(): this is TypedBigInt; + isData(): this is TypedData; + isString(): this is TypedString; + get tupleName(): null | string; + get arrayLength(): null | number; + static from(type: string, value: any): Typed; + static uint8(v: BigNumberish): Typed; + static uint16(v: BigNumberish): Typed; + static uint24(v: BigNumberish): Typed; + static uint32(v: BigNumberish): Typed; + static uint40(v: BigNumberish): Typed; + static uint48(v: BigNumberish): Typed; + static uint56(v: BigNumberish): Typed; + static uint64(v: BigNumberish): Typed; + static uint72(v: BigNumberish): Typed; + static uint80(v: BigNumberish): Typed; + static uint88(v: BigNumberish): Typed; + static uint96(v: BigNumberish): Typed; + static uint104(v: BigNumberish): Typed; + static uint112(v: BigNumberish): Typed; + static uint120(v: BigNumberish): Typed; + static uint128(v: BigNumberish): Typed; + static uint136(v: BigNumberish): Typed; + static uint144(v: BigNumberish): Typed; + static uint152(v: BigNumberish): Typed; + static uint160(v: BigNumberish): Typed; + static uint168(v: BigNumberish): Typed; + static uint176(v: BigNumberish): Typed; + static uint184(v: BigNumberish): Typed; + static uint192(v: BigNumberish): Typed; + static uint200(v: BigNumberish): Typed; + static uint208(v: BigNumberish): Typed; + static uint216(v: BigNumberish): Typed; + static uint224(v: BigNumberish): Typed; + static uint232(v: BigNumberish): Typed; + static uint240(v: BigNumberish): Typed; + static uint248(v: BigNumberish): Typed; + static uint256(v: BigNumberish): Typed; + static uint(v: BigNumberish): Typed; + static int8(v: BigNumberish): Typed; + static int16(v: BigNumberish): Typed; + static int24(v: BigNumberish): Typed; + static int32(v: BigNumberish): Typed; + static int40(v: BigNumberish): Typed; + static int48(v: BigNumberish): Typed; + static int56(v: BigNumberish): Typed; + static int64(v: BigNumberish): Typed; + static int72(v: BigNumberish): Typed; + static int80(v: BigNumberish): Typed; + static int88(v: BigNumberish): Typed; + static int96(v: BigNumberish): Typed; + static int104(v: BigNumberish): Typed; + static int112(v: BigNumberish): Typed; + static int120(v: BigNumberish): Typed; + static int128(v: BigNumberish): Typed; + static int136(v: BigNumberish): Typed; + static int144(v: BigNumberish): Typed; + static int152(v: BigNumberish): Typed; + static int160(v: BigNumberish): Typed; + static int168(v: BigNumberish): Typed; + static int176(v: BigNumberish): Typed; + static int184(v: BigNumberish): Typed; + static int192(v: BigNumberish): Typed; + static int200(v: BigNumberish): Typed; + static int208(v: BigNumberish): Typed; + static int216(v: BigNumberish): Typed; + static int224(v: BigNumberish): Typed; + static int232(v: BigNumberish): Typed; + static int240(v: BigNumberish): Typed; + static int248(v: BigNumberish): Typed; + static int256(v: BigNumberish): Typed; + static int(v: BigNumberish): Typed; + static bytes(v: BytesLike): Typed; + static bytes1(v: BytesLike): Typed; + static bytes2(v: BytesLike): Typed; + static bytes3(v: BytesLike): Typed; + static bytes4(v: BytesLike): Typed; + static bytes5(v: BytesLike): Typed; + static bytes6(v: BytesLike): Typed; + static bytes7(v: BytesLike): Typed; + static bytes8(v: BytesLike): Typed; + static bytes9(v: BytesLike): Typed; + static bytes10(v: BytesLike): Typed; + static bytes11(v: BytesLike): Typed; + static bytes12(v: BytesLike): Typed; + static bytes13(v: BytesLike): Typed; + static bytes14(v: BytesLike): Typed; + static bytes15(v: BytesLike): Typed; + static bytes16(v: BytesLike): Typed; + static bytes17(v: BytesLike): Typed; + static bytes18(v: BytesLike): Typed; + static bytes19(v: BytesLike): Typed; + static bytes20(v: BytesLike): Typed; + static bytes21(v: BytesLike): Typed; + static bytes22(v: BytesLike): Typed; + static bytes23(v: BytesLike): Typed; + static bytes24(v: BytesLike): Typed; + static bytes25(v: BytesLike): Typed; + static bytes26(v: BytesLike): Typed; + static bytes27(v: BytesLike): Typed; + static bytes28(v: BytesLike): Typed; + static bytes29(v: BytesLike): Typed; + static bytes30(v: BytesLike): Typed; + static bytes31(v: BytesLike): Typed; + static bytes32(v: BytesLike): Typed; + static address(v: string | Addressable): Typed; + static bool(v: any): Typed; + static string(v: string): Typed; + static array(v: Array, dynamic?: null | boolean): Typed; + static tuple(v: Array | Record, name?: string): Typed; + static overrides(v: Record): Typed; + static isTyped(value: any): value is Typed; + static dereference(value: Typed | T, type: string): T; +} +//# sourceMappingURL=typed.d.ts.map \ No newline at end of file diff --git a/types/abi/typed.d.ts.map b/types/abi/typed.d.ts.map new file mode 100644 index 000000000..39a88b1c9 --- /dev/null +++ b/types/abi/typed.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typed.d.ts","sourceRoot":"","sources":["../../src.ts/abi/typed.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE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AAC,EAAE,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,EAAE,OAAO,CAAC,EAAE,IAAI,GAAG,OAAO,GAAG,KAAK;IAKpE,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,GAAG,KAAK,CAAC,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,KAAK;IAKvF,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,KAAK;IAI/C,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,KAAK;IAI1C,MAAM,CAAC,WAAW,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC;CAS3D"} \ No newline at end of file diff --git a/types/address/address.d.ts b/types/address/address.d.ts new file mode 100644 index 000000000..5c7390901 --- /dev/null +++ b/types/address/address.d.ts @@ -0,0 +1,3 @@ +export declare function getAddress(address: string): string; +export declare function getIcapAddress(address: string): string; +//# sourceMappingURL=address.d.ts.map \ No newline at end of file diff --git a/types/address/address.d.ts.map b/types/address/address.d.ts.map new file mode 100644 index 000000000..df0d21675 --- /dev/null +++ b/types/address/address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src.ts/address/address.ts"],"names":[],"mappings":"AAmFA,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAkClD;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAKtD"} \ No newline at end of file diff --git a/types/address/checks.d.ts b/types/address/checks.d.ts new file mode 100644 index 000000000..2ab06d8be --- /dev/null +++ b/types/address/checks.d.ts @@ -0,0 +1,5 @@ +import type { Addressable, AddressLike, NameResolver } from "./index.js"; +export declare function isAddressable(value: any): value is Addressable; +export declare function isAddress(value: any): boolean; +export declare function resolveAddress(target: AddressLike, resolver?: null | NameResolver): string | Promise; +//# sourceMappingURL=checks.d.ts.map \ No newline at end of file diff --git a/types/address/checks.d.ts.map b/types/address/checks.d.ts.map new file mode 100644 index 000000000..00198952f --- /dev/null +++ b/types/address/checks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"checks.d.ts","sourceRoot":"","sources":["../../src.ts/address/checks.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAGzE,wBAAgB,aAAa,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,WAAW,CAE9D;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO,CAM7C;AAeD,wBAAgB,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,YAAY,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAqB5G"} \ No newline at end of file diff --git a/types/address/contract-address.d.ts b/types/address/contract-address.d.ts new file mode 100644 index 000000000..2e81279cf --- /dev/null +++ b/types/address/contract-address.d.ts @@ -0,0 +1,7 @@ +import type { BigNumberish, BytesLike } from "../utils/index.js"; +export declare function getCreateAddress(tx: { + from: string; + nonce: BigNumberish; +}): string; +export declare function getCreate2Address(_from: string, _salt: BytesLike, _initCodeHash: BytesLike): string; +//# sourceMappingURL=contract-address.d.ts.map \ No newline at end of file diff --git a/types/address/contract-address.d.ts.map b/types/address/contract-address.d.ts.map new file mode 100644 index 000000000..dce2051d0 --- /dev/null +++ b/types/address/contract-address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"contract-address.d.ts","sourceRoot":"","sources":["../../src.ts/address/contract-address.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAIjE,wBAAgB,gBAAgB,CAAC,EAAE,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,YAAY,CAAA;CAAE,GAAG,MAAM,CAclF;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,SAAS,GAAG,MAAM,CAcnG"} \ No newline at end of file diff --git a/types/address/index.d.ts b/types/address/index.d.ts new file mode 100644 index 000000000..cfdbc8205 --- /dev/null +++ b/types/address/index.d.ts @@ -0,0 +1,11 @@ +export interface Addressable { + getAddress(): Promise; +} +export declare type AddressLike = string | Promise | Addressable; +export interface NameResolver { + resolveName(name: string): Promise; +} +export { getAddress, getIcapAddress } from "./address.js"; +export { getCreateAddress, getCreate2Address } from "./contract-address.js"; +export { isAddressable, isAddress, resolveAddress } from "./checks.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/address/index.d.ts.map b/types/address/index.d.ts.map new file mode 100644 index 000000000..d182c5d25 --- /dev/null +++ b/types/address/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/address/index.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IACxB,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CACjC;AAED,oBAAY,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC;AAEjE,MAAM,WAAW,YAAY;IACzB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;CACrD;AAED,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE1D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG5E,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/types/constants/addresses.d.ts b/types/constants/addresses.d.ts new file mode 100644 index 000000000..0e158f865 --- /dev/null +++ b/types/constants/addresses.d.ts @@ -0,0 +1,5 @@ +/** + * A constant for the zero address. + */ +export declare const ZeroAddress = "0x0000000000000000000000000000000000000000"; +//# sourceMappingURL=addresses.d.ts.map \ No newline at end of file diff --git a/types/constants/addresses.d.ts.map b/types/constants/addresses.d.ts.map new file mode 100644 index 000000000..d60a7d43c --- /dev/null +++ b/types/constants/addresses.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"addresses.d.ts","sourceRoot":"","sources":["../../src.ts/constants/addresses.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,eAAO,MAAM,WAAW,+CAA+C,CAAC"} \ No newline at end of file diff --git a/types/constants/hashes.d.ts b/types/constants/hashes.d.ts new file mode 100644 index 000000000..9b4167b60 --- /dev/null +++ b/types/constants/hashes.d.ts @@ -0,0 +1,5 @@ +/** + * A constant for the zero hash. + */ +export declare const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; +//# sourceMappingURL=hashes.d.ts.map \ No newline at end of file diff --git a/types/constants/hashes.d.ts.map b/types/constants/hashes.d.ts.map new file mode 100644 index 000000000..2bfc41146 --- /dev/null +++ b/types/constants/hashes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hashes.d.ts","sourceRoot":"","sources":["../../src.ts/constants/hashes.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,QAAQ,uEAAuE,CAAC"} \ No newline at end of file diff --git a/types/constants/index.d.ts b/types/constants/index.d.ts new file mode 100644 index 000000000..04228bc79 --- /dev/null +++ b/types/constants/index.d.ts @@ -0,0 +1,5 @@ +export { ZeroAddress } from "./addresses.js"; +export { ZeroHash } from "./hashes.js"; +export { NegativeOne, Zero, One, Two, N, WeiPerEther, MaxUint256, MinInt256, MaxInt256 } from "./numbers.js"; +export { EtherSymbol, MessagePrefix } from "./strings.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/constants/index.d.ts.map b/types/constants/index.d.ts.map new file mode 100644 index 000000000..87523f7c1 --- /dev/null +++ b/types/constants/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/constants/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EACH,WAAW,EACX,IAAI,EACJ,GAAG,EACH,GAAG,EACH,CAAC,EACD,WAAW,EACX,UAAU,EACV,SAAS,EACT,SAAS,EACZ,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/types/constants/numbers.d.ts b/types/constants/numbers.d.ts new file mode 100644 index 000000000..bb90397b2 --- /dev/null +++ b/types/constants/numbers.d.ts @@ -0,0 +1,38 @@ +/** + * A constant for the BigInt of -1. + */ +declare const NegativeOne: bigint; +/** + * A constant for the BigInt of 0. + */ +declare const Zero: bigint; +/** + * A constant for the BigInt of 1. + */ +declare const One: bigint; +/** + * A constant for the BigInt of 2. + */ +declare const Two: bigint; +/** + * A constant for the order N for the secp256k1 curve. + */ +declare const N: bigint; +/** + * A constant for the number of wei in a single ether. + */ +declare const WeiPerEther: bigint; +/** + * A constant for the maximum value for a ``uint256``. + */ +declare const MaxUint256: bigint; +/** + * A constant for the minimum value for an ``int256``. + */ +declare const MinInt256: bigint; +/** + * A constant for the maximum value for an ``int256``. + */ +declare const MaxInt256: bigint; +export { NegativeOne, Zero, One, Two, N, WeiPerEther, MaxUint256, MinInt256, MaxInt256, }; +//# sourceMappingURL=numbers.d.ts.map \ No newline at end of file diff --git a/types/constants/numbers.d.ts.map b/types/constants/numbers.d.ts.map new file mode 100644 index 000000000..e95c23a40 --- /dev/null +++ b/types/constants/numbers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../../src.ts/constants/numbers.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,QAAA,MAAM,WAAW,QAAa,CAAC;AAE/B;;GAEG;AACH,QAAA,MAAM,IAAI,QAAY,CAAC;AAEvB;;GAEG;AACH,QAAA,MAAM,GAAG,QAAY,CAAC;AAEtB;;GAEG;AACH,QAAA,MAAM,GAAG,QAAY,CAAC;AAEtB;;GAEG;AACH,QAAA,MAAM,CAAC,QAA+E,CAAC;AAEvF;;GAEG;AACH,QAAA,MAAM,WAAW,QAAgC,CAAC;AAElD;;GAEG;AACH,QAAA,MAAM,UAAU,QAA+E,CAAC;AAEhG;;GAEG;AACH,QAAA,MAAM,SAAS,QAA6F,CAAC;AAE7G;;GAEG;AACH,QAAA,MAAM,SAAS,QAA+E,CAAC;AAE/F,OAAO,EACH,WAAW,EACX,IAAI,EACJ,GAAG,EACH,GAAG,EACH,CAAC,EACD,WAAW,EACX,UAAU,EACV,SAAS,EACT,SAAS,GACZ,CAAC"} \ No newline at end of file diff --git a/types/constants/strings.d.ts b/types/constants/strings.d.ts new file mode 100644 index 000000000..bd51caae1 --- /dev/null +++ b/types/constants/strings.d.ts @@ -0,0 +1,6 @@ +/** + * A constant for the ether symbol (normalized using NFKC). + */ +export declare const EtherSymbol = "\u039E"; +export declare const MessagePrefix = "\u0019Ethereum Signed Message:\n"; +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/types/constants/strings.d.ts.map b/types/constants/strings.d.ts.map new file mode 100644 index 000000000..707297963 --- /dev/null +++ b/types/constants/strings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../../src.ts/constants/strings.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,WAAW,WAAW,CAAC;AAGpC,eAAO,MAAM,aAAa,qCAAmC,CAAC"} \ No newline at end of file diff --git a/types/contract/contract.d.ts b/types/contract/contract.d.ts new file mode 100644 index 000000000..423a3cc4f --- /dev/null +++ b/types/contract/contract.d.ts @@ -0,0 +1,43 @@ +import { Interface } from "../abi/index.js"; +import { TransactionResponse } from "../providers/index.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 } from "./types.js"; +export declare function copyOverrides(arg: any): Promise>; +export declare function resolveArgs(_runner: null | ContractRunner, inputs: ReadonlyArray, args: Array): Promise>; +declare const internal: unique symbol; +export declare class BaseContract implements Addressable, EventEmitterable { + readonly target: string | Addressable; + readonly interface: Interface; + readonly runner: null | ContractRunner; + readonly filters: Record; + readonly [internal]: any; + constructor(target: string | Addressable, abi: Interface | InterfaceAbi, runner?: null | ContractRunner, _deployTx?: null | TransactionResponse); + getAddress(): Promise; + getDeployedCode(): Promise; + waitForDeployment(): Promise; + deploymentTransaction(): null | ContractTransactionResponse; + getFunction(key: string | FunctionFragment): T; + getEvent(key: string | EventFragment): ContractEvent; + queryTransaction(hash: string): Promise>; + queryFilter(event: ContractEventName, fromBlock?: BlockTag, toBlock?: BlockTag): Promise>; + on(event: ContractEventName, listener: Listener): Promise; + once(event: ContractEventName, listener: Listener): Promise; + emit(event: ContractEventName, ...args: Array): Promise; + listenerCount(event?: ContractEventName): Promise; + listeners(event?: ContractEventName): Promise>; + off(event: ContractEventName, listener?: Listener): Promise; + removeAllListeners(event?: ContractEventName): Promise; + addListener(event: ContractEventName, listener: Listener): Promise; + removeListener(event: ContractEventName, listener: Listener): Promise; + static buildClass(abi: InterfaceAbi): new (target: string, runner?: null | ContractRunner) => BaseContract & Omit; + static from(target: string, abi: InterfaceAbi, runner?: null | ContractRunner): BaseContract & Omit; +} +declare const Contract_base: new (target: string, abi: InterfaceAbi, runner?: ContractRunner | null | undefined) => BaseContract & Omit; +export declare class Contract extends Contract_base { +} +export {}; +//# sourceMappingURL=contract.d.ts.map \ No newline at end of file diff --git a/types/contract/contract.d.ts.map b/types/contract/contract.d.ts.map new file mode 100644 index 000000000..906fe0aad --- /dev/null +++ b/types/contract/contract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src.ts/contract/contract.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAS,MAAM,iBAAiB,CAAC;AAInD,OAAO,EAAoB,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE9E,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,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EACR,QAAQ,EAAE,cAAc,EAC3B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EACR,iBAAiB,EACjB,iBAAiB,EAGjB,cAAc,EAEd,aAAa,EACb,mBAAmB,EAEtB,MAAM,YAAY,CAAC;AAgGpB,wBAAsB,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAmB/F;AAED,wBAAsB,WAAW,CAAC,OAAO,EAAE,IAAI,GAAG,cAAc,EAAE,MAAM,EAAE,aAAa,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAUzI;AAiKD,QAAA,MAAM,QAAQ,eAAyC,CAAC;AAyJxD,qBAAa,YAAa,YAAW,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contract/factory.d.ts @@ -0,0 +1,22 @@ +import { Interface } from "../abi/index.js"; +import { BaseContract } from "./contract.js"; +import type { InterfaceAbi } from "../abi/index.js"; +import type { ContractRunner } from "../providers/index.js"; +import type { BytesLike } from "../utils/index.js"; +import type { ContractInterface, ContractMethodArgs, ContractDeployTransaction } from "./types.js"; +import type { ContractTransactionResponse } from "./wrappers.js"; +export declare class ContractFactory = Array, I = BaseContract> { + readonly interface: Interface; + readonly bytecode: string; + readonly runner: null | ContractRunner; + constructor(abi: Interface | InterfaceAbi, bytecode: BytesLike | { + object: string; + }, runner?: null | ContractRunner); + getDeployTransaction(...args: ContractMethodArgs): Promise; + deploy(...args: ContractMethodArgs): Promise>; + connect(runner: null | ContractRunner): ContractFactory; + static fromSolidity = Array, I = ContractInterface>(output: any, runner?: ContractRunner): ContractFactory; +} +//# sourceMappingURL=factory.d.ts.map \ No newline at end of file diff --git a/types/contract/factory.d.ts.map b/types/contract/factory.d.ts.map new file mode 100644 index 000000000..c90dd1bb4 --- /dev/null +++ b/types/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;AAI5C,OAAO,EAAE,YAAY,EAA8B,MAAM,eAAe,CAAC;AAEzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,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;AAKjE,qBAAa,eAAe,CAAC,CAAC,SAAS,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY;IAC5E,QAAQ,CAAC,SAAS,EAAG,SAAS,CAAC;IAC/B,QAAQ,CAAC,QAAQ,EAAG,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAG,IAAI,GAAG,cAAc,CAAC;gBAE5B,GAAG,EAAE,SAAS,GAAG,YAAY,EAAE,QAAQ,EAAE,SAAS,GAAG;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,cAAc;IAiB7G,oBAAoB,CAAC,GAAG,IAAI,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAmBxF,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;IAc5J,OAAO,CAAC,MAAM,EAAE,IAAI,GAAG,cAAc,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC;IAI7D,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;CAkB7I"} \ No newline at end of file diff --git a/types/contract/index.d.ts b/types/contract/index.d.ts new file mode 100644 index 000000000..ab74f2c63 --- /dev/null +++ b/types/contract/index.d.ts @@ -0,0 +1,5 @@ +export { BaseContract, Contract } from "./contract.js"; +export { ContractFactory } from "./factory.js"; +export { ContractEventPayload, ContractTransactionReceipt, ContractTransactionResponse, EventLog } from "./wrappers.js"; +export type { ConstantContractMethod, ContractEvent, ContractEventArgs, ContractEventName, ContractInterface, ContractMethod, ContractMethodArgs, ContractTransaction, DeferredTopicFilter, Overrides } from "./types.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/contract/index.d.ts.map b/types/contract/index.d.ts.map new file mode 100644 index 000000000..875d7a37a --- /dev/null +++ b/types/contract/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/contract/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,YAAY,EAAE,QAAQ,EACzB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACH,eAAe,EAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACH,oBAAoB,EAAE,0BAA0B,EAAE,2BAA2B,EAC7E,QAAQ,EACX,MAAM,eAAe,CAAC;AAEvB,YAAY,EACR,sBAAsB,EAAE,aAAa,EAAE,iBAAiB,EAAE,iBAAiB,EAC3E,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAE,mBAAmB,EAC1E,mBAAmB,EAAE,SAAS,EACjC,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/types/contract/types.d.ts b/types/contract/types.d.ts new file mode 100644 index 000000000..62f007003 --- /dev/null +++ b/types/contract/types.d.ts @@ -0,0 +1,48 @@ +import type { EventFragment, FunctionFragment, Result, Typed } from "../abi/index.js"; +import type { CallRequest, PreparedRequest, TopicFilter } from "../providers/index.js"; +import type { ContractTransactionResponse } from "./wrappers.js"; +export declare type ContractEventName = string | ContractEvent | TopicFilter; +export interface ContractInterface { + [name: string]: BaseContractMethod; +} +export interface DeferredTopicFilter { + getTopicFilter(): Promise; + fragment: EventFragment; +} +export interface ContractTransaction extends PreparedRequest { + to: string; + data: string; +} +export interface ContractDeployTransaction extends Omit { +} +export interface Overrides extends Omit { +} +export declare type PostfixOverrides> = A | [...A, Overrides]; +export declare type ContractMethodArgs> = PostfixOverrides<{ + [I in keyof A]-?: A[I] | Typed; +}>; +export interface BaseContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> { + (...args: ContractMethodArgs): Promise; + name: string; + fragment: FunctionFragment; + getFragment(...args: ContractMethodArgs): FunctionFragment; + populateTransaction(...args: ContractMethodArgs): Promise; + staticCall(...args: ContractMethodArgs): Promise; + send(...args: ContractMethodArgs): Promise; + estimateGas(...args: ContractMethodArgs): Promise; + staticCallResult(...args: ContractMethodArgs): Promise; +} +export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> extends BaseContractMethod { +} +export interface ConstantContractMethod, R = any> extends ContractMethod { +} +export declare type ContractEventArgs> = { + [I in keyof A]?: A[I] | Typed | null; +}; +export interface ContractEvent = Array> { + (...args: ContractEventArgs): DeferredTopicFilter; + name: string; + fragment: EventFragment; + getFragment(...args: ContractEventArgs): EventFragment; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/types/contract/types.d.ts.map b/types/contract/types.d.ts.map new file mode 100644 index 000000000..b018643c3 --- /dev/null +++ b/types/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,WAAW,EAAE,eAAe,EAAE,WAAW,EAC5C,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAIjE,oBAAY,iBAAiB,GAAG,MAAM,GAAG,aAAa,GAAG,WAAW,CAAC;AAErE,MAAM,WAAW,iBAAiB;IAC9B,CAAE,IAAI,EAAE,MAAM,GAAI,kBAAkB,CAAC;CACxC;AAED,MAAM,WAAW,mBAAmB;IAChC,cAAc,IAAI,OAAO,CAAC,WAAW,CAAC,CAAC;IACvC,QAAQ,EAAE,aAAa,CAAC;CAC3B;AAED,MAAM,WAAW,mBAAoB,SAAQ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d.ts new file mode 100644 index 000000000..9379ed206 --- /dev/null +++ b/types/contract/wrappers.d.ts @@ -0,0 +1,37 @@ +import { Block, Log, TransactionReceipt, TransactionResponse } from "../providers/index.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"; +export declare class EventLog extends Log { + readonly interface: Interface; + readonly fragment: EventFragment; + readonly args: Result; + constructor(log: Log, iface: Interface, fragment: EventFragment); + get eventName(): string; + get eventSignature(): string; +} +export declare class ContractTransactionReceipt extends TransactionReceipt { + #private; + constructor(iface: Interface, provider: null | Provider, tx: TransactionReceipt); + get logs(): Array; +} +export declare class ContractTransactionResponse extends TransactionResponse { + #private; + constructor(iface: Interface, provider: null | Provider, tx: TransactionResponse); + wait(confirms?: number): Promise; +} +export declare class ContractEventPayload extends EventPayload { + readonly fragment: EventFragment; + readonly log: EventLog; + readonly args: Result; + constructor(contract: BaseContract, listener: null | Listener, filter: ContractEventName, fragment: EventFragment, _log: Log); + get eventName(): string; + get eventSignature(): string; + getBlock(): Promise>; + getTransaction(): Promise; + getTransactionReceipt(): Promise; +} +//# sourceMappingURL=wrappers.d.ts.map \ No newline at end of file diff --git a/types/contract/wrappers.d.ts.map b/types/contract/wrappers.d.ts.map new file mode 100644 index 000000000..bcffb3614 --- /dev/null +++ b/types/contract/wrappers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wrappers.d.ts","sourceRoot":"","sources":["../../src.ts/contract/wrappers.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,EAAE,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EACtD,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAoB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEnE,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,iBAAiB,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Q,EAAE,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,GAAG;IAO5H,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED,IAAI,cAAc,IAAI,MAAM,CAE3B;IAEK,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAIlC,cAAc,IAAI,OAAO,CAAC,mBAAmB,CAAC;IAI9C,qBAAqB,IAAI,OAAO,CAAC,kBAAkB,CAAC;CAG7D"} \ No newline at end of file diff --git a/types/crypto/crypto-browser.d.ts b/types/crypto/crypto-browser.d.ts new file mode 100644 index 000000000..ba0bbf193 --- /dev/null +++ b/types/crypto/crypto-browser.d.ts @@ -0,0 +1,15 @@ +declare global { + interface Window { + } + const window: Window; + const self: Window; +} +export interface CryptoHasher { + update(data: Uint8Array): CryptoHasher; + digest(): Uint8Array; +} +export declare function createHash(algo: string): CryptoHasher; +export declare function createHmac(_algo: string, key: Uint8Array): CryptoHasher; +export declare function pbkdf2Sync(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, _algo: "sha256" | "sha512"): Uint8Array; +export declare function randomBytes(length: number): Uint8Array; +//# sourceMappingURL=crypto-browser.d.ts.map \ No newline at end of file diff --git a/types/crypto/crypto-browser.d.ts.map b/types/crypto/crypto-browser.d.ts.map new file mode 100644 index 000000000..bfa1bf9e4 --- /dev/null +++ b/types/crypto/crypto-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto-browser.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/crypto-browser.ts"],"names":[],"mappings":"AAUA,OAAO,CAAC,MAAM,CAAC;IACX,UAAU,MAAM;KAAI;IAEpB,MAAM,MAAM,EAAE,MAAM,CAAC;IACrB,MAAM,IAAI,EAAE,MAAM,CAAC;CACtB;AAcD,MAAM,WAAW,YAAY;IACzB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,YAAY,CAAC;IACvC,MAAM,IAAI,UAAU,CAAC;CACxB;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,CAMrD;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,GAAG,YAAY,CAMvE;AAED,wBAAgB,UAAU,CAAC,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,QAAQ,GAAG,UAAU,CAM7I;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CActD"} \ No newline at end of file diff --git a/types/crypto/crypto.d.ts b/types/crypto/crypto.d.ts new file mode 100644 index 000000000..e9c555de6 --- /dev/null +++ b/types/crypto/crypto.d.ts @@ -0,0 +1,2 @@ +export { createHash, createHmac, pbkdf2Sync, randomBytes } from "crypto"; +//# sourceMappingURL=crypto.d.ts.map \ No newline at end of file diff --git a/types/crypto/crypto.d.ts.map b/types/crypto/crypto.d.ts.map new file mode 100644 index 000000000..c417228d1 --- /dev/null +++ b/types/crypto/crypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/crypto.ts"],"names":[],"mappings":"AACA,OAAO,EACH,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAClD,MAAM,QAAQ,CAAC"} \ No newline at end of file diff --git a/types/crypto/hmac.d.ts b/types/crypto/hmac.d.ts new file mode 100644 index 000000000..f8f47f0e8 --- /dev/null +++ b/types/crypto/hmac.d.ts @@ -0,0 +1,8 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function computeHmac(algorithm: "sha256" | "sha512", _key: BytesLike, _data: BytesLike): string; +export declare namespace computeHmac { + var _: (algorithm: "sha256" | "sha512", key: Uint8Array, data: Uint8Array) => BytesLike; + var lock: () => void; + var register: (func: (algorithm: "sha256" | "sha512", key: Uint8Array, data: Uint8Array) => BytesLike) => void; +} +//# sourceMappingURL=hmac.d.ts.map \ No newline at end of file diff --git a/types/crypto/hmac.d.ts.map b/types/crypto/hmac.d.ts.map new file mode 100644 index 000000000..4cd000328 --- /dev/null +++ b/types/crypto/hmac.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/hmac.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,wBAAgB,WAAW,CAAC,SAAS,EAAE,QAAQ,GAAG,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,GAAG,MAAM,CAIrG;yBAJe,WAAW"} \ No newline at end of file diff --git a/types/crypto/index.d.ts b/types/crypto/index.d.ts new file mode 100644 index 000000000..0486e0ba0 --- /dev/null +++ b/types/crypto/index.d.ts @@ -0,0 +1,15 @@ +import { computeHmac } from "./hmac.js"; +import { keccak256 } from "./keccak.js"; +import { ripemd160 } from "./ripemd160.js"; +import { pbkdf2 } from "./pbkdf2.js"; +import { randomBytes } from "./random.js"; +import { scrypt, scryptSync } from "./scrypt.js"; +import { sha256, sha512 } from "./sha2.js"; +export { computeHmac, randomBytes, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync }; +export { SigningKey } from "./signing-key.js"; +export { Signature } from "./signature.js"; +declare function lock(): void; +export { lock }; +export type { ProgressCallback } from "./scrypt.js"; +export type { SignatureLike } from "./signature.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/crypto/index.d.ts.map b/types/crypto/index.d.ts.map new file mode 100644 index 000000000..9dcd14909 --- /dev/null +++ b/types/crypto/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAE3C,OAAO,EACH,WAAW,EAEX,WAAW,EAEX,SAAS,EACT,SAAS,EACT,MAAM,EAAE,MAAM,EAEd,MAAM,EACN,MAAM,EAAE,UAAU,EACrB,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,iBAAS,IAAI,IAAI,IAAI,CAUpB;AAED,OAAO,EAAE,IAAI,EAAE,CAAC;AAKhB,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD,YAAY,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/types/crypto/keccak.d.ts b/types/crypto/keccak.d.ts new file mode 100644 index 000000000..28cfa15f0 --- /dev/null +++ b/types/crypto/keccak.d.ts @@ -0,0 +1,8 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function keccak256(_data: BytesLike): string; +export declare namespace keccak256 { + var _: (data: Uint8Array) => Uint8Array; + var lock: () => void; + var register: (func: (data: Uint8Array) => BytesLike) => void; +} +//# sourceMappingURL=keccak.d.ts.map \ No newline at end of file diff --git a/types/crypto/keccak.d.ts.map b/types/crypto/keccak.d.ts.map new file mode 100644 index 000000000..7e2655bdb --- /dev/null +++ b/types/crypto/keccak.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"keccak.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/keccak.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAGlD;yBAHe,SAAS"} \ No newline at end of file diff --git a/types/crypto/pbkdf2.d.ts b/types/crypto/pbkdf2.d.ts new file mode 100644 index 000000000..61e71de7a --- /dev/null +++ b/types/crypto/pbkdf2.d.ts @@ -0,0 +1,8 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function pbkdf2(_password: BytesLike, _salt: BytesLike, iterations: number, keylen: number, algo: "sha256" | "sha512"): string; +export declare namespace pbkdf2 { + var _: (password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, algo: "sha256" | "sha512") => BytesLike; + var lock: () => void; + var register: (func: (password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, algo: "sha256" | "sha512") => BytesLike) => void; +} +//# sourceMappingURL=pbkdf2.d.ts.map \ No newline at end of file diff --git a/types/crypto/pbkdf2.d.ts.map b/types/crypto/pbkdf2.d.ts.map new file mode 100644 index 000000000..8fc853a83 --- /dev/null +++ b/types/crypto/pbkdf2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/pbkdf2.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,wBAAgB,MAAM,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAIpI;yBAJe,MAAM"} \ No newline at end of file diff --git a/types/crypto/random.d.ts b/types/crypto/random.d.ts new file mode 100644 index 000000000..1622ec42c --- /dev/null +++ b/types/crypto/random.d.ts @@ -0,0 +1,7 @@ +export declare function randomBytes(length: number): Uint8Array; +export declare namespace randomBytes { + var _: (length: number) => Uint8Array; + var lock: () => void; + var register: (func: (length: number) => Uint8Array) => void; +} +//# sourceMappingURL=random.d.ts.map \ No newline at end of file diff --git a/types/crypto/random.d.ts.map b/types/crypto/random.d.ts.map new file mode 100644 index 000000000..3f4877a9b --- /dev/null +++ b/types/crypto/random.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/random.ts"],"names":[],"mappings":"AAUA,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAEtD;yBAFe,WAAW"} \ No newline at end of file diff --git a/types/crypto/ripemd160.d.ts b/types/crypto/ripemd160.d.ts new file mode 100644 index 000000000..afe1bb72b --- /dev/null +++ b/types/crypto/ripemd160.d.ts @@ -0,0 +1,8 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function ripemd160(_data: BytesLike): string; +export declare namespace ripemd160 { + var _: (data: Uint8Array) => Uint8Array; + var lock: () => void; + var register: (func: (data: Uint8Array) => BytesLike) => void; +} +//# sourceMappingURL=ripemd160.d.ts.map \ No newline at end of file diff --git a/types/crypto/ripemd160.d.ts.map b/types/crypto/ripemd160.d.ts.map new file mode 100644 index 000000000..8c816dfd3 --- /dev/null +++ b/types/crypto/ripemd160.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ripemd160.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/ripemd160.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAGlD;yBAHe,SAAS"} \ No newline at end of file diff --git a/types/crypto/scrypt.d.ts b/types/crypto/scrypt.d.ts new file mode 100644 index 000000000..fd4985d02 --- /dev/null +++ b/types/crypto/scrypt.d.ts @@ -0,0 +1,15 @@ +import type { BytesLike } from "../utils/index.js"; +export declare type ProgressCallback = (percent: number) => void; +export declare function scrypt(_passwd: BytesLike, _salt: BytesLike, N: number, r: number, p: number, dkLen: number, progress?: ProgressCallback): Promise; +export declare namespace scrypt { + var _: (passwd: Uint8Array, salt: Uint8Array, N: number, r: number, p: number, dkLen: number, onProgress?: ProgressCallback | undefined) => Promise; + var lock: () => void; + var register: (func: (passwd: Uint8Array, salt: Uint8Array, N: number, r: number, p: number, dkLen: number, progress?: ProgressCallback | undefined) => Promise) => void; +} +export declare function scryptSync(_passwd: BytesLike, _salt: BytesLike, N: number, r: number, p: number, dkLen: number): string; +export declare namespace scryptSync { + var _: (passwd: Uint8Array, salt: Uint8Array, N: number, r: number, p: number, dkLen: number) => Uint8Array; + var lock: () => void; + var register: (func: (passwd: Uint8Array, salt: Uint8Array, N: number, r: number, p: number, dkLen: number) => BytesLike) => void; +} +//# sourceMappingURL=scrypt.d.ts.map \ No newline at end of file diff --git a/types/crypto/scrypt.d.ts.map b/types/crypto/scrypt.d.ts.map new file mode 100644 index 000000000..d2880d5a2 --- /dev/null +++ b/types/crypto/scrypt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/scrypt.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAGnD,oBAAY,gBAAgB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAgBzD,wBAAsB,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CAI/J;yBAJqB,MAAM;;;;;AAa5B,wBAAgB,UAAU,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAIvH;yBAJe,UAAU"} \ No newline at end of file diff --git a/types/crypto/sha2.d.ts b/types/crypto/sha2.d.ts new file mode 100644 index 000000000..7009d8d48 --- /dev/null +++ b/types/crypto/sha2.d.ts @@ -0,0 +1,14 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function sha256(_data: BytesLike): string; +export declare namespace sha256 { + var _: (data: Uint8Array) => Uint8Array; + var lock: () => void; + var register: (func: (data: Uint8Array) => BytesLike) => void; +} +export declare function sha512(_data: BytesLike): string; +export declare namespace sha512 { + var _: (data: Uint8Array) => Uint8Array; + var lock: () => void; + var register: (func: (data: Uint8Array) => BytesLike) => void; +} +//# sourceMappingURL=sha2.d.ts.map \ No newline at end of file diff --git a/types/crypto/sha2.d.ts.map b/types/crypto/sha2.d.ts.map new file mode 100644 index 000000000..a21231ac4 --- /dev/null +++ b/types/crypto/sha2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/sha2.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAiBnD,wBAAgB,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAG/C;yBAHe,MAAM;;;;;AAYtB,wBAAgB,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAG/C;yBAHe,MAAM"} \ No newline at end of file diff --git a/types/crypto/signature.d.ts b/types/crypto/signature.d.ts new file mode 100644 index 000000000..e128642ca --- /dev/null +++ b/types/crypto/signature.d.ts @@ -0,0 +1,46 @@ +import type { BigNumberish, BytesLike, Freezable, Frozen } from "../utils/index.js"; +export declare type SignatureLike = Signature | string | { + r: string; + s: string; + v: BigNumberish; + yParity?: 0 | 1; + yParityAndS?: string; +} | { + r: string; + yParityAndS: string; + yParity?: 0 | 1; + s?: string; + v?: number; +} | { + r: string; + s: string; + yParity: 0 | 1; + v?: BigNumberish; + yParityAndS?: string; +}; +export declare class Signature implements Freezable { + #private; + get r(): string; + set r(value: BytesLike); + get s(): string; + set s(value: BytesLike); + get v(): 27 | 28; + set v(value: BigNumberish); + get networkV(): null | bigint; + get legacyChainId(): null | bigint; + get yParity(): 0 | 1; + get yParityAndS(): string; + get compactSerialized(): string; + get serialized(): string; + constructor(guard: any, r: string, s: string, v: 27 | 28); + clone(): Signature; + freeze(): Frozen; + isFrozen(): boolean; + toJSON(): any; + static create(): Signature; + static getChainId(v: BigNumberish): bigint; + static getChainIdV(chainId: BigNumberish, v: 27 | 28): bigint; + static getNormalizedV(v: BigNumberish): 27 | 28; + static from(sig: SignatureLike): Signature; +} +//# sourceMappingURL=signature.d.ts.map \ No newline at end of file diff --git a/types/crypto/signature.d.ts.map b/types/crypto/signature.d.ts.map new file mode 100644 index 000000000..eed15ba68 --- /dev/null +++ b/types/crypto/signature.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"signature.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/signature.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAepF,oBAAY,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG;IAC7C,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,YAAY,CAAC;IAChB,OAAO,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG;IACA,CAAC,EAAE,MAAM,CAAC;IACV,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,CAAC,CAAC,EAAE,MAAM,CAAC;CACd,GAAG;IACA,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,EAAE,CAAC,GAAG,CAAC,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"} \ No newline at end of file diff --git a/types/crypto/signing-key.d.ts b/types/crypto/signing-key.d.ts new file mode 100644 index 000000000..7269c34ca --- /dev/null +++ b/types/crypto/signing-key.d.ts @@ -0,0 +1,16 @@ +import { Signature } from "./signature.js"; +import type { BytesLike, Frozen } from "../utils/index.js"; +import type { SignatureLike } from "./index.js"; +export declare class SigningKey { + #private; + constructor(privateKey: BytesLike); + get privateKey(): string; + get publicKey(): string; + get compressedPublicKey(): string; + sign(digest: BytesLike): Frozen; + computeShardSecret(other: BytesLike): string; + static computePublicKey(key: BytesLike, compressed?: boolean): string; + static recoverPublicKey(digest: BytesLike, signature: SignatureLike): string; + static _addPoints(p0: BytesLike, p1: BytesLike, compressed?: boolean): string; +} +//# sourceMappingURL=signing-key.d.ts.map \ No newline at end of file diff --git a/types/crypto/signing-key.d.ts.map b/types/crypto/signing-key.d.ts.map new file mode 100644 index 000000000..7491d9152 --- /dev/null +++ b/types/crypto/signing-key.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"signing-key.d.ts","sourceRoot":"","sources":["../../src.ts/crypto/signing-key.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAUhD,qBAAa,UAAU;;gBAGP,UAAU,EAAE,SAAS;IAUjC,IAAI,UAAU,IAAI,MAAM,CAA6B;IACrD,IAAI,SAAS,IAAI,MAAM,CAA0D;IACjF,IAAI,mBAAmB,IAAI,MAAM,CAAgE;IAEjG,IAAI,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IAmB1C,kBAAkB,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM;IAK5C,MAAM,CAAC,gBAAgB,CAAC,GAAG,EAAE,SAAS,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,MAAM;IAmBrE,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,GAAG,MAAM;IAU5E,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,MAAM;CAKhF"} \ No newline at end of file diff --git a/types/ethers.d.ts b/types/ethers.d.ts new file mode 100644 index 000000000..457bd4f66 --- /dev/null +++ b/types/ethers.d.ts @@ -0,0 +1,21 @@ +export { version } from "./_version.js"; +export { formatBytes32String, parseBytes32String, AbiCoder, defaultAbiCoder, ConstructorFragment, ErrorFragment, EventFragment, Fragment, FunctionFragment, ParamType, checkResultErrors, Indexed, Interface, LogDescription, Result, TransactionDescription, Typed, } from "./abi/index.js"; +export { getAddress, getIcapAddress, getCreateAddress, getCreate2Address } from "./address/index.js"; +export { ZeroAddress, NegativeOne, Zero, One, Two, WeiPerEther, MaxUint256, MinInt256, MaxInt256, ZeroHash, EtherSymbol, MessagePrefix } from "./constants/index.js"; +export { BaseContract, Contract, ContractFactory, ContractEventPayload, ContractTransactionReceipt, ContractTransactionResponse, EventLog, } from "./contract/index.js"; +export { computeHmac, randomBytes, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync, lock, Signature, SigningKey } from "./crypto/index.js"; +export { id, hashMessage, solidityPacked, solidityPackedKeccak256, solidityPackedSha256, TypedDataEncoder } from "./hash/index.js"; +export { accessListify, computeAddress, recoverAddress, Transaction } from "./transaction/index.js"; +export { decodeBase58, encodeBase58, isCallException, isError, FetchRequest, FetchResponse, FixedFormat, FixedNumber, formatFixed, parseFixed, assertArgument, Logger, logger, fromTwos, toTwos, mask, toArray, toBigInt, toHex, toNumber, formatEther, parseEther, formatUnits, parseUnits, _toEscapedUtf8String, toUtf8Bytes, toUtf8CodePoints, toUtf8String, Utf8ErrorFuncs, decodeRlp, encodeRlp } from "./utils/index.js"; +export { defaultPath, getAccountPath, HDNodeWallet, HDNodeVoidWallet, HDNodeWalletManager, isCrowdsaleJson, decryptCrowdsaleJson, isKeystoreJson, decryptKeystoreJsonSync, decryptKeystoreJson, encryptKeystoreJson, Mnemonic, Wallet } from "./wallet/index.js"; +export { Wordlist, langEn, LangEn, wordlists, WordlistOwl, WordlistOwlA } from "./wordlists/index.js"; +export type { JsonFragment, JsonFragmentType, InterfaceAbi, } from "./abi/index.js"; +export type { Addressable } from "./address/index.js"; +export type { ConstantContractMethod, ContractEvent, ContractEventArgs, ContractEventName, ContractInterface, ContractMethod, ContractMethodArgs, ContractTransaction, DeferredTopicFilter, Overrides } from "./contract/index.js"; +export type { ProgressCallback, SignatureLike } from "./crypto/index.js"; +export type { TypedDataDomain, TypedDataField } from "./hash/index.js"; +export { FallbackProvider, JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner, AlchemyProvider, AnkrProvider, CloudflareProvider, EtherscanProvider, InfuraProvider, IpcSocketProvider, SocketProvider, WebSocketProvider, Network } from "./providers/index.js"; +export type { AccessList, AccessListish, AccessListSet, SignedTransaction, TransactionLike } from "./transaction/index.js"; +export type { BytesLike, BigNumberish, Numeric, ErrorCode, Utf8ErrorFunc, UnicodeNormalizationForm, Utf8ErrorReason, RlpStructuredData, GetUrlResponse, FetchRequestWithBody, FetchResponseWithBody, FetchPreflightFunc, FetchProcessFunc, FetchRetryFunc, FetchGatewayFunc, FetchGetUrlFunc } from "./utils/index.js"; +export type { KeystoreAccountParams, KeystoreAccount, EncryptOptions } from "./wallet/index.js"; +//# sourceMappingURL=ethers.d.ts.map \ No newline at end of file diff --git a/types/ethers.d.ts.map b/types/ethers.d.ts.map new file mode 100644 index 000000000..1508993f8 --- /dev/null +++ b/types/ethers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ethers.d.ts","sourceRoot":"","sources":["../src.ts/ethers.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,OAAO,EACH,mB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ACxC,iBAAiB,EAAE,eAAe,EACrC,MAAM,wBAAwB,CAAC;AAEhC,YAAY,EACR,SAAS,EACT,YAAY,EAAE,OAAO,EACrB,SAAS,EACT,aAAa,EAAE,wBAAwB,EAAE,eAAe,EACxD,iBAAiB,EAEjB,cAAc,EACd,oBAAoB,EAAE,qBAAqB,EAC3C,kBAAkB,EAAE,gBAAgB,EAAE,cAAc,EACpD,gBAAgB,EAAE,eAAe,EACpC,MAAM,kBAAkB,CAAC;AAE1B,YAAY,EACR,qBAAqB,EAAE,eAAe,EACtC,cAAc,EACjB,MAAM,mBAAmB,CAAC"} \ No newline at end of file diff --git a/types/hash/id.d.ts b/types/hash/id.d.ts new file mode 100644 index 000000000..80fc69ce5 --- /dev/null +++ b/types/hash/id.d.ts @@ -0,0 +1,2 @@ +export declare function id(value: string): string; +//# sourceMappingURL=id.d.ts.map \ No newline at end of file diff --git a/types/hash/id.d.ts.map b/types/hash/id.d.ts.map new file mode 100644 index 000000000..57ba2c4f7 --- /dev/null +++ b/types/hash/id.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"id.d.ts","sourceRoot":"","sources":["../../src.ts/hash/id.ts"],"names":[],"mappings":"AAGA,wBAAgB,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAExC"} \ No newline at end of file diff --git a/types/hash/index.d.ts b/types/hash/index.d.ts new file mode 100644 index 000000000..e61b18d75 --- /dev/null +++ b/types/hash/index.d.ts @@ -0,0 +1,7 @@ +export { id } from "./id.js"; +export { isValidName, namehash, dnsEncode } from "./namehash.js"; +export { hashMessage } from "./message.js"; +export { solidityPacked, solidityPackedKeccak256, solidityPackedSha256 } from "./solidity.js"; +export { TypedDataEncoder } from "./typed-data.js"; +export type { TypedDataDomain, TypedDataField } from "./typed-data.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/hash/index.d.ts.map b/types/hash/index.d.ts.map new file mode 100644 index 000000000..2bf892df8 --- /dev/null +++ b/types/hash/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/hash/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAA;AAC5B,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACH,cAAc,EAAE,uBAAuB,EAAE,oBAAoB,EAChE,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,YAAY,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/types/hash/message.d.ts b/types/hash/message.d.ts new file mode 100644 index 000000000..6744eb2f0 --- /dev/null +++ b/types/hash/message.d.ts @@ -0,0 +1,2 @@ +export declare function hashMessage(message: Uint8Array | string): string; +//# sourceMappingURL=message.d.ts.map \ No newline at end of file diff --git a/types/hash/message.d.ts.map b/types/hash/message.d.ts.map new file mode 100644 index 000000000..090e04398 --- /dev/null +++ b/types/hash/message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["../../src.ts/hash/message.ts"],"names":[],"mappings":"AAKA,wBAAgB,WAAW,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,MAAM,CAOhE"} \ No newline at end of file diff --git a/types/hash/namehash.d.ts b/types/hash/namehash.d.ts new file mode 100644 index 000000000..3ccc70a6e --- /dev/null +++ b/types/hash/namehash.d.ts @@ -0,0 +1,5 @@ +export declare function ensNormalize(name: string): string; +export declare function isValidName(name: string): boolean; +export declare function namehash(name: string): string; +export declare function dnsEncode(name: string): string; +//# sourceMappingURL=namehash.d.ts.map \ No newline at end of file diff --git a/types/hash/namehash.d.ts.map b/types/hash/namehash.d.ts.map new file mode 100644 index 000000000..ba007ae48 --- /dev/null +++ b/types/hash/namehash.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"namehash.d.ts","sourceRoot":"","sources":["../../src.ts/hash/namehash.ts"],"names":[],"mappings":"AA2CA,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAKjD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAc7C;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAa9C"} \ No newline at end of file diff --git a/types/hash/solidity.d.ts b/types/hash/solidity.d.ts new file mode 100644 index 000000000..6ff0c6d01 --- /dev/null +++ b/types/hash/solidity.d.ts @@ -0,0 +1,24 @@ +export declare function solidityPacked(types: ReadonlyArray, values: ReadonlyArray): string; +/** + * Computes the non-standard packed (tightly packed) keccak256 hash of + * the values given the types. + * + * @param {Array} types - The Solidity types to interpret each value as [default: bar] + * @param {Array} values - The values to pack + * + * @returns: {HexString} the hexstring of the hash + * @example: + * solidityPackedKeccak256([ "address", "uint" ], [ "0x1234", 45 ]); + * //_result: + * + * @see https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode + */ +export declare function solidityPackedKeccak256(types: ReadonlyArray, values: ReadonlyArray): string; +/** + * Test Function, for fun + * + * @param foo - something fun + */ +export declare function test(foo: number | string): void; +export declare function solidityPackedSha256(types: ReadonlyArray, values: ReadonlyArray): string; +//# sourceMappingURL=solidity.d.ts.map \ No newline at end of file diff --git a/types/hash/solidity.d.ts.map b/types/hash/solidity.d.ts.map new file mode 100644 index 000000000..0980c25ba --- /dev/null +++ b/types/hash/solidity.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"solidity.d.ts","sourceRoot":"","sources":["../../src.ts/hash/solidity.ts"],"names":[],"mappings":"AA2EA,wBAAgB,cAAc,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,UAStF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,UAE/F;AAED;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAC/C;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,UAE5F"} \ No newline at end of file diff --git a/types/hash/typed-data.d.ts b/types/hash/typed-data.d.ts new file mode 100644 index 000000000..3a776216c --- /dev/null +++ b/types/hash/typed-data.d.ts @@ -0,0 +1,38 @@ +import type { BigNumberish, BytesLike } from "../utils/index.js"; +export interface TypedDataDomain { + name?: string; + version?: string; + chainId?: BigNumberish; + verifyingContract?: string; + salt?: BytesLike; +} +export interface TypedDataField { + name: string; + type: string; +} +export declare class TypedDataEncoder { + #private; + readonly primaryType: string; + get types(): Record>; + constructor(types: Record>); + getEncoder(type: string): (value: any) => string; + encodeType(name: string): string; + encodeData(type: string, value: any): string; + hashStruct(name: string, value: Record): string; + encode(value: Record): string; + hash(value: Record): string; + _visit(type: string, value: any, callback: (type: string, data: any) => any): any; + visit(value: Record, callback: (type: string, data: any) => any): any; + static from(types: Record>): TypedDataEncoder; + static getPrimaryType(types: Record>): string; + static hashStruct(name: string, types: Record>, value: Record): string; + static hashDomain(domain: TypedDataDomain): string; + static encode(domain: TypedDataDomain, types: Record>, value: Record): string; + static hash(domain: TypedDataDomain, types: Record>, value: Record): string; + static resolveNames(domain: TypedDataDomain, types: Record>, value: Record, resolveName: (name: string) => Promise): Promise<{ + domain: TypedDataDomain; + value: any; + }>; + static getPayload(domain: TypedDataDomain, types: Record>, value: Record): any; +} +//# sourceMappingURL=typed-data.d.ts.map \ No newline at end of file diff --git a/types/hash/typed-data.d.ts.map b/types/hash/typed-data.d.ts.map new file mode 100644 index 000000000..b17ed5230 --- /dev/null +++ b/types/hash/typed-data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typed-data.d.ts","sourceRoot":"","sources":["../../src.ts/hash/typed-data.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWjE,MAAM,WAAW,eAAe;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,IAAI,CAAC,EAAE,SAAS,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CAChB;AA4HD,qBAAa,gBAAgB;;IACzB,QAAQ,CAAC,WAAW,EAAG,MAAM,CAAC;IAG9B,IAAI,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC,CAEjD;gBAMW,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IA8FxD,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,CAAC,KAAK,EAAE,GAAG,KAAK,MAAM;IAuDhD,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAQhC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,MAAM;IAI5C,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;IAI5D,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;IAI1C,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,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,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,eAAe,CAAC;QAAC,KAAK,EAAE,GAAG,CAAA;KAAE,CAAC;IA0C9N,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG;CA2D5H"} \ No newline at end of file diff --git a/types/index.d.ts b/types/index.d.ts new file mode 100644 index 000000000..8be1ef736 --- /dev/null +++ b/types/index.d.ts @@ -0,0 +1,4 @@ +import * as ethers from "./ethers.js"; +export { ethers }; +export * from "./ethers.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/index.d.ts.map b/types/index.d.ts.map new file mode 100644 index 000000000..b74d646ff --- /dev/null +++ b/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src.ts/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAE,MAAM,EAAE,CAAC;AAElB,cAAc,aAAa,CAAC"} \ No newline at end of file diff --git a/types/providers/abstract-provider.d.ts b/types/providers/abstract-provider.d.ts new file mode 100644 index 000000000..3240300a1 --- /dev/null +++ b/types/providers/abstract-provider.d.ts @@ -0,0 +1,184 @@ +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 { Frozen, Listener } from "../utils/index.js"; +import type { AccessList } from "../transaction/index.js"; +import type { Networkish } from "./network.js"; +import type { BlockTag, CallRequest, EventFilter, Filter, FilterByBlockHash, OrphanFilter, Provider, ProviderEvent, TransactionRequest } from "./provider.js"; +export declare type Subscription = { + type: "block" | "close" | "debug" | "network" | "pending"; + tag: string; +} | { + type: "transaction"; + tag: string; + hash: string; +} | { + type: "event"; + tag: string; + filter: EventFilter; +} | { + type: "orphan"; + tag: string; + filter: OrphanFilter; +}; +export interface Subscriber { + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; + pollingInterval?: number; +} +export declare class UnmanagedSubscriber implements Subscriber { + name: string; + constructor(name: string); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +export interface ProviderPlugin { + readonly name: string; + validate(provider: Provider): ProviderPlugin; +} +export declare type PerformActionFilter = { + address?: string | Array; + topics?: Array>; + fromBlock?: BlockTag; + toBlock?: BlockTag; +} | { + address?: string | Array; + topics?: Array>; + blockHash?: string; +}; +export declare type PerformActionTransaction = { + type?: number; + to?: string; + from?: string; + nonce?: number; + gasLimit?: bigint; + gasPrice?: bigint; + maxPriorityFeePerGas?: bigint; + maxFeePerGas?: bigint; + data?: string; + value?: bigint; + chainId?: bigint; + accessList?: AccessList; +}; +export declare type PerformActionRequest = { + method: "call"; + transaction: PerformActionTransaction; + blockTag: BlockTag; +} | { + method: "chainId"; +} | { + method: "estimateGas"; + transaction: PerformActionTransaction; +} | { + method: "getBalance"; + address: string; + blockTag: BlockTag; +} | { + method: "getBlock"; + blockTag: BlockTag; + includeTransactions: boolean; +} | { + method: "getBlock"; + blockHash: string; + includeTransactions: boolean; +} | { + method: "getBlockNumber"; +} | { + method: "getCode"; + address: string; + blockTag: BlockTag; +} | { + method: "getGasPrice"; +} | { + method: "getLogs"; + filter: PerformActionFilter; +} | { + method: "getStorageAt"; + address: string; + position: bigint; + blockTag: BlockTag; +} | { + method: "getTransaction"; + hash: string; +} | { + method: "getTransactionCount"; + address: string; + blockTag: BlockTag; +} | { + method: "getTransactionReceipt"; + hash: string; +} | { + method: "getTransactionResult"; + hash: string; +} | { + method: "broadcastTransaction"; + signedTransaction: string; +}; +export declare function copyRequest(tx: T): T; +export declare class AbstractProvider implements Provider { + #private; + constructor(_network?: "any" | Networkish); + get provider(): this; + get plugins(): Array; + attachPlugin(plugin: ProviderPlugin): this; + getPlugin(name: string): null | T; + set disableCcipRead(value: boolean); + get disableCcipRead(): boolean; + ccipReadFetch(tx: PerformActionTransaction, calldata: string, urls: Array): Promise; + _wrapTransaction(tx: TransactionResponse, hash: string, blockNumber: number): TransactionResponse; + _detectNetwork(): Promise>; + _perform(req: PerformActionRequest): Promise; + getBlockNumber(): Promise; + _getAddress(address: AddressLike): string | Promise; + _getBlockTag(blockTag?: BlockTag): string | Promise; + getNetwork(): Promise>; + getFeeData(): Promise; + _getTransaction(_request: CallRequest): Promise; + estimateGas(_tx: TransactionRequest): Promise; + call(_tx: CallRequest): Promise; + getBalance(address: AddressLike, blockTag?: BlockTag): Promise; + getTransactionCount(address: AddressLike, blockTag?: BlockTag): Promise; + getCode(address: AddressLike, blockTag?: BlockTag): Promise; + getStorageAt(address: AddressLike, _position: BigNumberish, blockTag?: BlockTag): Promise; + broadcastTransaction(signedTx: string): Promise; + getBlock(block: BlockTag | string): Promise>; + getBlockWithTransactions(block: BlockTag | string): Promise>; + getTransaction(hash: string): Promise; + getTransactionReceipt(hash: string): Promise; + getTransactionResult(hash: string): Promise; + _getFilter(filter: Filter | FilterByBlockHash): PerformActionFilter | 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?: number, timeout?: number): Promise; + waitForBlock(blockTag?: BlockTag): Promise>; + _clearTimeout(timerId: number): void; + _setTimeout(_func: () => void, timeout?: number): number; + _forEachSubscriber(func: (s: Subscriber) => void): void; + _getSubscriber(sub: Subscription): Subscriber; + _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; + shutdown(): Promise; + get paused(): boolean; + set paused(pause: boolean); + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +//# sourceMappingURL=abstract-provider.d.ts.map \ No newline at end of file diff --git a/types/providers/abstract-provider.d.ts.map b/types/providers/abstract-provider.d.ts.map new file mode 100644 index 000000000..5d1594010 --- /dev/null +++ b/types/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":"AAkBA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAK7F,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAa,MAAM,mBAAmB,CAAC;AACjE,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAE1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,KAAK,EACR,QAAQ,EAAE,WAAW,EAAE,WAAW,EAA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AC,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;IAMvE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAU/B,IAAI,MAAM,IAAI,OAAO,CAAwC;IAC7D,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,EAQxB;IAED,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAoBtC,MAAM,IAAI,IAAI;CAiBjB"} \ No newline at end of file diff --git a/types/providers/abstract-signer.d.ts b/types/providers/abstract-signer.d.ts new file mode 100644 index 000000000..6b32a137b --- /dev/null +++ b/types/providers/abstract-signer.d.ts @@ -0,0 +1,48 @@ +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { BlockTag, CallRequest, Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +import type { Signer } from "./signer.js"; +export declare abstract class AbstractSigner

implements Signer { + #private; + readonly provider: P; + constructor(provider?: P); + abstract getAddress(): Promise; + abstract connect(provider: null | Provider): Signer; + getNonce(blockTag?: BlockTag): Promise; + populateCall(tx: CallRequest): Promise>; + populateTransaction(tx: TransactionRequest): Promise>; + estimateGas(tx: CallRequest): Promise; + call(tx: CallRequest): 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; +} +export declare class VoidSigner extends AbstractSigner { + #private; + readonly address: string; + 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; +} +export declare class WrappedSigner extends AbstractSigner { + #private; + constructor(signer: Signer); + getAddress(): Promise; + connect(provider: null | Provider): WrappedSigner; + getNonce(blockTag?: BlockTag): Promise; + populateCall(tx: CallRequest): Promise>; + populateTransaction(tx: TransactionRequest): Promise>; + estimateGas(tx: CallRequest): Promise; + call(tx: CallRequest): Promise; + resolveName(name: string): Promise; + signTransaction(tx: TransactionRequest): Promise; + sendTransaction(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/types/providers/abstract-signer.d.ts.map b/types/providers/abstract-signer.d.ts.map new file mode 100644 index 000000000..0e6f29a98 --- /dev/null +++ b/types/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":"AAIA,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,WAAW,EAAE,QAAQ,EAAE,kBAAkB,EAAE,mBAAmB,EAC3E,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAG1C,8BAAsB,cAAc,CAAC,CAAC,SAAS,IAAI,GAAG,QAAQ,GAAG,IAAI,GAAG,QAAQ,CAAE,YAAW,MAAM;;IAC/F,QAAQ,CAAC,QAAQ,EAAG,CAAC,CAAC;gBAEV,QAAQ,CAAC,EAAE,CAAC;IAIxB,QAAQ,CAAC,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC;IACtC,QAAQ,CAAC,OAAO,CA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AAe,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/types/providers/common-networks.d.ts b/types/providers/common-networks.d.ts new file mode 100644 index 000000000..5c7bf6ea5 --- /dev/null +++ b/types/providers/common-networks.d.ts @@ -0,0 +1,8 @@ +/** + * Exports the same Network as "./network.js" except with common + * networks injected registered. + */ +import { Network } from "./network.js"; +export declare function injectCommonNetworks(): void; +export { Network }; +//# sourceMappingURL=common-networks.d.ts.map \ No newline at end of file diff --git a/types/providers/common-networks.d.ts.map b/types/providers/common-networks.d.ts.map new file mode 100644 index 000000000..5d570157f --- /dev/null +++ b/types/providers/common-networks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common-networks.d.ts","sourceRoot":"","sources":["../../src.ts/providers/common-networks.ts"],"names":[],"mappings":"AACA;;;GAGG;AAKH,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAUvC,wBAAgB,oBAAoB,IAAI,IAAI,CA8E3C;AAID,OAAO,EAAE,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/types/providers/community.d.ts b/types/providers/community.d.ts new file mode 100644 index 000000000..edb14e7e5 --- /dev/null +++ b/types/providers/community.d.ts @@ -0,0 +1,5 @@ +export interface CommunityResourcable { + isCommunityResource(): boolean; +} +export declare function showThrottleMessage(service: string): void; +//# sourceMappingURL=community.d.ts.map \ No newline at end of file diff --git a/types/providers/community.d.ts.map b/types/providers/community.d.ts.map new file mode 100644 index 000000000..c39820fa7 --- /dev/null +++ b/types/providers/community.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"community.d.ts","sourceRoot":"","sources":["../../src.ts/providers/community.ts"],"names":[],"mappings":"AACA,MAAM,WAAW,oBAAoB;IACjC,mBAAmB,IAAI,OAAO,CAAC;CAClC;AAID,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,QAgBlD"} \ No newline at end of file diff --git a/types/providers/contracts.d.ts b/types/providers/contracts.d.ts new file mode 100644 index 000000000..1dd1ce5bf --- /dev/null +++ b/types/providers/contracts.d.ts @@ -0,0 +1,9 @@ +import type { CallRequest, Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +export interface ContractRunner { + provider: null | Provider; + estimateGas?: (tx: TransactionRequest) => Promise; + call?: (tx: CallRequest) => Promise; + resolveName?: (name: string) => Promise; + sendTransaction?: (tx: TransactionRequest) => Promise; +} +//# sourceMappingURL=contracts.d.ts.map \ No newline at end of file diff --git a/types/providers/contracts.d.ts.map b/types/providers/contracts.d.ts.map new file mode 100644 index 000000000..ad655cc6f --- /dev/null +++ b/types/providers/contracts.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src.ts/providers/contracts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,WAAW,EAAE,QAAQ,EAAE,kBAAkB,EAAE,mBAAmB,EACjE,MAAM,eAAe,CAAC;AAIvB,MAAM,WAAW,cAAc;IAC3B,QAAQ,EAAE,IAAI,GAAG,QAAQ,CAAC;IAG1B,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,kBAAkB,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAG1D,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAG5C,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;IAGvD,eAAe,CAAC,EAAE,CAAC,EAAE,EAAE,kBAAkB,KAAK,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC9E"} \ No newline at end of file diff --git a/types/providers/default-provider.d.ts b/types/providers/default-provider.d.ts new file mode 100644 index 000000000..657919cb1 --- /dev/null +++ b/types/providers/default-provider.d.ts @@ -0,0 +1,5 @@ +import type { AbstractProvider } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +import { WebSocketLike } from "./provider-websocket.js"; +export declare function getDefaultProvider(network: string | Networkish | WebSocketLike, options?: any): AbstractProvider; +//# sourceMappingURL=default-provider.d.ts.map \ No newline at end of file diff --git a/types/providers/default-provider.d.ts.map b/types/providers/default-provider.d.ts.map new file mode 100644 index 000000000..0453c5f6c --- /dev/null +++ b/types/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":"AAYA,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;AAOxD,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,aAAa,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,gBAAgB,CAmEhH"} \ No newline at end of file diff --git a/types/providers/ens-resolver.d.ts b/types/providers/ens-resolver.d.ts new file mode 100644 index 000000000..e4d658692 --- /dev/null +++ b/types/providers/ens-resolver.d.ts @@ -0,0 +1,39 @@ +import type { BytesLike } from "../utils/index.js"; +import type { AbstractProvider, ProviderPlugin } from "./abstract-provider.js"; +import type { Provider } from "./provider.js"; +export declare type AvatarLinkageType = "name" | "avatar" | "!avatar" | "url" | "data" | "ipfs" | "erc721" | "erc1155" | "!erc721-caip" | "!erc1155-caip" | "!owner" | "owner" | "!balance" | "balance" | "metadata-url-base" | "metadata-url-expanded" | "metadata-url" | "!metadata-url" | "!metadata" | "metadata" | "!imageUrl" | "imageUrl-ipfs" | "imageUrl" | "!imageUrl-ipfs"; +export interface AvatarLinkage { + type: AvatarLinkageType; + value: string; +} +export interface AvatarResult { + linkage: Array; + url: null | string; +} +export declare abstract class MulticoinProviderPlugin implements ProviderPlugin { + readonly name: string; + constructor(name: string); + validate(proivder: Provider): ProviderPlugin; + supportsCoinType(coinType: number): boolean; + encodeAddress(coinType: number, address: string): Promise; + decodeAddress(coinType: number, data: BytesLike): Promise; +} +export declare class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin { + constructor(); +} +export declare class EnsResolver { + #private; + provider: AbstractProvider; + address: string; + name: string; + constructor(provider: AbstractProvider, address: string, name: string); + supportsWildcard(): Promise; + _fetch(selector: string, parameters?: BytesLike): Promise; + getAddress(coinType?: number): Promise; + getText(key: string): Promise; + getContentHash(): Promise; + getAvatar(): Promise; + _getAvatar(): Promise; + static fromName(provider: AbstractProvider, name: string): Promise; +} +//# sourceMappingURL=ens-resolver.d.ts.map \ No newline at end of file diff --git a/types/providers/ens-resolver.d.ts.map b/types/providers/ens-resolver.d.ts.map new file mode 100644 index 000000000..28a7ca8dd --- /dev/null +++ b/types/providers/ens-resolver.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ens-resolver.d.ts","sourceRoot":"","sources":["../../src.ts/providers/ens-resolver.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAgB,SAAS,EAAe,MAAM,mBAAmB,CAAC;AAE9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE/E,OAAO,KAAK,EAAe,QAAQ,EAAE,MAAM,eAAe,CAAC;AAiF3D,oBAAY,iBAAiB,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GACnF,QAAQ,GAAG,SAAS,GAAG,cAAc,GAAG,eAAe,GACvD,QAAQ,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAC3C,mBAAmB,GAAG,uBAAuB,GAAG,cAAc,GAAG,eAAe,GAChF,WAAW,GAAG,UAAU,GACxB,WAAW,GAAG,eAAe,GAAG,UAAU,GAAG,gBAAgB,CAAC;AAElE,MAAM,WA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AO,CAAC,IAAI,GAAG,MAAM,CAAC;IAInC,UAAU,IAAI,OAAO,CAAC,YAAY,CAAC;WAoM5B,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,CAAC;CA2B/F"} \ No newline at end of file diff --git a/types/providers/formatter.d.ts b/types/providers/formatter.d.ts new file mode 100644 index 000000000..c6c77b2b2 --- /dev/null +++ b/types/providers/formatter.d.ts @@ -0,0 +1,36 @@ +import { Block, Log, TransactionReceipt, TransactionResponse } from "./provider.js"; +import type { AccessList } from "../transaction/index.js"; +import type { PerformActionTransaction } from "./abstract-provider.js"; +import type { Filter, Provider } from "./provider.js"; +export declare type FormatFunc = (value: any) => any; +export declare class Formatter { + #private; + constructor(); + address(value: any): string; + callAddress(value: any): string; + contractAddress(value: any): string; + blockTag(value?: any): string; + block(value: any, provider?: Provider): Block; + blockWithTransactions(value: any, provider?: Provider): Block; + transactionRequest(value: any, provider?: Provider): PerformActionTransaction; + transactionResponse(value: any, provider?: Provider): TransactionResponse; + log(value: any, provider?: Provider): Log; + receipt(value: any, provider?: Provider): TransactionReceipt; + topics(value: any): Array; + filter(value: any): Filter; + filterLog(value: any): any; + transaction(value: any): TransactionResponse; + accessList(value: any): AccessList; + allowFalsish(format: FormatFunc, ifFalse: any): FormatFunc; + allowNull(format: FormatFunc, ifNull?: any): FormatFunc; + arrayOf(format: FormatFunc): FormatFunc; + bigNumber(value: any): bigint; + uint256(value: any): bigint; + boolean(value: any): boolean; + _hexstring(dataOrLength?: boolean | number): FormatFunc; + data(value: string): string; + hash(value: any): string; + number(value: any): number; + object(format: Record, altNames?: Record>): FormatFunc; +} +//# sourceMappingURL=formatter.d.ts.map \ No newline at end of file diff --git a/types/providers/formatter.d.ts.map b/types/providers/formatter.d.ts.map new file mode 100644 index 000000000..683be67b3 --- /dev/null +++ b/types/providers/formatter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"formatter.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C,MAAM,CAAC;IAIjC,MAAM,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;IAI1B,SAAS,CAAC,KAAK,EAAE,GAAG,GAAG,GAAG;IAM1B,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,mBAAmB;IAQ5C,UAAU,CAAC,KAAK,EAAE,GAAG,GAAG,UAAU;IAKlC,YAAY,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,GAAG,UAAU;IAQ1D,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,GAAG,GAAG,UAAU;IAQvD,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU;IAQvC,SAAS,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;IAI7B,OAAO,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;IAS3B,OAAO,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO;IAa5B,UAAU,CAAC,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,UAAU;IAUvD,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAQ3B,IAAI,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;IAQxB,MAAM,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;IAO1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,UAAU;CAyBnG"} \ No newline at end of file diff --git a/types/providers/index.d.ts b/types/providers/index.d.ts new file mode 100644 index 000000000..e7cc76c33 --- /dev/null +++ b/types/providers/index.d.ts @@ -0,0 +1,23 @@ +export { AbstractSigner, VoidSigner, WrappedSigner } from "./abstract-signer.js"; +export { Formatter } from "./formatter.js"; +export { Network } from "./common-networks.js"; +export { NetworkPlugin, GasCostPlugin, EnsPlugin, } from "./plugins-network.js"; +export { Block, FeeData, Log, TransactionReceipt, TransactionResponse, dummyProvider, copyRequest, } from "./provider.js"; +export { FallbackProvider } from "./provider-fallback.js"; +export { JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner } from "./provider-jsonrpc.js"; +export { AlchemyProvider } from "./provider-alchemy.js"; +export { AnkrProvider } from "./provider-ankr.js"; +export { CloudflareProvider } from "./provider-cloudflare.js"; +export { EtherscanProvider } from "./provider-etherscan.js"; +export { InfuraProvider } from "./provider-infura.js"; +import { IpcSocketProvider } from "./provider-ipcsocket.js"; +export { IpcSocketProvider }; +export { SocketProvider } from "./provider-socket.js"; +export { WebSocketProvider } from "./provider-websocket.js"; +export type { ContractRunner } from "./contracts.js"; +export type { FormatFunc } from "./formatter.js"; +export type { Networkish } from "./network.js"; +export type { GasCostParameters } from "./plugins-network.js"; +export type { BlockTag, CallRequest, TransactionRequest, PreparedRequest, EventFilter, Filter, FilterByBlockHash, OrphanFilter, ProviderEvent, TopicFilter, Provider, } from "./provider.js"; +export type { Signer } from "./signer.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/providers/index.d.ts.map b/types/providers/index.d.ts.map new file mode 100644 index 000000000..b6d36c927 --- /dev/null +++ b/types/providers/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/providers/index.ts"],"names":[],"mappings":"AAMA,OAAO,EACH,cAAc,EACd,UAAU,EACV,aAAa,EAChB,MAAM,sBAAsB,CAAC;AAW9B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAE/C,OAAO,EACH,aAAa,EACb,aAAa,EACb,SAAS,GAIZ,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACH,KAAK,EACL,OAAO,EACP,GAAG,EACH,kBAAkB,EAClB,mBAAmB,EAEnB,aAAa,EAEb,WAAW,GAEd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE1F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAQ5D,YAAY,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAUrD,YAAY,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,YAAY,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,YAAY,EACR,QAAQ,EACR,WAAW,EAAE,kBAAkB,EAAE,eAAe,EAChD,WAAW,EAAE,MAAM,EAAE,iBAAiB,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAChF,QAAQ,GACX,MAAM,eAAe,CAAC;AAEvB,YAAY,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/types/providers/network.d.ts b/types/providers/network.d.ts new file mode 100644 index 000000000..188bb3380 --- /dev/null +++ b/types/providers/network.d.ts @@ -0,0 +1,40 @@ +import { Formatter } from "./formatter.js"; +import type { BigNumberish } from "../utils/index.js"; +import type { Freezable, Frozen } from "../utils/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { NetworkPlugin } from "./plugins-network.js"; +/** + * A Networkish can be used to allude to a Network, by specifing: + * - a [[Network]] object + * - a well-known (or registered) network name + * - a well-known (or registered) chain ID + * - an object with sufficient details to describe a network + */ +export declare type Networkish = Network | number | bigint | string | { + name?: string; + chainId?: number; + ensAddress?: string; + ensNetwork?: number; +}; +export declare class Network implements Freezable { + #private; + constructor(name: string, _chainId: BigNumberish, formatter?: Formatter); + toJSON(): any; + get name(): string; + set name(value: string); + get chainId(): bigint; + set chainId(value: BigNumberish); + get formatter(): Formatter; + set formatter(value: Formatter); + get plugins(): Array; + attachPlugin(plugin: NetworkPlugin): this; + getPlugin(name: string): null | T; + getPlugins(basename: string): Array; + clone(): Network; + freeze(): Frozen; + isFrozen(): boolean; + computeIntrinsicGas(tx: TransactionLike): number; + static from(network?: Networkish): Network; + static register(nameOrChainId: string | number | bigint, networkFunc: () => Network): void; +} +//# sourceMappingURL=network.d.ts.map \ No newline at end of file diff --git a/types/providers/network.d.ts.map b/types/providers/network.d.ts.map new file mode 100644 index 000000000..7544a1df3 --- /dev/null +++ b/types/providers/network.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"network.d.ts","sourceRoot":"","sources":["../../src.ts/providers/network.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;;;;;GAMG;AACH,oBAAY,UAAU,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG;IAC1D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,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+++ b/types/providers/pagination.d.ts @@ -0,0 +1,6 @@ +export interface PaginationResult extends Array { + next(): Promise>; + totalResults: null | number; + done: boolean; +} +//# sourceMappingURL=pagination.d.ts.map \ No newline at end of file diff --git a/types/providers/pagination.d.ts.map b/types/providers/pagination.d.ts.map new file mode 100644 index 000000000..083dedb30 --- /dev/null +++ b/types/providers/pagination.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src.ts/providers/pagination.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB,CAAC,CAAC,CAAE,SAAQ,KAAK,CAAC,CAAC,CAAC;IACjD,IAAI,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;IAGrC,YAAY,EAAE,IAAI,GAAG,MAAM,CAAC;IAE5B,IAAI,EAAE,OAAO,CAAC;CACjB"} \ No newline at end of file diff --git a/types/providers/plugins-network.d.ts b/types/providers/plugins-network.d.ts new file mode 100644 index 000000000..672f0641d --- /dev/null +++ b/types/providers/plugins-network.d.ts @@ -0,0 +1,42 @@ +import type { Network } from "./network.js"; +import type { FeeData, Provider } from "./provider.js"; +export declare class NetworkPlugin { + readonly name: string; + constructor(name: string); + clone(): NetworkPlugin; + validate(network: Network): NetworkPlugin; +} +export declare type GasCostParameters = { + txBase?: number; + txCreate?: number; + txDataZero?: number; + txDataNonzero?: number; + txAccessListStorageKey?: number; + txAccessListAddress?: number; +}; +export declare class GasCostPlugin extends NetworkPlugin { + readonly effectiveBlock: number; + readonly txBase: number; + readonly txCreate: number; + readonly txDataZero: number; + readonly txDataNonzero: number; + readonly txAccessListStorageKey: number; + readonly txAccessListAddress: number; + constructor(effectiveBlock?: number, costs?: GasCostParameters); + clone(): GasCostPlugin; +} +export declare class EnsPlugin extends NetworkPlugin { + readonly address: string; + readonly targetNetwork: number; + constructor(address?: null | string, targetNetwork?: null | number); + clone(): EnsPlugin; + validate(network: Network): this; +} +export declare class FeeDataNetworkPlugin extends NetworkPlugin { + #private; + get feeDataFunc(): (provider: Provider) => Promise; + constructor(feeDataFunc: (provider: Provider) => Promise); + getFeeData(provider: Provider): Promise; + clone(): FeeDataNetworkPlugin; +} +//# sourceMappingURL=plugins-network.d.ts.map \ No newline at end of file diff --git a/types/providers/plugins-network.d.ts.map b/types/providers/plugins-network.d.ts.map new file mode 100644 index 000000000..9ec21fe73 --- /dev/null +++ b/types/providers/plugins-network.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"plugins-network.d.ts","sourceRoot":"","sources":["../../src.ts/providers/plugins-network.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAKvD,qBAAa,aAAa;IACtB,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;gBAEX,IAAI,EAAE,MAAM;IAIxB,KAAK,IAAI,aAAa;IAItB,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,aAAa;CAG5C;AAKD,oBAAY,iBAAiB,GAAG;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,qBAAa,aAAc,SAAQ,aAAa;IAC5C,QAAQ,CAAC,cAAc,EAAG,MAAM,CAAC;IAEjC,QAAQ,CAAC,MAAM,EAAG,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAG,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAG,MAAM,CAAC;IAC7B,QAAQ,CAAC,aAAa,EAAG,MAAM,CAAC;IAChC,QAAQ,CAAC,sBAAsB,EAAG,MAAM,CAAC;IACzC,QAAQ,CAAC,mBAAmB,EAAG,MAAM,CAAC;gBAE1B,cAAc,GAAE,MAAU,EAAE,KAAK,CAAC,EAAE,iBAAiB;IAuBjE,KAAK,IAAI,aAAa;CAGzB;AAID,qBAAa,SAAU,SAAQ,aAAa;IAGxC,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;IAG1B,QAAQ,CAAC,aAAa,EAAG,MAAM,CAAC;gBAEpB,OAAO,CAAC,EAAE,IAAI,GAAG,MAAM,EAAE,aAAa,CAAC,EAAE,IAAI,GAAG,MAAM;IAQlE,KAAK,IAAI,SAAS;IAIlB,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;CAInC;AAqBD,qBAAa,oBAAqB,SAAQ,aAAa;;IAGnD,IAAI,WAAW,IAAI,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC,OAAO,CAAC,CAA8B;gBAE7E,WAAW,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC,OAAO,CAAC;IAK3D,UAAU,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;IAItD,KAAK,IAAI,oBAAoB;CAGhC"} \ No newline at end of file diff --git a/types/providers/provider-alchemy.d.ts b/types/providers/provider-alchemy.d.ts new file mode 100644 index 000000000..a559923a4 --- /dev/null +++ b/types/providers/provider-alchemy.d.ts @@ -0,0 +1,15 @@ +import { FetchRequest } from "../utils/fetch.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import type { AbstractProvider, PerformActionRequest } from "./abstract-provider.js"; +import type { CommunityResourcable } from "./community.js"; +import type { Networkish } from "./network.js"; +export declare class AlchemyProvider extends JsonRpcProvider implements CommunityResourcable { + readonly apiKey: string; + constructor(_network?: Networkish, apiKey?: null | string); + _getProvider(chainId: number): AbstractProvider; + _perform(req: PerformActionRequest): Promise; + isCommunityResource(): boolean; + static getRequest(network: Network, apiKey?: string): FetchRequest; +} +//# sourceMappingURL=provider-alchemy.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-alchemy.d.ts.map b/types/providers/provider-alchemy.d.ts.map new file mode 100644 index 000000000..22fb2c1ea --- /dev/null +++ b/types/providers/provider-alchemy.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-alchemy.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-alchemy.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAkC/C,qBAAa,eAAgB,SAAQ,eAAgB,YAAW,oBAAoB;IAChF,QAAQ,CAAC,MAAM,EAAG,MAAM,CAAC;gBAEb,QAAQ,GAAE,UAAwB,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,MAAM;IAUtE,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,gBAAgB;IAOzC,QAAQ,CAAC,GAAG,EAAE,oBAAoB,GAAG,OAAO,CAAC,GAAG,CAAC;IA6BvD,mBAAmB,IAAI,OAAO;IAI9B,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,YAAY;CAerE"} \ No newline at end of file diff --git a/types/providers/provider-ankr.d.ts b/types/providers/provider-ankr.d.ts new file mode 100644 index 000000000..1e98e6692 --- /dev/null +++ b/types/providers/provider-ankr.d.ts @@ -0,0 +1,14 @@ +import { FetchRequest } from "../utils/fetch.js"; +import { AbstractProvider } from "./abstract-provider.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import type { CommunityResourcable } from "./community.js"; +import type { Networkish } from "./network.js"; +export declare class AnkrProvider extends JsonRpcProvider implements CommunityResourcable { + readonly apiKey: string; + constructor(_network?: Networkish, apiKey?: null | string); + _getProvider(chainId: number): AbstractProvider; + static getRequest(network: Network, apiKey?: null | string): FetchRequest; + isCommunityResource(): boolean; +} +//# sourceMappingURL=provider-ankr.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-ankr.d.ts.map b/types/providers/provider-ankr.d.ts.map new file mode 100644 index 000000000..a9da6d89f --- /dev/null +++ b/types/providers/provider-ankr.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ankr.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-ankr.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG1D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAwB/C,qBAAa,YAAa,SAAQ,eAAgB,YAAW,oBAAoB;IAC7E,QAAQ,CAAC,MAAM,EAAG,MAAM,CAAC;gBAEb,QAAQ,GAAE,UAAwB,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,MAAM;IAatE,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,gBAAgB;IAO/C,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,YAAY;IAgBzE,mBAAmB,IAAI,OAAO;CAGjC"} \ No newline at end of file diff --git a/types/providers/provider-cloudflare.d.ts b/types/providers/provider-cloudflare.d.ts new file mode 100644 index 000000000..e27d4d2d1 --- /dev/null +++ b/types/providers/provider-cloudflare.d.ts @@ -0,0 +1,6 @@ +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import type { Networkish } from "./network.js"; +export declare class CloudflareProvider extends JsonRpcProvider { + constructor(_network?: Networkish); +} +//# sourceMappingURL=provider-cloudflare.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-cloudflare.d.ts.map b/types/providers/provider-cloudflare.d.ts.map new file mode 100644 index 000000000..436c553fb --- /dev/null +++ b/types/providers/provider-cloudflare.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-cloudflare.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-cloudflare.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG/C,qBAAa,kBAAmB,SAAQ,eAAe;gBACvC,QAAQ,GAAE,UAAwB;CAOjD"} \ No newline at end of file diff --git a/types/providers/provider-etherscan.d.ts b/types/providers/provider-etherscan.d.ts new file mode 100644 index 000000000..a84e02b2e --- /dev/null +++ b/types/providers/provider-etherscan.d.ts @@ -0,0 +1,31 @@ +import { AbstractProvider } from "./abstract-provider.js"; +import { Network } from "./network.js"; +import { NetworkPlugin } from "./plugins-network.js"; +import { PerformActionRequest } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +import type { TransactionRequest } from "./provider.js"; +export declare class EtherscanPlugin extends NetworkPlugin { + readonly baseUrl: string; + readonly communityApiKey: string; + constructor(baseUrl: string, communityApiKey: string); + clone(): EtherscanPlugin; +} +export declare class EtherscanProvider extends AbstractProvider { + readonly network: Network; + readonly apiKey: string; + constructor(_network?: Networkish, apiKey?: string); + getBaseUrl(): string; + getUrl(module: string, params: Record): string; + getPostUrl(): string; + getPostData(module: string, params: Record): Record; + detectNetwork(): Promise; + fetch(module: string, params: Record, post?: boolean): Promise; + _getTransactionPostData(transaction: TransactionRequest): Record; + _checkError(req: PerformActionRequest, error: Error, transaction: any): never; + _detectNetwork(): Promise; + _perform(req: PerformActionRequest): Promise; + getNetwork(): Promise; + getEtherPrice(): Promise; + isCommunityResource(): boolean; +} +//# sourceMappingURL=provider-etherscan.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-etherscan.d.ts.map b/types/providers/provider-etherscan.d.ts.map new file mode 100644 index 000000000..850d19863 --- /dev/null +++ b/types/providers/provider-etherscan.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-etherscan.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-etherscan.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAUxD,qBAAa,eAAgB,SAAQ,aAAa;IAC9C,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;IAC1B,QAAQ,CAAC,eAAe,EAAG,MAAM,CAAC;gBAEtB,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM;IAMpD,KAAK,IAAI,eAAe;CAG3B;AAGD,qBAAa,iBAAkB,SAAQ,gBAAgB;IACnD,QAAQ,CAAC,OAAO,EAAG,OAAO,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAG,MAAM,CAAC;gBAEb,QAAQ,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,MAAM;IAmBlD,UAAU,IAAI,MAAM;IAqBpB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM;IAY9D,UAAU,IAAI,MAAM;IAIpB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAMvE,aAAa,IAAI,OAAO,CAAC,OAAO,CAAC;IAIjC,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC;IA2FtF,uBAAuB,CAAC,WAAW,EAAE,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAuBhF,WAAW,CAAC,GAAG,EAAE,oBAAoB,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,GAAG,KAAK;IAuEvE,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC;IAIlC,QAAQ,CAAC,GAAG,EAAE,oBAAoB,GAAG,OAAO,CAAC,GAAG,CAAC;IAiKjD,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC;IAI9B,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAKtC,mBAAmB,IAAI,OAAO;CAMjC"} \ No newline at end of file diff --git a/types/providers/provider-fallback.d.ts b/types/providers/provider-fallback.d.ts new file mode 100644 index 000000000..18e094f5e --- /dev/null +++ b/types/providers/provider-fallback.d.ts @@ -0,0 +1,49 @@ +import { AbstractProvider } from "./abstract-provider.js"; +import { Network } from "./network.js"; +import type { PerformActionRequest } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +export interface FallbackProviderConfig { + provider: AbstractProvider; + stallTimeout?: number; + priority?: number; + weight?: number; +} +export interface FallbackProviderState extends Required { + blockNumber: number; + requests: number; + errorResponses: number; + lateResponses: number; + outOfSync: number; + unsupportedEvents: number; + rollingDuration: number; + score: number; +} +export declare type FallbackProviderOptions = { + quorum: number; + eventQuorum: number; + eventWorkers: number; +}; +export declare class FallbackProvider extends AbstractProvider { + #private; + readonly quorum: number; + readonly eventQuorum: number; + readonly eventWorkers: number; + constructor(providers: Array, network?: Networkish); + get providerConfigs(): Array; + _detectNetwork(): Promise any; + name: string; + chainId: bigint; + formatter: Readonly; + readonly plugins: readonly import("./plugins-network.js").NetworkPlugin[]; + attachPlugin: (plugin: import("./plugins-network.js").NetworkPlugin) => Network; + getPlugin: (name: string) => T | null; + getPlugins: (basename: string) => T_1[]; + clone: () => Network; + freeze: () => Readonly; + isFrozen: () => boolean; + computeIntrinsicGas: (tx: import("../ethers.js").TransactionLike) => number; + }>>; + _perform(req: PerformActionRequest): Promise; +} +//# sourceMappingURL=provider-fallback.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-fallback.d.ts.map b/types/providers/provider-fallback.d.ts.map new file mode 100644 index 000000000..8e2fdef0d --- /dev/null +++ b/types/providers/provider-fallback.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-fallback.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-fallback.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAItC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAqB9C,MAAM,WAAW,sBAAsB;IAGnC,QAAQ,EAAE,gBAAgB,CAAC;IAI3B,YAAY,CAAC,EAAE,MAAM,CAAC;IAGtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAGlB,MAAM,CAAC,EAAE,MAAM,CAAC;CACnB;AAMD,MAAM,WAAW,qBAAsB,SAAQ,QAAQ,CAAC,sBAAsB,CAAC;IAG3E,WAAW,EAAE,MAAM,CAAC;IAGpB,QAAQ,EAAE,MAAM,CAAC;IAGjB,cAAc,EAAE,MAAM,CAAC;IAGvB,aAAa,EAAE,MAAM,CAAC;IAGtB,SAAS,EAAE,MAAM,CAAC;IAGlB,iBAAiB,EAAE,MAAM,CAAC;IAG1B,eAAe,EAAE,MAAM,CAAC;IAGxB,KAAK,EAAE,MAAM,CAAC;CACjB;AA+BD,oBAAY,uBAAuB,GAAG;IAGlC,MAAM,EAAE,MAAM,CAAC;IAIf,WAAW,EAAE,MAAM,CAAC;IAKpB,YAAY,EAAE,MAAM,CAAC;CACxB,CAAC;AAsIF,qBAAa,gBAAiB,SAAQ,gBAAgB;;IAGlD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;gBAOlB,SAAS,EAAE,KAAK,CAAC,gBAAgB,GAAG,sBAAsB,CAAC,EAAE,OAAO,CAAC,EAAE,UAAU;IAuB7F,IAAI,eAAe,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAElD;IAEK,cAAc;;;;;;;;;;;;;;IAwPd,QAAQ,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,oBAAoB,GAAG,OAAO,CAAC,CAAC,CAAC;CAajE"} \ No newline at end of file diff --git a/types/providers/provider-infura.d.ts b/types/providers/provider-infura.d.ts new file mode 100644 index 000000000..483ed10f6 --- /dev/null +++ b/types/providers/provider-infura.d.ts @@ -0,0 +1,15 @@ +import { FetchRequest } from "../utils/fetch.js"; +import { Network } from "./network.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import type { AbstractProvider } from "./abstract-provider.js"; +import type { CommunityResourcable } from "./community.js"; +import type { Networkish } from "./network.js"; +export declare class InfuraProvider extends JsonRpcProvider implements CommunityResourcable { + readonly projectId: string; + readonly projectSecret: null | string; + constructor(_network?: Networkish, projectId?: null | string, projectSecret?: null | string); + _getProvider(chainId: number): AbstractProvider; + static getRequest(network: Network, projectId?: null | string, projectSecret?: null | string): FetchRequest; + isCommunityResource(): boolean; +} +//# sourceMappingURL=provider-infura.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-infura.d.ts.map b/types/providers/provider-infura.d.ts.map new file mode 100644 index 000000000..688e9c34d --- /dev/null +++ b/types/providers/provider-infura.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-infura.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-infura.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAmC/C,qBAAa,cAAe,SAAQ,eAAgB,YAAW,oBAAoB;IAC/E,QAAQ,CAAC,SAAS,EAAG,MAAM,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAG,IAAI,GAAG,MAAM,CAAC;gBAE3B,QAAQ,GAAE,UAAwB,EAAE,SAAS,CAAC,EAAE,IAAI,GAAG,MAAM,EAAE,aAAa,CAAC,EAAE,IAAI,GAAG,MAAM;IAWxG,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,gBAAgB;IAO/C,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,IAAI,GAAG,MAAM,EAAE,aAAa,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,YAAY;IAkB3G,mBAAmB,IAAI,OAAO;CAGjC"} \ No newline at end of file diff --git a/types/providers/provider-ipcsocket-browser.d.ts b/types/providers/provider-ipcsocket-browser.d.ts new file mode 100644 index 000000000..6aae787dc --- /dev/null +++ b/types/providers/provider-ipcsocket-browser.d.ts @@ -0,0 +1,3 @@ +declare const IpcSocketProvider: undefined; +export { IpcSocketProvider }; +//# sourceMappingURL=provider-ipcsocket-browser.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-ipcsocket-browser.d.ts.map b/types/providers/provider-ipcsocket-browser.d.ts.map new file mode 100644 index 000000000..e49cd58d3 --- /dev/null +++ b/types/providers/provider-ipcsocket-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ipcsocket-browser.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-ipcsocket-browser.ts"],"names":[],"mappings":"AAAA,QAAA,MAAM,iBAAiB,WAAY,CAAC;AAEpC,OAAO,EAAE,iBAAiB,EAAE,CAAC"} \ No newline at end of file diff --git a/types/providers/provider-ipcsocket.d.ts b/types/providers/provider-ipcsocket.d.ts new file mode 100644 index 000000000..4817d3632 --- /dev/null +++ b/types/providers/provider-ipcsocket.d.ts @@ -0,0 +1,12 @@ +/// +import { SocketProvider } from "./provider-socket.js"; +import type { Socket } from "net"; +import type { Networkish } from "./network.js"; +export declare class IpcSocketProvider extends SocketProvider { + #private; + get socket(): Socket; + constructor(path: string, network?: Networkish); + stop(): void; + _write(message: string): Promise; +} +//# sourceMappingURL=provider-ipcsocket.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-ipcsocket.d.ts.map b/types/providers/provider-ipcsocket.d.ts.map new file mode 100644 index 000000000..91cd66557 --- /dev/null +++ b/types/providers/provider-ipcsocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-ipcsocket.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-ipcsocket.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAClC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAmB/C,qBAAa,iBAAkB,SAAQ,cAAc;;IAEjD,IAAI,MAAM,IAAI,MAAM,CAAyB;gBAEjC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,UAAU;IAuB9C,IAAI,IAAI,IAAI;IAKN,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAI/C"} \ No newline at end of file diff --git a/types/providers/provider-jsonrpc.d.ts b/types/providers/provider-jsonrpc.d.ts new file mode 100644 index 000000000..17fb85129 --- /dev/null +++ b/types/providers/provider-jsonrpc.d.ts @@ -0,0 +1,91 @@ +import { FetchRequest } from "../utils/fetch.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"; +export declare type JsonRpcPayload = { + id: number; + method: string; + params: Array | Record; + jsonrpc: "2.0"; +}; +export declare type JsonRpcResult = { + id: number; + result: any; +}; +export declare type JsonRpcError = { + id: number; + error: { + code: number; + message?: string; + data?: any; + }; +}; +export declare type JsonRpcOptions = { + polling?: boolean; + staticNetwork?: null | Network; + batchStallTime?: number; + batchMaxSize?: number; + batchMaxCount?: number; +}; +export interface JsonRpcTransactionRequest { + from?: string; + to?: string; + data?: string; + chainId?: string; + type?: string; + gas?: string; + gasPrice?: string; + maxFeePerGas?: string; + maxPriorityFeePerGas?: string; + nonce?: string; + value?: string; + 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; +} +export declare class JsonRpcApiProvider extends AbstractProvider { + #private; + constructor(network?: Networkish, options?: JsonRpcOptions); + _getOption(key: K): JsonRpcOptions[K]; + send(method: string, params: Array | Record): Promise; + _send(payload: JsonRpcPayload | Array): Promise>; + getSigner(address?: number | string): Promise; + _detectNetwork(): Promise; + _getSubscriber(sub: Subscription): Subscriber; + getRpcTransaction(tx: TransactionRequest): JsonRpcTransactionRequest; + getRpcRequest(req: PerformActionRequest): null | { + method: string; + args: Array; + }; + getRpcError(payload: JsonRpcPayload, error: JsonRpcError): Error; + _perform(req: PerformActionRequest): Promise; +} +export declare class JsonRpcProvider extends JsonRpcApiProvider { + #private; + constructor(url?: string | FetchRequest, network?: Networkish, options?: JsonRpcOptions); + _send(payload: JsonRpcPayload | Array): Promise>; + get pollingInterval(): number; + set pollingInterval(value: number); +} +//# sourceMappingURL=provider-jsonrpc.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-jsonrpc.d.ts.map b/types/providers/provider-jsonrpc.d.ts.map new file mode 100644 index 000000000..1af791a69 --- /dev/null +++ b/types/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":"AAOA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAOjD,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,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U,EAAE,OAAO,CAAC,EAAE,cAAc;IAajF,KAAK,CAAC,OAAO,EAAE,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IAc3F,IAAI,eAAe,IAAI,MAAM,CAAkC;IAC/D,IAAI,eAAe,CAAC,KAAK,EAAE,MAAM,EAQhC;CACJ"} \ No newline at end of file diff --git a/types/providers/provider-pocket.d.ts b/types/providers/provider-pocket.d.ts new file mode 100644 index 000000000..1104d8538 --- /dev/null +++ b/types/providers/provider-pocket.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=provider-pocket.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-pocket.d.ts.map b/types/providers/provider-pocket.d.ts.map new file mode 100644 index 000000000..42d9c0851 --- /dev/null +++ b/types/providers/provider-pocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-pocket.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-pocket.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/types/providers/provider-socket.d.ts b/types/providers/provider-socket.d.ts new file mode 100644 index 000000000..4bc3a1ad6 --- /dev/null +++ b/types/providers/provider-socket.d.ts @@ -0,0 +1,51 @@ +/** + * SocketProvider + * + * Generic long-lived socket provider. + * + * Sub-classing notes + * - a sub-class MUST call the `_start()` method once connected + * - a sub-class MUST override the `_write(string)` method + * - a sub-class MUST call `_processMessage(string)` for each message + */ +import { JsonRpcApiProvider } from "./provider-jsonrpc.js"; +import type { Subscriber, Subscription } from "./abstract-provider.js"; +import type { EventFilter } from "./provider.js"; +import type { JsonRpcError, JsonRpcPayload, JsonRpcResult } from "./provider-jsonrpc.js"; +import type { Networkish } from "./network.js"; +export declare class SocketSubscriber implements Subscriber { + #private; + get filter(): Array; + constructor(provider: SocketProvider, filter: Array); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; + _handleMessage(message: any): void; + _emit(provider: SocketProvider, message: any): Promise; +} +export declare class SocketBlockSubscriber extends SocketSubscriber { + constructor(provider: SocketProvider); + _emit(provider: SocketProvider, message: any): Promise; +} +export declare class SocketPendingSubscriber extends SocketSubscriber { + constructor(provider: SocketProvider); + _emit(provider: SocketProvider, message: any): Promise; +} +export declare class SocketEventSubscriber extends SocketSubscriber { + #private; + get logFilter(): EventFilter; + constructor(provider: SocketProvider, filter: EventFilter); + _emit(provider: SocketProvider, message: any): Promise; +} +export declare class SocketProvider extends JsonRpcApiProvider { + #private; + constructor(network?: Networkish); + _getSubscriber(sub: Subscription): Subscriber; + _register(filterId: number | string, subscriber: SocketSubscriber): void; + _send(payload: JsonRpcPayload | Array): Promise>; + _start(): Promise; + _processMessage(message: string): Promise; + _write(message: string): Promise; +} +//# sourceMappingURL=provider-socket.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-socket.d.ts.map b/types/providers/provider-socket.d.ts.map new file mode 100644 index 000000000..6fa9ddfa0 --- /dev/null +++ b/types/providers/provider-socket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-socket.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-socket.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACzF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAW/C,qBAAa,gBAAiB,YAAW,UAAU;;IAI/C,IAAI,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAqC;gBAOjD,QAAQ,EAAE,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC;IAQxD,KAAK,IAAI,IAAI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,CAAC,IAAI,CAAC;IAsC/C,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAG/C"} \ No newline at end of file diff --git a/types/providers/provider-websocket.d.ts b/types/providers/provider-websocket.d.ts new file mode 100644 index 000000000..20d77b897 --- /dev/null +++ b/types/providers/provider-websocket.d.ts @@ -0,0 +1,18 @@ +import { SocketProvider } from "./provider-socket.js"; +import type { Networkish } from "./network.js"; +export interface WebSocketLike { + onopen: null | ((...args: Array) => any); + onmessage: null | ((...args: Array) => any); + onerror: null | ((...args: Array) => any); + readyState: number; + send(payload: any): void; + close(code?: number, reason?: string): void; +} +export declare class WebSocketProvider extends SocketProvider { + #private; + url: string; + get websocket(): WebSocketLike; + constructor(url: string | WebSocketLike, network?: Networkish); + _write(message: string): Promise; +} +//# sourceMappingURL=provider-websocket.d.ts.map \ No newline at end of file diff --git a/types/providers/provider-websocket.d.ts.map b/types/providers/provider-websocket.d.ts.map new file mode 100644 index 000000000..d54ff3daf --- /dev/null +++ b/types/providers/provider-websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-websocket.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-websocket.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,WAAW,aAAa;IAC1B,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC;IAC9C,SAAS,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC;IACjD,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC;IAE/C,UAAU,EAAE,MAAM,CAAC;IAEnB,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI,CAAC;IACzB,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/C;AAED,qBAAa,iBAAkB,SAAQ,cAAc;;IACjD,GAAG,EAAG,MAAM,CAAC;IAGb,IAAI,SAAS,IAAI,aAAa,CAA4B;gBAE9C,GAAG,EAAE,MAAM,GAAG,aAAa,EAAE,OAAO,CAAC,EAAE,UAAU;IAiBvD,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAG/C"} \ No newline at end of file diff --git a/types/providers/provider.d.ts b/types/providers/provider.d.ts new file mode 100644 index 000000000..8cd091d2e --- /dev/null +++ b/types/providers/provider.d.ts @@ -0,0 +1,404 @@ +import type { AddressLike, NameResolver } from "../address/index.js"; +import type { BigNumberish, EventEmitterable, Frozen } 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"; +export declare type BlockTag = number | string; +export declare class FeeData { + readonly gasPrice: null | bigint; + readonly maxFeePerGas: null | bigint; + readonly maxPriorityFeePerGas: null | bigint; + constructor(gasPrice?: null | bigint, maxFeePerGas?: null | bigint, maxPriorityFeePerGas?: null | bigint); + toJSON(): any; +} +export interface TransactionRequest { + type?: null | number; + to?: null | AddressLike; + from?: null | AddressLike; + nonce?: null | number; + gasLimit?: null | BigNumberish; + gasPrice?: null | BigNumberish; + maxPriorityFeePerGas?: null | BigNumberish; + maxFeePerGas?: null | BigNumberish; + data?: null | string; + value?: null | BigNumberish; + chainId?: null | BigNumberish; + accessList?: null | AccessListish; + customData?: any; +} +export interface CallRequest extends TransactionRequest { + blockTag?: BlockTag; + enableCcipRead?: boolean; +} +export interface PreparedRequest { + type?: number; + to?: AddressLike; + from?: AddressLike; + nonce?: number; + gasLimit?: bigint; + gasPrice?: bigint; + maxPriorityFeePerGas?: bigint; + maxFeePerGas?: bigint; + data?: string; + value?: bigint; + chainId?: bigint; + accessList?: AccessList; + customData?: any; + blockTag?: BlockTag; + enableCcipRead?: boolean; +} +export declare function copyRequest(req: CallRequest): PreparedRequest; +export interface BlockParams { + hash?: null | string; + number: number; + timestamp: number; + parentHash: string; + nonce: string; + difficulty: bigint; + gasLimit: bigint; + gasUsed: bigint; + miner: string; + extraData: string; + baseFeePerGas: null | bigint; + transactions: ReadonlyArray; +} +export interface MinedBlock extends Block { + readonly number: number; + readonly hash: string; + readonly timestamp: number; + readonly date: Date; + readonly miner: string; +} +export interface LondonBlock extends Block { + readonly baseFeePerGas: bigint; +} +export declare class Block implements BlockParams, Iterable { + #private; + readonly provider: Provider; + readonly number: number; + readonly hash: null | string; + readonly timestamp: number; + readonly parentHash: string; + readonly nonce: string; + readonly difficulty: bigint; + readonly gasLimit: bigint; + readonly gasUsed: bigint; + readonly miner: string; + readonly extraData: string; + readonly baseFeePerGas: null | bigint; + constructor(block: BlockParams, provider?: null | Provider); + get transactions(): ReadonlyArray; + toJSON(): any; + [Symbol.iterator](): Iterator; + get length(): number; + get date(): null | Date; + getTransaction(index: number): Promise; + isMined(): this is MinedBlock; + isLondon(): this is LondonBlock; + orphanedEvent(): OrphanFilter; +} +export interface LogParams { + transactionHash: string; + blockHash: string; + blockNumber: number; + removed: boolean; + address: string; + data: string; + topics: ReadonlyArray; + index: number; + transactionIndex: number; +} +export declare class Log implements LogParams { + readonly provider: Provider; + readonly transactionHash: string; + readonly blockHash: string; + readonly blockNumber: number; + readonly removed: boolean; + readonly address: string; + readonly data: string; + readonly topics: ReadonlyArray; + readonly index: number; + readonly transactionIndex: number; + constructor(log: LogParams, provider?: null | Provider); + toJSON(): any; + getBlock(): Promise>; + getTransaction(): Promise; + getTransactionReceipt(): Promise; + removedEvent(): OrphanFilter; +} +export interface TransactionReceiptParams { + to: null | string; + from: string; + contractAddress: null | string; + hash: string; + index: number; + blockHash: string; + blockNumber: number; + logsBloom: string; + logs: ReadonlyArray; + gasUsed: bigint; + cumulativeGasUsed: bigint; + gasPrice?: null | bigint; + effectiveGasPrice?: null | bigint; + byzantium: boolean; + status: null | number; + root: null | string; +} +export interface LegacyTransactionReceipt { + byzantium: false; + status: null; + root: string; +} +export interface ByzantiumTransactionReceipt { + byzantium: true; + status: number; + root: null; +} +export declare class TransactionReceipt implements TransactionReceiptParams, Iterable { + #private; + readonly provider: Provider; + readonly to: null | string; + readonly from: string; + readonly contractAddress: null | string; + readonly hash: string; + readonly index: number; + readonly blockHash: string; + readonly blockNumber: number; + readonly logsBloom: string; + readonly gasUsed: bigint; + readonly cumulativeGasUsed: bigint; + readonly gasPrice: bigint; + readonly byzantium: boolean; + readonly status: null | number; + readonly root: null | string; + constructor(tx: TransactionReceiptParams, provider?: null | Provider); + get logs(): ReadonlyArray; + toJSON(): any; + get length(): number; + [Symbol.iterator](): Iterator; + get fee(): bigint; + getBlock(): Promise>; + getTransaction(): Promise; + confirmations(): Promise; + removedEvent(): OrphanFilter; + reorderedEvent(other?: TransactionResponse): OrphanFilter; +} +export interface TransactionResponseParams { + blockNumber: null | number; + blockHash: null | string; + hash: string; + index: number; + type: number; + to: null | string; + from: string; + nonce: number; + gasLimit: bigint; + gasPrice: bigint; + maxPriorityFeePerGas: null | bigint; + maxFeePerGas: null | bigint; + data: string; + value: bigint; + chainId: bigint; + signature: Signature; + accessList: null | AccessList; +} +export interface MinedTransactionResponse extends TransactionResponse { + blockNumber: number; + blockHash: string; + date: Date; +} +export interface LegacyTransactionResponse extends TransactionResponse { + accessList: null; + maxFeePerGas: null; + maxPriorityFeePerGas: null; +} +export interface BerlinTransactionResponse extends TransactionResponse { + accessList: AccessList; + maxFeePerGas: null; + maxPriorityFeePerGas: null; +} +export interface LondonTransactionResponse extends TransactionResponse { + accessList: AccessList; + maxFeePerGas: bigint; + maxPriorityFeePerGas: bigint; +} +export declare class TransactionResponse implements TransactionLike, TransactionResponseParams { + readonly provider: Provider; + readonly blockNumber: null | number; + readonly blockHash: null | string; + readonly index: number; + readonly hash: string; + readonly type: number; + readonly to: null | string; + readonly from: string; + readonly nonce: number; + readonly gasLimit: bigint; + readonly gasPrice: bigint; + readonly maxPriorityFeePerGas: null | bigint; + readonly maxFeePerGas: null | bigint; + readonly data: string; + readonly value: bigint; + readonly chainId: bigint; + readonly signature: Signature; + readonly accessList: null | AccessList; + constructor(tx: TransactionResponseParams, provider?: null | Provider); + toJSON(): any; + getBlock(): Promise>; + getTransaction(): Promise; + wait(confirms?: number): Promise; + isMined(): this is MinedTransactionResponse; + isLegacy(): this is LegacyTransactionResponse; + isBerlin(): this is BerlinTransactionResponse; + isLondon(): this is LondonTransactionResponse; + removedEvent(): OrphanFilter; + reorderedEvent(other?: TransactionResponse): OrphanFilter; +} +export declare 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; + }; +}; +export declare type TopicFilter = Array>; +export interface EventFilter { + address?: AddressLike | Array; + topics?: TopicFilter; +} +export interface Filter extends EventFilter { + fromBlock?: BlockTag; + toBlock?: BlockTag; +} +export interface FilterByBlockHash extends EventFilter { + blockHash?: string; +} +export declare type ProviderEvent = string | Array> | EventFilter | OrphanFilter; +export interface Provider extends ContractRunner, EventEmitterable, NameResolver { + provider: this; + /** + * Get the current block number. + */ + getBlockNumber(): Promise; + /** + * Get the connected [[Network]]. + */ + getNetwork(): Promise>; + /** + * Get the best guess at the recommended [[FeeData]]. + */ + getFeeData(): Promise; + /** + * Get the account balance (in wei) of %%address%%. If %%blockTag%% is specified and + * the node supports archive access, the balance is as of that [[BlockTag]]. + * + * @param {Address | Addressable} address - The account to lookup the balance of + * @param blockTag - The block tag to use for historic archive access. [default: ``"latest"``] + * + * @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, the transaction count is as of that [[BlockTag]]. + * + * @param {Address | Addressable} address - The account to lookup the transaction count of + * @param blockTag - The block tag to use for historic archive access. [default: ``"latest"``] + * + * @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//. + * + * @param {Address | Addressable} address - The account to lookup the bytecode of + * @param blockTag - The block tag to use for historic archive access. [default: ``"latest"``] + * + * @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 a given //address// and slot //position//. + * + * @param {Address | Addressable} address - The account to lookup the storage of + * @param position - The storage slot to fetch the value of + * @param blockTag - The block tag to use for historic archive access. [default: ``"latest"``] + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getStorageAt(address: AddressLike, position: BigNumberish, blockTag?: BlockTag): Promise; + /** + * Estimates the amount of gas required to executre %%tx%%. + * + * @param tx - The transaction to estimate the gas requirement for + */ + estimateGas(tx: TransactionRequest): Promise; + /** + * Uses call to simulate execution of %%tx%%. + * + * @param tx - The transaction to simulate + */ + call(tx: CallRequest): Promise; + /** + * Broadcasts the %%signedTx%% to the network, adding it to the memory pool + * of any node for which the transaction meets the rebroadcast requirements. + * + * @param signedTx - The transaction to broadcast + */ + broadcastTransaction(signedTx: string): Promise; + getBlock(blockHashOrBlockTag: BlockTag | string): Promise>; + getBlockWithTransactions(blockHashOrBlockTag: BlockTag | string): Promise>; + getTransaction(hash: string): Promise; + getTransactionReceipt(hash: string): Promise; + getLogs(filter: Filter | FilterByBlockHash): Promise>; + resolveName(name: string): Promise; + lookupAddress(address: string): Promise; + waitForTransaction(hash: string, confirms?: number, timeout?: number): Promise; + waitForBlock(blockTag?: BlockTag): Promise>; +} +/** + * A singleton [[Provider]] instance that can be used as a placeholder. This + * allows API that have a Provider added later to not require a null check. + * + * All operations performed on this [[Provider]] will throw. + */ +export declare const dummyProvider: Provider; +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/types/providers/provider.d.ts.map b/types/providers/provider.d.ts.map new file mode 100644 index 000000000..f8ffc16a4 --- /dev/null +++ b/types/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,EAAY,MAAM,mBAAmB,CAAC;AAC1F,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;AAG5C,oBAAY,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;AAevC,qBAAa,OAAO;IAChB,QAAQ,CAAC,QAAQ,EAAG,IAAI,GAAG,MAAM,CAAC;IAClC,QAAQ,CAAC,YAAY,EAAG,IAAI,GAAG,MAAM,CAAC;IACtC,QAAQ,CAAC,oB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ts new file mode 100644 index 000000000..32f0054a4 --- /dev/null +++ b/types/providers/signer.d.ts @@ -0,0 +1,118 @@ +import type { Addressable, NameResolver } from "../address/index.js"; +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { ContractRunner } from "./contracts.js"; +import type { BlockTag, CallRequest, Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +/** + * A Signer represents an account on the Ethereum Blockchain, and is most often + * backed by a private key represented by a mnemonic or residing on a Hardware Wallet. + * + * The API remains abstract though, so that it can deal with more advanced exotic + * Signing entities, such as Smart Contract Wallets or Virtual Wallets (where the + * private key may not be known). + */ +export interface Signer extends Addressable, ContractRunner, NameResolver { + /** + * The [[Provider]] attached to this Signer (if any). + */ + provider: null | Provider; + /** + * Returns a new instance of this Signer connected to //provider// or detached + * from any Provider if null. + */ + connect(provider: null | Provider): Signer; + /** + * Get the [[Address]] of the Signer. + */ + getAddress(): Promise; + /** + * Gets the next nonce required for this Signer to send a transaction. + * + * @param blockTag - The blocktag to base the transaction count on, keep in mind + * many nodes do not honour this value and silently ignore it [default: ``"latest"``] + */ + getNonce(blockTag?: BlockTag): Promise; + /** + * Prepares a {@link CallRequest} for calling: + * - resolves ``to`` and ``from`` addresses + * - if ``from`` is specified , check that it matches this Signer + * + * @param tx - The call to prepare + */ + populateCall(tx: CallRequest): Promise>; + /** + * Prepares a {@link TransactionRequest} for sending to the network by + * populating any missing properties: + * - resolves ``to`` and ``from`` addresses + * - if ``from`` is specified , check that it matches this Signer + * - populates ``nonce`` via ``signer.getNonce("pending")`` + * - populates ``gasLimit`` via ``signer.estimateGas(tx)`` + * - populates ``type`` and relevant fee data for that type (``gasPrice`` + * for legacy transactions, ``maxFeePerGas`` for EIP-1559, etc) + * + * @note Some Signer implementations may skip populating properties that + * are populated downstream; for example JsonRpcSigner defers to the + * node to populate the nonce and fee data. + * + * @param tx - The call to prepare + * @returns The fully prepared {@link TransactionLike} + */ + populateTransaction(tx: TransactionRequest): Promise>; + /** + * Estimates the required gas required to execute //tx// on the Blockchain. This + * will be the expected amount a transaction will require as its ``gasLimit`` + * to successfully run all the necessary computations and store the needed state + * that the transaction intends. + * + * Keep in mind that this is **best efforts**, since the state of the Blockchain + * is in flux, which could affect transaction gas requirements. + * + * @throws UNPREDICTABLE_GAS_LIMIT A transaction that is believed by the node to likely + * fail will throw an error during gas estimation. This could indicate that it + * will actually fail or that the circumstances are simply too complex for the + * node to take into account. In these cases, a manually determined ``gasLimit`` + * will need to be made. + */ + estimateGas(tx: CallRequest): Promise; + /** + * Evaluates the //tx// by running it against the current Blockchain state. This + * cannot change state and has no cost in ether, as it is effectively simulating + * execution. + * + * This can be used to have the Blockchain perform computations based on its state + * (e.g. running a Contract's getters) or to simulate the effect of a transaction + * before actually performing an operation. + */ + call(tx: CallRequest): Promise; + /** + * Resolves an [[Address]], ENS Name or [[Addressable]] to an [[Address]]. + */ + resolveName(name: string): Promise; + /** + * Signs %%tx%%, returning the fully signed transaction. This does not populate + * any additional properties within the transaction. + */ + signTransaction(tx: TransactionRequest): Promise; + /** + * Sends %%tx%% to the Network. The ``signer.populateTransaction(tx)`` is + * called first to ensure all necessary properties for the transaction to be + * valid have been popualted dirst. + */ + sendTransaction(tx: TransactionRequest): Promise; + /** + * Signers an [[EIP-191]] prefixed personal message. + * + * If the %%message%% is a string, it is signed as UTF-8 encoded bytes. It is **not** + * interpretted as a [[BytesLike]]; so the string ``"0x1234"`` is signed as six + * characters, **not** two bytes. + * + * To sign that example as two bytes, the Uint8Array should be used + * (i.e. ``new Uint8Array([ 0x12, 0x34 ])``). + */ + signMessage(message: string | Uint8Array): Promise; + /** + * Signs the [[EIP-712]] typed data. + */ + signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; +} +//# sourceMappingURL=signer.d.ts.map \ No newline at end of file diff --git a/types/providers/signer.d.ts.map b/types/providers/signer.d.ts.map new file mode 100644 index 000000000..01203b36d --- /dev/null +++ b/types/providers/signer.d.ts.map @@ -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,MAAM,CAAC,CAAC;IAEvC;;OAEG;IACH,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;IAMlD;;;OAGG;IACH,eAAe,CAAC,EAAE,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEzD;;;;OAIG;IACH,eAAe,CAAC,EAAE,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAEtE;;;;;;;;;OASG;IACH,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAE3D;;OAEG;IACH,aAAa,CAAC,MAAM,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,CAAC;CACrI"} \ No newline at end of file diff --git a/types/providers/subscriber-connection.d.ts b/types/providers/subscriber-connection.d.ts new file mode 100644 index 000000000..85d0483e5 --- /dev/null +++ b/types/providers/subscriber-connection.d.ts @@ -0,0 +1,15 @@ +import type { Subscriber } from "./abstract-provider.js"; +import type { Provider } from "./provider.js"; +export interface ConnectionRpcProvider extends Provider { + _subscribe(param: Array, processFunc: (result: any) => void): number; + _unsubscribe(filterId: number): void; +} +export declare class BlockConnectionSubscriber implements Subscriber { + #private; + constructor(provider: ConnectionRpcProvider); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +//# sourceMappingURL=subscriber-connection.d.ts.map \ No newline at end of file diff --git a/types/providers/subscriber-connection.d.ts.map b/types/providers/subscriber-connection.d.ts.map new file mode 100644 index 000000000..d6b42f162 --- /dev/null +++ b/types/providers/subscriber-connection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-connection.d.ts","sourceRoot":"","sources":["../../src.ts/providers/subscriber-connection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAKzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,MAAM,WAAW,qBAAsB,SAAQ,QAAQ;IAEnD,UAAU,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC;IAC1E,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACxC;AAED,qBAAa,yBAA0B,YAAW,UAAU;;gBAM5C,QAAQ,EAAE,qBAAqB;IAM3C,KAAK,IAAI,IAAI;IAWb,IAAI,IAAI,IAAI;IAOZ,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAKtC,MAAM,IAAI,IAAI;CAGjB"} \ No newline at end of file diff --git a/types/providers/subscriber-filterid.d.ts b/types/providers/subscriber-filterid.d.ts new file mode 100644 index 000000000..eaeda3ab4 --- /dev/null +++ b/types/providers/subscriber-filterid.d.ts @@ -0,0 +1,26 @@ +import type { AbstractProvider, Subscriber } from "./abstract-provider.js"; +import type { EventFilter } from "./provider.js"; +import type { JsonRpcApiProvider } from "./provider-jsonrpc.js"; +export declare class FilterIdSubscriber implements Subscriber { + #private; + constructor(provider: JsonRpcApiProvider); + _subscribe(provider: JsonRpcApiProvider): Promise; + _emitResults(provider: AbstractProvider, result: Array): Promise; + _recover(provider: AbstractProvider): Subscriber; + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +export declare class FilterIdEventSubscriber extends FilterIdSubscriber { + #private; + constructor(provider: JsonRpcApiProvider, filter: EventFilter); + _recover(provider: AbstractProvider): Subscriber; + _subscribe(provider: JsonRpcApiProvider): Promise; + _emitResults(provider: JsonRpcApiProvider, results: Array): Promise; +} +export declare class FilterIdPendingSubscriber extends FilterIdSubscriber { + _subscribe(provider: JsonRpcApiProvider): Promise; + _emitResults(provider: JsonRpcApiProvider, results: Array): Promise; +} +//# sourceMappingURL=subscriber-filterid.d.ts.map \ No newline at end of file diff --git a/types/providers/subscriber-filterid.d.ts.map b/types/providers/subscriber-filterid.d.ts.map new file mode 100644 index 000000000..4597f9ce8 --- /dev/null +++ b/types/providers/subscriber-filterid.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-filterid.d.ts","sourceRoot":"","sources":["../../src.ts/providers/subscriber-filterid.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAE3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAOhE,qBAAa,kBAAmB,YAAW,UAAU;;gBAQrC,QAAQ,EAAE,kBAAkB;IASxC,UAAU,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC;IAIzD,YAAY,CAAC,QAAQ,EAAE,gBAAgB,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3E,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,GAAG,UAAU;IAwChD,KAAK,IAAI,IAAI;IAEb,IAAI,IAAI,IAAI;IAKZ,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAKtC,MAAM,IAAI,IAAI;CACjB;AAED,qBAAa,uBAAwB,SAAQ,kBAAkB;;gBAG/C,QAAQ,EAAE,kBAAkB,EAAE,MAAM,EAAE,WAAW;IAK7D,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,GAAG,UAAU;IAI1C,UAAU,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC;IAMzD,YAAY,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAOvF;AAED,qBAAa,yBAA0B,SAAQ,kBAAkB;IACvD,UAAU,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC;IAIzD,YAAY,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAMvF"} \ No newline at end of file diff --git a/types/providers/subscriber-hotswap.d.ts b/types/providers/subscriber-hotswap.d.ts new file mode 100644 index 000000000..2474bb9d0 --- /dev/null +++ b/types/providers/subscriber-hotswap.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=subscriber-hotswap.d.ts.map \ No newline at end of file diff --git a/types/providers/subscriber-hotswap.d.ts.map b/types/providers/subscriber-hotswap.d.ts.map new file mode 100644 index 000000000..8b79d5954 --- /dev/null +++ b/types/providers/subscriber-hotswap.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-hotswap.d.ts","sourceRoot":"","sources":["../../src.ts/providers/subscriber-hotswap.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/types/providers/subscriber-polling.d.ts b/types/providers/subscriber-polling.d.ts new file mode 100644 index 000000000..68ab753e4 --- /dev/null +++ b/types/providers/subscriber-polling.d.ts @@ -0,0 +1,41 @@ +import type { AbstractProvider, Subscriber } from "./abstract-provider.js"; +import type { EventFilter, OrphanFilter, ProviderEvent } from "./provider.js"; +export declare function getPollingSubscriber(provider: AbstractProvider, event: ProviderEvent): Subscriber; +export declare class PollingBlockSubscriber implements Subscriber { + #private; + constructor(provider: AbstractProvider); + get pollingInterval(): number; + set pollingInterval(value: number); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +export declare class OnBlockSubscriber implements Subscriber { + #private; + constructor(provider: AbstractProvider); + _poll(blockNumber: number, provider: AbstractProvider): Promise; + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +export declare class PollingOrphanSubscriber extends OnBlockSubscriber { + #private; + constructor(provider: AbstractProvider, filter: OrphanFilter); + _poll(blockNumber: number, provider: AbstractProvider): Promise; +} +export declare class PollingTransactionSubscriber extends OnBlockSubscriber { + #private; + constructor(provider: AbstractProvider, hash: string); + _poll(blockNumber: number, provider: AbstractProvider): Promise; +} +export declare class PollingEventSubscriber implements Subscriber { + #private; + constructor(provider: AbstractProvider, filter: EventFilter); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +//# sourceMappingURL=subscriber-polling.d.ts.map \ No newline at end of file diff --git a/types/providers/subscriber-polling.d.ts.map b/types/providers/subscriber-polling.d.ts.map new file mode 100644 index 000000000..f232bf757 --- /dev/null +++ b/types/providers/subscriber-polling.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber-polling.d.ts","sourceRoot":"","sources":["../../src.ts/providers/subscriber-polling.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAC3E,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAO9E,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,KAAK,EAAE,aAAa,GAAG,UAAU,CAOjG;AAID,qBAAa,sBAAuB,YAAW,UAAU;;gBAUzC,QAAQ,EAAE,gBAAgB;IAQtC,IAAI,eAAe,IAAI,MAAM,CAA2B;IACxD,IAAI,eAAe,CAAC,KAAK,EAAE,MAAM,EAA6B;IAsB9D,KAAK,IAAI,IAAI;IAMb,IAAI,IAAI,IAAI;IAMZ,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAKtC,MAAM,IAAI,IAAI;CAGjB;AAED,qBAAa,iBAAkB,YAAW,UAAU;;gBAIpC,QAAQ,EAAE,gBAAgB;IAOhC,KAAK,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3E,KAAK,IAAI,IAAI;IAKb,IAAI,IAAI,IAAI;IAIZ,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IACtC,MAAM,IAAI,IAAI;CACjB;AAED,qBAAa,uBAAwB,SAAQ,iBAAiB;;gBAG9C,QAAQ,EAAE,gBAAgB,EAAE,MAAM,EAAE,YAAY;IAKtD,KAAK,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;CAI9E;AAED,qBAAa,4BAA6B,SAAQ,iBAAiB;;gBAGnD,QAAQ,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM;IAK9C,KAAK,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;CAI9E;AAED,qBAAa,sBAAuB,YAAW,UAAU;;gBASzC,QAAQ,EAAE,gBAAgB,EAAE,MAAM,EAAE,WAAW;IAgC3D,KAAK,IAAI,IAAI;IASb,IAAI,IAAI,IAAI;IAIZ,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAKtC,MAAM,IAAI,IAAI;CAGjB"} \ No newline at end of file diff --git a/types/providers/subscriber.d.ts b/types/providers/subscriber.d.ts new file mode 100644 index 000000000..32c83ea8e --- /dev/null +++ b/types/providers/subscriber.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=subscriber.d.ts.map \ No newline at end of file diff --git a/types/providers/subscriber.d.ts.map b/types/providers/subscriber.d.ts.map new file mode 100644 index 000000000..6b156e1d1 --- /dev/null +++ b/types/providers/subscriber.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"subscriber.d.ts","sourceRoot":"","sources":["../../src.ts/providers/subscriber.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/types/providers/ws-browser.d.ts b/types/providers/ws-browser.d.ts new file mode 100644 index 000000000..d92720422 --- /dev/null +++ b/types/providers/ws-browser.d.ts @@ -0,0 +1,3 @@ +declare const _WebSocket: any; +export { _WebSocket as WebSocket }; +//# sourceMappingURL=ws-browser.d.ts.map \ No newline at end of file diff --git a/types/providers/ws-browser.d.ts.map b/types/providers/ws-browser.d.ts.map new file mode 100644 index 000000000..f549c4b0c --- /dev/null +++ b/types/providers/ws-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ws-browser.d.ts","sourceRoot":"","sources":["../../src.ts/providers/ws-browser.ts"],"names":[],"mappings":"AAQA,QAAA,MAAM,UAAU,KAAwB,CAAC;AAEzC,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,CAAC"} \ No newline at end of file diff --git a/types/providers/ws.d.ts b/types/providers/ws.d.ts new file mode 100644 index 000000000..75d53b7d4 --- /dev/null +++ b/types/providers/ws.d.ts @@ -0,0 +1,2 @@ +export { WebSocket } from "ws"; +//# sourceMappingURL=ws.d.ts.map \ No newline at end of file diff --git a/types/providers/ws.d.ts.map b/types/providers/ws.d.ts.map new file mode 100644 index 000000000..c424f8d82 --- /dev/null +++ b/types/providers/ws.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../../src.ts/providers/ws.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC"} \ No newline at end of file diff --git a/types/transaction/accesslist.d.ts b/types/transaction/accesslist.d.ts new file mode 100644 index 000000000..886fc9df5 --- /dev/null +++ b/types/transaction/accesslist.d.ts @@ -0,0 +1,3 @@ +import type { AccessList, AccessListish } from "./index.js"; +export declare function accessListify(value: AccessListish): AccessList; +//# sourceMappingURL=accesslist.d.ts.map \ No newline at end of file diff --git a/types/transaction/accesslist.d.ts.map b/types/transaction/accesslist.d.ts.map new file mode 100644 index 000000000..575c34cbe --- /dev/null +++ b/types/transaction/accesslist.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"accesslist.d.ts","sourceRoot":"","sources":["../../src.ts/transaction/accesslist.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAgB5D,wBAAgB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,UAAU,CAuB9D"} \ No newline at end of file diff --git a/types/transaction/address.d.ts b/types/transaction/address.d.ts new file mode 100644 index 000000000..3417fd6c5 --- /dev/null +++ b/types/transaction/address.d.ts @@ -0,0 +1,5 @@ +import type { SignatureLike } from "../crypto/index.js"; +import type { BytesLike } from "../utils/index.js"; +export declare function computeAddress(key: string): string; +export declare function recoverAddress(digest: BytesLike, signature: SignatureLike): string; +//# sourceMappingURL=address.d.ts.map \ No newline at end of file diff --git a/types/transaction/address.d.ts.map b/types/transaction/address.d.ts.map new file mode 100644 index 000000000..482d33d89 --- /dev/null +++ b/types/transaction/address.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src.ts/transaction/address.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAGnD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAGlD;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,GAAG,MAAM,CAElF"} \ No newline at end of file diff --git a/types/transaction/index.d.ts b/types/transaction/index.d.ts new file mode 100644 index 000000000..1c41af6cd --- /dev/null +++ b/types/transaction/index.d.ts @@ -0,0 +1,11 @@ +export declare type AccessListSet = { + address: string; + storageKeys: Array; +}; +export declare type AccessList = Array; +export declare type AccessListish = AccessList | Array<[string, Array]> | Record>; +export { accessListify } from "./accesslist.js"; +export { computeAddress, recoverAddress } from "./address.js"; +export { Transaction } from "./transaction.js"; +export type { SignedTransaction, TransactionLike } from "./transaction.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/transaction/index.d.ts.map b/types/transaction/index.d.ts.map new file mode 100644 index 000000000..9d2ea6bd0 --- /dev/null +++ b/types/transaction/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/transaction/index.ts"],"names":[],"mappings":"AACA,oBAAY,aAAa,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC;AAC5E,oBAAY,UAAU,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC;AAG9C,oBAAY,aAAa,GAAG,UAAU,GACV,KAAK,CAAC,CAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAE,CAAC,GAChC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;AAG1D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC"} \ No newline at end of file diff --git a/types/transaction/transaction.d.ts b/types/transaction/transaction.d.ts new file mode 100644 index 000000000..226dba0a9 --- /dev/null +++ b/types/transaction/transaction.d.ts @@ -0,0 +1,86 @@ +import { Signature } from "../crypto/index.js"; +import type { BigNumberish, BytesLike, Freezable, Frozen } from "../utils/index.js"; +import type { SignatureLike } from "../crypto/index.js"; +import type { AccessList, AccessListish } from "./index.js"; +export interface TransactionLike { + type?: null | number; + to?: null | A; + from?: null | A; + nonce?: null | number; + gasLimit?: null | BigNumberish; + gasPrice?: null | BigNumberish; + maxPriorityFeePerGas?: null | BigNumberish; + maxFeePerGas?: null | BigNumberish; + data?: null | string; + value?: null | BigNumberish; + chainId?: null | BigNumberish; + hash?: null | string; + signature?: null | SignatureLike; + accessList?: null | AccessListish; +} +export interface SignedTransaction extends Transaction { + type: number; + typeName: string; + from: string; + signature: Signature; +} +export interface LegacyTransaction extends Transaction { + type: 0; + gasPrice: bigint; +} +export interface BerlinTransaction extends Transaction { + type: 1; + gasPrice: bigint; + accessList: AccessList; +} +export interface LondonTransaction extends Transaction { + type: 2; + maxFeePerGas: bigint; + maxPriorityFeePerGas: bigint; + accessList: AccessList; +} +export declare class Transaction implements Freezable, TransactionLike { + #private; + get type(): null | number; + get typeName(): null | string; + set type(value: null | number | string); + get to(): null | string; + set to(value: null | string); + get nonce(): number; + set nonce(value: BigNumberish); + get gasLimit(): bigint; + set gasLimit(value: BigNumberish); + get gasPrice(): null | bigint; + set gasPrice(value: null | BigNumberish); + get maxPriorityFeePerGas(): null | bigint; + set maxPriorityFeePerGas(value: null | BigNumberish); + get maxFeePerGas(): null | bigint; + set maxFeePerGas(value: null | BigNumberish); + get data(): string; + set data(value: BytesLike); + get value(): bigint; + set value(value: BigNumberish); + get chainId(): bigint; + set chainId(value: BigNumberish); + get signature(): null | Signature; + set signature(value: null | SignatureLike); + get accessList(): null | AccessList; + set accessList(value: null | AccessListish); + constructor(); + get hash(): null | string; + get unsignedHash(): string; + get from(): null | string; + get fromPublicKey(): null | string; + isSigned(): this is SignedTransaction; + get serialized(): string; + get unsignedSerialized(): string; + inferTypes(): Array; + isLegacy(): this is LegacyTransaction; + isBerlin(): this is BerlinTransaction; + isLondon(): this is LondonTransaction; + clone(): Transaction; + freeze(): Frozen; + isFrozen(): boolean; + static from(tx: string | TransactionLike): Transaction; +} +//# sourceMappingURL=transaction.d.ts.map \ No newline at end of file diff --git a/types/transaction/transaction.d.ts.map b/types/transaction/transaction.d.ts.map new file mode 100644 index 000000000..eda833289 --- /dev/null +++ b/types/transaction/transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["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100644 index 000000000..081e0c9f6 --- /dev/null +++ b/types/utils/base58.d.ts @@ -0,0 +1,10 @@ +import type { BytesLike } from "./index.js"; +/** + * Encode %%value%% as Base58-encoded data. + */ +export declare function encodeBase58(_value: BytesLike): string; +/** + * Decode the Base58-encoded %%value%%. + */ +export declare function decodeBase58(value: string): string; +//# sourceMappingURL=base58.d.ts.map \ No newline at end of file diff --git a/types/utils/base58.d.ts.map b/types/utils/base58.d.ts.map new file mode 100644 index 000000000..189a4c16a --- /dev/null +++ b/types/utils/base58.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base58.d.ts","sourceRoot":"","sources":["../../src.ts/utils/base58.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAwB5C;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAQtD;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOlD"} \ No newline at end of file diff --git a/types/utils/base64-browser.d.ts b/types/utils/base64-browser.d.ts new file mode 100644 index 000000000..ea96c442c --- /dev/null +++ b/types/utils/base64-browser.d.ts @@ -0,0 +1,4 @@ +import type { BytesLike } from "./data.js"; +export declare function decodeBase64(textData: string): Uint8Array; +export declare function encodeBase64(_data: BytesLike): string; +//# sourceMappingURL=base64-browser.d.ts.map \ No newline at end of file diff --git a/types/utils/base64-browser.d.ts.map b/types/utils/base64-browser.d.ts.map new file mode 100644 index 000000000..0adb8e7b6 --- /dev/null +++ b/types/utils/base64-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base64-browser.d.ts","sourceRoot":"","sources":["../../src.ts/utils/base64-browser.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG3C,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,CAOzD;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAOrD"} \ No newline at end of file diff --git a/types/utils/base64.d.ts b/types/utils/base64.d.ts new file mode 100644 index 000000000..9c0ab3e90 --- /dev/null +++ b/types/utils/base64.d.ts @@ -0,0 +1,4 @@ +import type { BytesLike } from "./data.js"; +export declare function decodeBase64(textData: string): Uint8Array; +export declare function encodeBase64(data: BytesLike): string; +//# sourceMappingURL=base64.d.ts.map \ No newline at end of file diff --git a/types/utils/base64.d.ts.map b/types/utils/base64.d.ts.map new file mode 100644 index 000000000..006c4b303 --- /dev/null +++ b/types/utils/base64.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../../src.ts/utils/base64.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG3C,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,CAEzD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAEpD"} \ No newline at end of file diff --git a/types/utils/data.d.ts b/types/utils/data.d.ts new file mode 100644 index 000000000..6ea8bf0ae --- /dev/null +++ b/types/utils/data.d.ts @@ -0,0 +1,11 @@ +export declare type BytesLike = string | Uint8Array; +export declare function isHexString(value: any, length?: number | boolean): value is string; +export declare function isBytesLike(value: any): value is BytesLike; +export declare function hexlify(data: BytesLike): string; +export declare function concat(datas: ReadonlyArray): string; +export declare function dataLength(data: BytesLike): number; +export declare function dataSlice(data: BytesLike, start?: number, end?: number): string; +export declare function stripZerosLeft(data: BytesLike): string; +export declare function zeroPadValue(data: BytesLike, length: number): string; +export declare function zeroPadBytes(data: BytesLike, length: number): string; +//# sourceMappingURL=data.d.ts.map \ No newline at end of file diff --git a/types/utils/data.d.ts.map b/types/utils/data.d.ts.map new file mode 100644 index 000000000..caac71c2a --- /dev/null +++ b/types/utils/data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../src.ts/utils/data.ts"],"names":[],"mappings":"AAEA,oBAAY,SAAS,GAAG,MAAM,GAAG,UAAU,CAAC;AAG5C,wBAAgB,WAAW,CAAC,KAAK,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,KAAK,IAAI,MAAM,CASlF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,SAAS,CAE1D;AAGD,wBAAgB,OAAO,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAS/C;AAED,wBAAgB,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,SAAS,CAAC,GAAG,MAAM,CAE9D;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAGlD;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAM/E;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAItD;AAwBD,wBAAgB,YAAY,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEpE;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEpE"} \ No newline at end of file diff --git a/types/utils/errors.d.ts b/types/utils/errors.d.ts new file mode 100644 index 000000000..90d9b1f45 --- /dev/null +++ b/types/utils/errors.d.ts @@ -0,0 +1,140 @@ +export declare type ErrorSignature = { + r: string; + s: string; + yParity: 0 | 1; + networkV: bigint; +}; +export declare type ErrorAccessList = Array<{ + address: string; + storageKeys: Array; +}>; +export interface ErrorFetchRequestWithBody extends ErrorFetchRequest { + body: Readonly; +} +export interface ErrorFetchRequest { + url: string; + method: string; + headers: Readonly>; + getHeader(key: string): string; + body: null | Readonly; + hasBody(): this is ErrorFetchRequestWithBody; +} +export interface ErrorFetchResponseWithBody extends ErrorFetchResponse { + body: Readonly; +} +export interface ErrorFetchResponse { + statusCode: number; + statusMessage: string; + headers: Readonly>; + getHeader(key: string): string; + body: null | Readonly; + hasBody(): this is ErrorFetchResponseWithBody; +} +export declare type ErrorCode = "UNKNOWN_ERROR" | "NOT_IMPLEMENTED" | "UNSUPPORTED_OPERATION" | "NETWORK_ERROR" | "SERVER_ERROR" | "TIMEOUT" | "BAD_DATA" | "CANCELLED" | "BUFFER_OVERRUN" | "NUMERIC_FAULT" | "INVALID_ARGUMENT" | "MISSING_ARGUMENT" | "UNEXPECTED_ARGUMENT" | "VALUE_MISMATCH" | "CALL_EXCEPTION" | "INSUFFICIENT_FUNDS" | "NONCE_EXPIRED" | "REPLACEMENT_UNDERPRICED" | "TRANSACTION_REPLACED" | "UNPREDICTABLE_GAS_LIMIT" | "UNCONFIGURED_NAME" | "OFFCHAIN_FAULT" | "ACTION_REJECTED"; +export interface EthersError extends Error { + code: ErrorCode; + info?: Record; + error?: Error; +} +export interface UnknownError extends EthersError<"UNKNOWN_ERROR"> { + [key: string]: any; +} +export interface NotImplementedError extends EthersError<"NOT_IMPLEMENTED"> { + operation: string; +} +export interface UnsupportedOperationError extends EthersError<"UNSUPPORTED_OPERATION"> { + operation: string; +} +export interface NetworkError extends EthersError<"NETWORK_ERROR"> { + event: string; +} +export interface ServerError extends EthersError<"SERVER_ERROR"> { + request: ErrorFetchRequest | string; + response?: ErrorFetchResponse; +} +export interface TimeoutError extends EthersError<"TIMEOUT"> { + operation: string; + reason: string; + request?: ErrorFetchRequest; +} +export interface BadDataError extends EthersError<"BAD_DATA"> { + value: any; +} +export interface CancelledError extends EthersError<"CANCELLED"> { +} +export interface BufferOverrunError extends EthersError<"BUFFER_OVERRUN"> { + buffer: Uint8Array; + length: number; + offset: number; +} +export interface NumericFaultError extends EthersError<"NUMERIC_FAULT"> { + operation: string; + fault: string; + value: any; +} +export interface InvalidArgumentError extends EthersError<"INVALID_ARGUMENT"> { + argument: string; + value: any; + info?: Record; +} +export interface MissingArgumentError extends EthersError<"MISSING_ARGUMENT"> { + count: number; + expectedCount: number; +} +export interface UnexpectedArgumentError extends EthersError<"UNEXPECTED_ARGUMENT"> { + count: number; + expectedCount: number; +} +export interface CallExceptionError extends EthersError<"CALL_EXCEPTION"> { + data: string; + transaction?: any; + method?: string; + signature?: string; + args?: ReadonlyArray; + errorSignature?: string; + errorName?: string; + errorArgs?: ReadonlyArray; + reason?: string; +} +export interface InsufficientFundsError extends EthersError<"INSUFFICIENT_FUNDS"> { + transaction: any; +} +export interface NonceExpiredError extends EthersError<"NONCE_EXPIRED"> { + transaction: any; +} +export interface OffchainFaultError extends EthersError<"OFFCHAIN_FAULT"> { + transaction?: any; + reason: string; +} +export interface ReplacementUnderpricedError extends EthersError<"REPLACEMENT_UNDERPRICED"> { + transaction: any; +} +export interface TransactionReplacedError extends EthersError<"TRANSACTION_REPLACED"> { + cancelled: boolean; + reason: "repriced" | "cancelled" | "replaced"; + hash: string; + replacement: any; + receipt: any; +} +export interface UnconfiguredNameError extends EthersError<"UNCONFIGURED_NAME"> { + value: string; +} +export interface UnpredictableGasLimitError extends EthersError<"UNPREDICTABLE_GAS_LIMIT"> { + transaction: any; +} +export interface ActionRejectedError extends EthersError<"ACTION_REJECTED"> { + action: string; +} +export declare type CodedEthersError = T extends "UNKNOWN_ERROR" ? UnknownError : T extends "NOT_IMPLEMENTED" ? NotImplementedError : T extends "UNSUPPORTED_OPERATION" ? UnsupportedOperationError : T extends "NETWORK_ERROR" ? NetworkError : T extends "SERVER_ERROR" ? ServerError : T extends "TIMEOUT" ? TimeoutError : T extends "BAD_DATA" ? BadDataError : T extends "CANCELLED" ? CancelledError : T extends "BUFFER_OVERRUN" ? BufferOverrunError : T extends "NUMERIC_FAULT" ? NumericFaultError : T extends "INVALID_ARGUMENT" ? InvalidArgumentError : T extends "MISSING_ARGUMENT" ? MissingArgumentError : T extends "UNEXPECTED_ARGUMENT" ? UnexpectedArgumentError : T extends "CALL_EXCEPTION" ? CallExceptionError : T extends "INSUFFICIENT_FUNDS" ? InsufficientFundsError : T extends "NONCE_EXPIRED" ? NonceExpiredError : T extends "OFFCHAIN_FAULT" ? OffchainFaultError : T extends "REPLACEMENT_UNDERPRICED" ? ReplacementUnderpricedError : T extends "TRANSACTION_REPLACED" ? TransactionReplacedError : T extends "UNCONFIGURED_NAME" ? UnconfiguredNameError : T extends "UNPREDICTABLE_GAS_LIMIT" ? UnpredictableGasLimitError : T extends "ACTION_REJECTED" ? ActionRejectedError : never; +/** + * try { + * // code.... + * } catch (e) { + * if (isError(e, errors.CALL_EXCEPTION)) { + * console.log(e.data); + * } + * } + */ +export declare function isError>(error: any, code: K): error is T; +export declare function isCallException(error: any): error is CallExceptionError; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/types/utils/errors.d.ts.map b/types/utils/errors.d.ts.map new file mode 100644 index 000000000..1f6b9d636 --- /dev/null +++ b/types/utils/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src.ts/utils/errors.ts"],"names":[],"mappings":"AAGA,oBAAY,cAAc,GAAG;IACzB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,oBAAY,eAAe,GAAG,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC,CAAC;AA6BrF,MAAM,WAAW,yBAA0B,SAAQ,iBAAiB;IAChE,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC;CAC9B;AAED,MAAM,WAAW,iBAAiB;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,QAAQ,CAAC,MAAM,C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AS,sBAAsB,GAAG,wBAAwB,GAC3D,CAAC,SAAS,mBAAmB,GAAG,qBAAqB,GACrD,CAAC,SAAS,yBAAyB,GAAG,0BAA0B,GAEhE,CAAC,SAAS,iBAAiB,GAAG,mBAAmB,GAEjD,KAAK,CAAC;AAEV;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,gBAAgB,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,GAAG,KAAK,IAAI,CAAC,CAE3G;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,kBAAkB,CAEvE"} \ No newline at end of file diff --git a/types/utils/events.d.ts b/types/utils/events.d.ts new file mode 100644 index 000000000..bac52a9ab --- /dev/null +++ b/types/utils/events.d.ts @@ -0,0 +1,20 @@ +export declare type Listener = (...args: Array) => void; +export interface EventEmitterable { + on(event: T, listener: Listener): Promise; + once(event: T, listener: Listener): Promise; + emit(event: T, ...args: Array): Promise; + listenerCount(event?: T): Promise; + listeners(event?: T): Promise>; + off(event: T, listener?: Listener): Promise; + removeAllListeners(event?: T): Promise; + addListener(event: T, listener: Listener): Promise; + removeListener(event: T, listener: Listener): Promise; +} +export declare class EventPayload { + #private; + readonly filter: T; + readonly emitter: EventEmitterable; + constructor(emitter: EventEmitterable, listener: null | Listener, filter: T); + removeListener(): Promise; +} +//# sourceMappingURL=events.d.ts.map \ No newline at end of file diff --git a/types/utils/events.d.ts.map b/types/utils/events.d.ts.map new file mode 100644 index 000000000..816f420e1 --- /dev/null +++ b/types/utils/events.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src.ts/utils/events.ts"],"names":[],"mappings":"AAEA,oBAAY,QAAQ,GAAG,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC;AAErD,MAAM,WAAW,gBAAgB,CA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ts b/types/utils/fetch.d.ts new file mode 100644 index 000000000..8f8cb68e0 --- /dev/null +++ b/types/utils/fetch.d.ts @@ -0,0 +1,105 @@ +export declare type GetUrlResponse = { + statusCode: number; + statusMessage: string; + headers: Record; + body: null | Uint8Array; +}; +export interface FetchRequestWithBody extends FetchRequest { + body: Uint8Array; +} +/** + * Called before any network request, allowing updated headers (e.g. Bearer tokens), etc. + */ +export declare type FetchPreflightFunc = (request: FetchRequest) => Promise; +/** + * Called on the response, allowing client-based throttling logic or post-processing. + */ +export declare type FetchProcessFunc = (request: FetchRequest, response: FetchResponse) => Promise; +/** + * Called prior to each retry; return true to retry, false to abort. + */ +export declare type FetchRetryFunc = (request: FetchRequest, response: FetchResponse, attempt: number) => Promise; +/** + * Called on Gateway URLs. + */ +export declare type FetchGatewayFunc = (url: string, signal?: FetchCancelSignal) => Promise; +/** + * Used to perform a fetch; use this to override the underlying network + * fetch layer. In NodeJS, the default uses the "http" and "https" libraries + * and in the browser ``fetch`` is used. If you wish to use Axios, this is + * how you would register it. + */ +export declare type FetchGetUrlFunc = (request: FetchRequest, signal?: FetchCancelSignal) => Promise; +export declare function getIpfsGatewayFunc(base: string): FetchGatewayFunc; +export declare class FetchCancelSignal { + #private; + constructor(request: FetchRequest); + addListener(listener: () => void): void; + get cancelled(): boolean; + checkSignal(): void; +} +export declare class FetchRequest implements Iterable<[key: string, value: string]> { + #private; + get url(): string; + set url(url: string); + get body(): null | Uint8Array; + set body(body: null | string | Readonly | Readonly); + hasBody(): this is FetchRequestWithBody; + get method(): string; + set method(method: null | string); + get headers(): Readonly>; + getHeader(key: string): string; + setHeader(key: string, value: string | number): void; + clearHeaders(): void; + [Symbol.iterator](): Iterator<[key: string, value: string]>; + get credentials(): null | string; + setCredentials(username: string, password: string): void; + get allowGzip(): boolean; + set allowGzip(value: boolean); + get allowInsecureAuthentication(): boolean; + set allowInsecureAuthentication(value: boolean); + get timeout(): number; + set timeout(timeout: number); + get preflightFunc(): null | FetchPreflightFunc; + set preflightFunc(preflight: null | FetchPreflightFunc); + get processFunc(): null | FetchProcessFunc; + set processFunc(process: null | FetchProcessFunc); + get retryFunc(): null | FetchRetryFunc; + set retryFunc(retry: null | FetchRetryFunc); + constructor(url: string); + send(): Promise; + cancel(): void; + /** + * Returns a new [[FetchRequest]] that represents the redirection + * to %%location%%. + */ + redirect(location: string): FetchRequest; + clone(): FetchRequest; + static lockConfig(): void; + static getGateway(scheme: string): null | FetchGatewayFunc; + static registerGateway(scheme: string, func: FetchGatewayFunc): void; + static registerGetUrl(getUrl: FetchGetUrlFunc): void; +} +export interface FetchResponseWithBody extends FetchResponse { + body: Readonly; +} +export declare class FetchResponse implements Iterable<[key: string, value: string]> { + #private; + toString(): string; + get statusCode(): number; + get statusMessage(): string; + get headers(): Readonly>; + get body(): null | Readonly; + get bodyText(): string; + get bodyJson(): any; + [Symbol.iterator](): Iterator<[key: string, value: string]>; + constructor(statusCode: number, statusMessage: string, headers: Readonly>, body: null | Uint8Array, request?: FetchRequest); + makeServerError(message?: string, error?: Error): FetchResponse; + throwThrottleError(message?: string, stall?: number): never; + getHeader(key: string): string; + hasBody(): this is FetchResponseWithBody; + get request(): null | FetchRequest; + ok(): boolean; + assertOk(): void; +} +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/types/utils/fetch.d.ts.map b/types/utils/fetch.d.ts.map new file mode 100644 index 000000000..0ab103710 --- /dev/null +++ b/types/utils/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src.ts/utils/fetch.ts"],"names":[],"mappings":"AASA,oBAAY,cAAc,GAAG;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,IAAI,GAAG,UAAU,CAAA;CAC1B,CAAC;AAEF,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACtD,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AG,UAAU,EAAE,OAAO,CAAC,EAAE,YAAY;IAajJ,eAAe,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,aAAa;IAc/D,kBAAkB,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK;IAc3D,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAI9B,OAAO,IAAI,IAAI,IAAI,qBAAqB;IAIxC,IAAI,OAAO,IAAI,IAAI,GAAG,YAAY,CAA0B;IAE5D,EAAE,IAAI,OAAO;IAIb,QAAQ,IAAI,IAAI;CAUnB"} \ No newline at end of file diff --git a/types/utils/fixednumber.d.ts b/types/utils/fixednumber.d.ts new file mode 100644 index 000000000..a50bf7946 --- /dev/null +++ b/types/utils/fixednumber.d.ts @@ -0,0 +1,37 @@ +import type { BigNumberish, BytesLike, Numeric } from "./index.js"; +export declare function formatFixed(_value: BigNumberish, _decimals?: Numeric): string; +export declare function parseFixed(value: string, _decimals: Numeric): bigint; +export declare class FixedFormat { + readonly signed: boolean; + readonly width: number; + readonly decimals: number; + readonly name: string; + readonly _multiplier: bigint; + constructor(constructorGuard: any, signed: boolean, width: number, decimals: number); + static from(value: any): FixedFormat; +} +export declare class FixedNumber { + #private; + readonly format: FixedFormat; + readonly _isFixedNumber: boolean; + constructor(constructorGuard: any, hex: string, value: string, format?: FixedFormat); + addUnsafe(other: FixedNumber): FixedNumber; + subUnsafe(other: FixedNumber): FixedNumber; + mulUnsafe(other: FixedNumber): FixedNumber; + divUnsafe(other: FixedNumber): FixedNumber; + floor(): FixedNumber; + ceiling(): FixedNumber; + round(decimals?: number): FixedNumber; + isZero(): boolean; + isNegative(): boolean; + toString(): string; + toHexString(_width: Numeric): string; + toUnsafeFloat(): number; + toFormat(format: FixedFormat | string): FixedNumber; + static fromValue(value: BigNumberish, decimals?: number, format?: FixedFormat | string | number): FixedNumber; + static fromString(value: string, format?: FixedFormat | string | number): FixedNumber; + static fromBytes(_value: BytesLike, format?: FixedFormat | string | number): FixedNumber; + static from(value: any, format?: FixedFormat | string | number): FixedNumber; + static isFixedNumber(value: any): value is FixedNumber; +} +//# sourceMappingURL=fixednumber.d.ts.map \ No newline at end of file diff --git a/types/utils/fixednumber.d.ts.map b/types/utils/fixednumber.d.ts.map new file mode 100644 index 000000000..d470b8291 --- /dev/null +++ b/types/utils/fixednumber.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fixednumber.d.ts","sourceRoot":"","sources":["../../src.ts/utils/fixednumber.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AA2BnE,wBAAgB,WAAW,CAAC,MAAM,EAAE,YAAY,EAAE,SAAS,CAAC,EAAE,OAAO,GAAG,MAAM,CA4B7E;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,MAAM,CAkDpE;AAGD,qBAAa,WAAW;IACpB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;gBAEjB,gBAAgB,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAkBnF,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,GAAG,WAAW;CAgDvC;AAED,qBAAa,WAAW;;IACpB,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAE7B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;gBAKrB,gBAAgB,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW;IAsBnF,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW;IAO1C,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW;IAO1C,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW;IAO1C,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW;IAO1C,KAAK,IAAI,WAAW;IAcpB,OAAO,IAAI,WAAW;IAetB,KAAK,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,WAAW;IAmBrC,MAAM,IAAI,OAAO;IAIjB,UAAU,IAAI,OAAO;IAIrB,QAAQ,IAAI,MAAM;IAElB,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM;IAcpC,aAAa,IAAI,MAAM;IAEvB,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,GAAG,WAAW;IAKnD,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,YAAY,EAAE,QAAQ,SAAI,EAAE,MAAM,GAAE,WAAW,GAAG,MAAM,GAAG,MAAgB,GAAG,WAAW;IAKjH,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,GAAE,WAAW,GAAG,MAAM,GAAG,MAAgB,GAAG,WAAW;IAoB9F,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,GAAE,WAAW,GAAG,MAAM,GAAG,MAAgB,GAAG,WAAW;IAiBjG,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,MAAM;IAqB9D,MAAM,CAAC,aAAa,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,WAAW;CAGzD"} \ No newline at end of file diff --git a/types/utils/geturl-browser.d.ts b/types/utils/geturl-browser.d.ts new file mode 100644 index 000000000..e7f096036 --- /dev/null +++ b/types/utils/geturl-browser.d.ts @@ -0,0 +1,21 @@ +import type { FetchRequest, FetchCancelSignal, GetUrlResponse } from "./fetch.js"; +declare global { + class Headers { + constructor(values: Array<[string, string]>); + forEach(func: (v: string, k: string) => void): void; + } + class Response { + status: number; + statusText: string; + headers: Headers; + arrayBuffer(): Promise; + } + type FetchInit = { + method?: string; + headers?: Headers; + body?: Uint8Array; + }; + function fetch(url: string, init: FetchInit): Promise; +} +export declare function getUrl(req: FetchRequest, _signal?: FetchCancelSignal): Promise; +//# sourceMappingURL=geturl-browser.d.ts.map \ No newline at end of file diff --git a/types/utils/geturl-browser.d.ts.map b/types/utils/geturl-browser.d.ts.map new file mode 100644 index 000000000..11201ff55 --- /dev/null +++ b/types/utils/geturl-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"geturl-browser.d.ts","sourceRoot":"","sources":["../../src.ts/utils/geturl-browser.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAGlF,OAAO,CAAC,MAAM,CAAC;IACX,MAAM,OAAO;oBACG,MAAM,EAAE,KAAK,CAAC,CAAE,MAAM,EAAE,MAAM,CAAE,CAAC;QAC7C,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI;KACtD;IAED,MAAM,QAAQ;QACV,MAAM,EAAE,MAAM,CAAC;QACf,UAAU,EAAE,MAAM,CAAC;QACnB,OAAO,EAAE,OAAO,CAAC;QACjB,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC;KACtC;IAED,KAAK,SAAS,GAAG;QACb,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,IAAI,CAAC,EAAE,UAAU,CAAA;KACpB,CAAC;IAEF,SAAS,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACnE;AAID,wBAAsB,MAAM,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CA6CpG"} \ No newline at end of file diff --git a/types/utils/geturl.d.ts b/types/utils/geturl.d.ts new file mode 100644 index 000000000..c407acee9 --- /dev/null +++ b/types/utils/geturl.d.ts @@ -0,0 +1,3 @@ +import type { FetchRequest, FetchCancelSignal, GetUrlResponse } from "./fetch.js"; +export declare function getUrl(req: FetchRequest, signal?: FetchCancelSignal): Promise; +//# sourceMappingURL=geturl.d.ts.map \ No newline at end of file diff --git a/types/utils/geturl.d.ts.map b/types/utils/geturl.d.ts.map new file mode 100644 index 000000000..9d7c1baa8 --- /dev/null +++ b/types/utils/geturl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"geturl.d.ts","sourceRoot":"","sources":["../../src.ts/utils/geturl.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAGlF,wBAAsB,MAAM,CAAC,GAAG,EAAE,YAAY,EAAE,MAAM,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CAsFnG"} \ No newline at end of file diff --git a/types/utils/index.d.ts b/types/utils/index.d.ts new file mode 100644 index 000000000..3661e7625 --- /dev/null +++ b/types/utils/index.d.ts @@ -0,0 +1,31 @@ +export interface Freezable { + clone(): T; + freeze(): Frozen; + isFrozen(): boolean; +} +export declare type Frozen = Readonly<{ + [P in keyof T]: T[P] extends (...args: Array) => any ? T[P] : T[P] extends Freezable ? Frozen : Readonly; +}>; +export { decodeBase58, encodeBase58 } from "./base58.js"; +export { decodeBase64, encodeBase64 } from "./base64.js"; +export { isHexString, isBytesLike, hexlify, concat, dataLength, dataSlice, stripZerosLeft, zeroPadValue, zeroPadBytes } from "./data.js"; +export { isCallException, isError } from "./errors.js"; +export { EventPayload } from "./events.js"; +export { FetchRequest, FetchResponse } from "./fetch.js"; +export { FixedFormat, FixedNumber, formatFixed, parseFixed } from "./fixednumber.js"; +export { assertArgument, Logger, logger } from "./logger.js"; +export { fromTwos, toTwos, mask, toBigInt, toNumber, toHex, toArray, toQuantity } from "./maths.js"; +export { resolveProperties, defineReadOnly, defineProperties } from "./properties.js"; +export { decodeRlp } from "./rlp-decode.js"; +export { encodeRlp } from "./rlp-encode.js"; +export { getStore, setStore } from "./storage.js"; +export { formatEther, parseEther, formatUnits, parseUnits } from "./units.js"; +export { _toEscapedUtf8String, toUtf8Bytes, toUtf8CodePoints, toUtf8String, Utf8ErrorFuncs, } from "./utf8.js"; +export type { BytesLike } from "./data.js"; +export type { ErrorSignature, ErrorFetchRequestWithBody, ErrorFetchRequest, ErrorFetchResponseWithBody, ErrorFetchResponse, ErrorCode, EthersError, UnknownError, NotImplementedError, UnsupportedOperationError, NetworkError, ServerError, TimeoutError, BadDataError, CancelledError, BufferOverrunError, NumericFaultError, InvalidArgumentError, MissingArgumentError, UnexpectedArgumentError, CallExceptionError, InsufficientFundsError, NonceExpiredError, OffchainFaultError, ReplacementUnderpricedError, TransactionReplacedError, UnconfiguredNameError, UnpredictableGasLimitError, ActionRejectedError, CodedEthersError } from "./errors.js"; +export type { EventEmitterable, Listener } from "./events.js"; +export type { GetUrlResponse, FetchRequestWithBody, FetchResponseWithBody, FetchPreflightFunc, FetchProcessFunc, FetchRetryFunc, FetchGatewayFunc, FetchGetUrlFunc } from "./fetch.js"; +export { BigNumberish, Numeric } from "./maths.js"; +export type { RlpStructuredData } from "./rlp.js"; +export type { Utf8ErrorFunc, UnicodeNormalizationForm, Utf8ErrorReason } from "./utf8.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/utils/index.d.ts.map b/types/utils/index.d.ts.map new file mode 100644 index 000000000..f5e5e4aca --- /dev/null +++ b/types/utils/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/utils/index.ts"],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,EAAE,MAAM,YAAY,CAAC;AAEnD,YAAY,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAElD,YAAY,EACR,aAAa,EACb,wBAAwB,EACxB,eAAe,EAClB,MAAM,WAAW,CAAC"} \ No newline at end of file diff --git a/types/utils/logger.d.ts b/types/utils/logger.d.ts new file mode 100644 index 000000000..7a7dd852a --- /dev/null +++ b/types/utils/logger.d.ts @@ -0,0 +1,28 @@ +import type { BigNumberish, BytesLike } from "./index.js"; +import type { CodedEthersError, ErrorCode } from "./errors.js"; +export declare type ErrorInfo = Omit; +export declare type LogLevel = "debug" | "info" | "warning" | "error" | "off"; +export declare type AssertFunc = () => (undefined | T); +export declare class Logger { + #private; + readonly version: string; + constructor(version?: string); + get logLevel(): LogLevel; + set logLevel(value: LogLevel); + makeError>(message: string, code: K, info?: ErrorInfo): T; + throwError>(message: string, code: K, info?: ErrorInfo): never; + throwArgumentError(message: string, name: string, value: any): never; + assertNormalize(form: string): void; + assertPrivate(givenGuard: any, guard: any, className?: string): void; + assertArgumentCount(count: number, expectedCount: number, message?: string): void; + getBytes(value: BytesLike, name?: string): Uint8Array; + getBytesCopy(value: BytesLike, name?: string): Uint8Array; + getNumber(value: BigNumberish, name?: string): number; + getBigInt(value: BigNumberish, name?: string): bigint; + debug(...args: Array): void; + info(...args: Array): void; + warn(...args: Array): void; +} +export declare const logger: Logger; +export declare function assertArgument(check: unknown, message: string, name: string, value: unknown): asserts check; +//# sourceMappingURL=logger.d.ts.map \ No newline at end of file diff --git a/types/utils/logger.d.ts.map b/types/utils/logger.d.ts.map new file mode 100644 index 000000000..6899762aa --- /dev/null +++ b/types/utils/logger.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src.ts/utils/logger.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,SAAS,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E,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU;IAIrD,YAAY,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU;IAIzD,SAAS,CAAC,KAAK,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM;IAwBrD,SAAS,CAAC,KAAK,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM;IA6BrD,KAAK,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI;IAIhC,IAAI,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI;IAI/B,IAAI,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI;CAGlC;AAED,eAAO,MAAM,MAAM,QAAsB,CAAC;AAE1C,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,CAE3G"} \ No newline at end of file diff --git a/types/utils/maths.d.ts b/types/utils/maths.d.ts new file mode 100644 index 000000000..2ff7bba73 --- /dev/null +++ b/types/utils/maths.d.ts @@ -0,0 +1,28 @@ +import type { BytesLike } from "./data.js"; +export declare type Numeric = number | bigint; +export declare type BigNumberish = string | Numeric; +/** + * Convert %%value%% from a twos-compliment value of %%width%% bits. + */ +export declare function fromTwos(_value: BigNumberish, _width: Numeric): bigint; +/** + * Convert %%value%% to a twos-compliment value of %%width%% bits. + */ +export declare function toTwos(_value: BigNumberish, _width: Numeric): bigint; +/** + * Mask %%value%% with a bitmask of %%bits%% ones. + */ +export declare function mask(_value: BigNumberish, _bits: Numeric): bigint; +export declare function toBigInt(value: BigNumberish | Uint8Array): bigint; +export declare function toNumber(value: BigNumberish | Uint8Array): number; +/** + * Converts %%value%% to a Big Endian hexstring, optionally padded to + * %%width%% bytes. + */ +export declare function toHex(_value: BigNumberish, _width?: Numeric): string; +/** + * Converts %%value%% to a Big Endian Uint8Array. + */ +export declare function toArray(_value: BigNumberish): Uint8Array; +export declare function toQuantity(value: BytesLike | BigNumberish): string; +//# sourceMappingURL=maths.d.ts.map \ No newline at end of file diff --git a/types/utils/maths.d.ts.map b/types/utils/maths.d.ts.map new file mode 100644 index 000000000..c9c75423f --- /dev/null +++ b/types/utils/maths.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"maths.d.ts","sourceRoot":"","sources":["../../src.ts/utils/maths.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG3C,oBAAY,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;AACtC,oBAAY,YAAY,GAAG,MAAM,GAAG,OAAO,CAAC;AAM5C;;GAEG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CAWtE;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CAUpE;AAED;;GAEG;AACH,wBAAgB,IAAI,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,CAIjE;AASD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,GAAG,MAAM,CAWjE;AAMD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,GAAG,MAAM,CAEjE;AAED;;;GAGG;AAEH,wBAAgB,KAAK,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,MAAM,CAmBpE;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,GAAG,UAAU,CAgBxD;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,GAAG,YAAY,GAAG,MAAM,CAKlE"} \ No newline at end of file diff --git a/types/utils/properties.d.ts b/types/utils/properties.d.ts new file mode 100644 index 000000000..26861a497 --- /dev/null +++ b/types/utils/properties.d.ts @@ -0,0 +1,12 @@ +export declare function resolveProperties(value: { + [P in keyof T]: T[P] | Promise; +}): Promise; +export declare function defineReadOnly(object: T, name: P, value: T[P]): void; +export declare function defineProperties(target: T, values: { + [K in keyof T]?: undefined | T[K]; +}, types?: { + [K in keyof T]?: string; +}, defaults?: { + [K in keyof T]?: T[K]; +}): void; +//# sourceMappingURL=properties.d.ts.map \ No newline at end of file diff --git a/types/utils/properties.d.ts.map b/types/utils/properties.d.ts.map new file mode 100644 index 000000000..182891e71 --- /dev/null +++ b/types/utils/properties.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"properties.d.ts","sourceRoot":"","sources":["../../src.ts/utils/properties.ts"],"names":[],"mappings":"AAAA,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,KAAK,EAAE;KAAI,CAAC,IAAI,MAAM,CAAC,GAAI,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOvG;AAED,wBAAgB,cAAc,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAM1F;AA4ED,wBAAgB,gBAAgB,CAAC,CAAC,EACjC,MAAM,EAAE,CAAC,EACT,MAAM,EAAE;KAAI,CAAC,IAAI,MAAM,CAAC,CAAE,CAAC,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,EAC/C,KAAK,CAAC,EAAE;KAAI,CAAC,IAAI,MAAM,CAAC,CAAE,CAAC,EAAE,MAAM;CAAE,EACrC,QAAQ,CAAC,EAAE;KAAI,CAAC,IAAI,MAAM,CAAC,CAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,IAAI,CAc7C"} \ No newline at end of file diff --git a/types/utils/rlp-decode.d.ts b/types/utils/rlp-decode.d.ts new file mode 100644 index 000000000..0f832690b --- /dev/null +++ b/types/utils/rlp-decode.d.ts @@ -0,0 +1,3 @@ +import type { BytesLike, RlpStructuredData } from "./index.js"; +export declare function decodeRlp(_data: BytesLike): RlpStructuredData; +//# sourceMappingURL=rlp-decode.d.ts.map \ No newline at end of file diff --git a/types/utils/rlp-decode.d.ts.map b/types/utils/rlp-decode.d.ts.map new file mode 100644 index 000000000..bbc156e61 --- /dev/null +++ b/types/utils/rlp-decode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp-decode.d.ts","sourceRoot":"","sources":["../../src.ts/utils/rlp-decode.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AA8F/D,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,iBAAiB,CAO7D"} \ No newline at end of file diff --git a/types/utils/rlp-encode.d.ts b/types/utils/rlp-encode.d.ts new file mode 100644 index 000000000..762820281 --- /dev/null +++ b/types/utils/rlp-encode.d.ts @@ -0,0 +1,3 @@ +import type { RlpStructuredData } from "./rlp.js"; +export declare function encodeRlp(object: RlpStructuredData): string; +//# sourceMappingURL=rlp-encode.d.ts.map \ No newline at end of file diff --git a/types/utils/rlp-encode.d.ts.map b/types/utils/rlp-encode.d.ts.map new file mode 100644 index 000000000..c22c7cf2a --- /dev/null +++ b/types/utils/rlp-encode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp-encode.d.ts","sourceRoot":"","sources":["../../src.ts/utils/rlp-encode.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAiDlD,wBAAgB,SAAS,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAO3D"} \ No newline at end of file diff --git a/types/utils/rlp.d.ts b/types/utils/rlp.d.ts new file mode 100644 index 000000000..3bbda2cd2 --- /dev/null +++ b/types/utils/rlp.d.ts @@ -0,0 +1,4 @@ +export declare type RlpStructuredData = string | Array; +export { decodeRlp } from "./rlp-decode.js"; +export { encodeRlp } from "./rlp-encode.js"; +//# sourceMappingURL=rlp.d.ts.map \ No newline at end of file diff --git a/types/utils/rlp.d.ts.map b/types/utils/rlp.d.ts.map new file mode 100644 index 000000000..6b5c4750f --- /dev/null +++ b/types/utils/rlp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rlp.d.ts","sourceRoot":"","sources":["../../src.ts/utils/rlp.ts"],"names":[],"mappings":"AACA,oBAAY,iBAAiB,GAAG,MAAM,GAAG,KAAK,CAAC,iBAAiB,CAAC,CAAC;AAElE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/types/utils/storage.d.ts b/types/utils/storage.d.ts new file mode 100644 index 000000000..2d3b704e5 --- /dev/null +++ b/types/utils/storage.d.ts @@ -0,0 +1,3 @@ +export declare function getStore(store: T, key: P): T[P]; +export declare function setStore(store: T, key: P, value: T[P]): void; +//# sourceMappingURL=storage.d.ts.map \ No newline at end of file diff --git a/types/utils/storage.d.ts.map b/types/utils/storage.d.ts.map new file mode 100644 index 000000000..dc2c81c74 --- /dev/null +++ b/types/utils/storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src.ts/utils/storage.ts"],"names":[],"mappings":"AAAA,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAErE;AAED,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAKlF"} \ No newline at end of file diff --git a/types/utils/units.d.ts b/types/utils/units.d.ts new file mode 100644 index 000000000..2d663cc50 --- /dev/null +++ b/types/utils/units.d.ts @@ -0,0 +1,24 @@ +import type { BigNumberish, Numeric } from "../utils/index.js"; +/** + * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal + * places. The %%unit%% may be the number of decimal places or the name of + * a unit (e.g. ``"gwei"`` for 9 decimal places). + * + */ +export declare function formatUnits(value: BigNumberish, unit?: string | Numeric): string; +/** + * Converts the //decimal string// %%value%% to a [[BigInt]], assuming + * %%unit%% decimal places. The %%unit%% may the number of decimal places + * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places). + */ +export declare function parseUnits(value: string, unit?: string | Numeric): bigint; +/** + * Converts %%value%% into a //decimal string// using 18 decimal places. + */ +export declare function formatEther(wei: BigNumberish): string; +/** + * Converts the //decimal string// %%ether%% to a [[BigInt]], using 18 + * decimal places. + */ +export declare function parseEther(ether: string): bigint; +//# sourceMappingURL=units.d.ts.map \ No newline at end of file diff --git a/types/utils/units.d.ts.map b/types/utils/units.d.ts.map new file mode 100644 index 000000000..616460dd4 --- /dev/null +++ b/types/utils/units.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"units.d.ts","sourceRoot":"","sources":["../../src.ts/utils/units.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAa/D;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAOhF;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAWzE;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAErD;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD"} \ No newline at end of file diff --git a/types/utils/utf8.d.ts b/types/utils/utf8.d.ts new file mode 100644 index 000000000..8d733dc35 --- /dev/null +++ b/types/utils/utf8.d.ts @@ -0,0 +1,11 @@ +import type { BytesLike } from "./index.js"; +export declare type UnicodeNormalizationForm = "NFC" | "NFD" | "NFKC" | "NFKD"; +export declare type Utf8ErrorReason = "UNEXPECTED_CONTINUE" | "BAD_PREFIX" | "OVERRUN" | "MISSING_CONTINUE" | "OUT_OF_RANGE" | "UTF16_SURROGATE" | "OVERLONG"; +export declare type Utf8ErrorFunc = (reason: Utf8ErrorReason, offset: number, bytes: ArrayLike, output: Array, badCodepoint?: number) => number; +export declare const Utf8ErrorFuncs: Readonly>; +export declare function toUtf8Bytes(str: string, form?: UnicodeNormalizationForm): Uint8Array; +export declare function _toEscapedUtf8String(bytes: BytesLike, onError?: Utf8ErrorFunc): string; +export declare function _toUtf8String(codePoints: Array): string; +export declare function toUtf8String(bytes: BytesLike, onError?: Utf8ErrorFunc): string; +export declare function toUtf8CodePoints(str: string, form?: UnicodeNormalizationForm): Array; +//# sourceMappingURL=utf8.d.ts.map \ No newline at end of file diff --git a/types/utils/utf8.d.ts.map b/types/utils/utf8.d.ts.map new file mode 100644 index 000000000..ac40ca634 --- /dev/null +++ b/types/utils/utf8.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utf8.d.ts","sourceRoot":"","sources":["../../src.ts/utils/utf8.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAK5C,oBAAY,wBAAwB,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;AAEvE,oBAAY,eAAe,GAGvB,qBAAqB,GAIrB,YAAY,GAIZ,SAAS,GAIT,kBAAkB,GAKlB,cAAc,GAKd,iBAAiB,GAKjB,UAAU,CAAC;AAGf,oBAAY,aAAa,GAAG,CAAC,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;AA4CxJ,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,OAAO,GAAG,QAAQ,GAAG,SAAS,EAAE,aAAa,CAAC,CAIzF,CAAC;AAqGH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,wBAAwB,GAAG,UAAU,CAyCpF;AAOD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM,CAwBtF;AAED,wBAAgB,aAAa,CAAC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAW/D;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM,CAE9E;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,wBAAwB,GAAG,KAAK,CAAC,MAAM,CAAC,CAE5F"} \ No newline at end of file diff --git a/types/wallet/base-wallet.d.ts b/types/wallet/base-wallet.d.ts new file mode 100644 index 000000000..20ab089cc --- /dev/null +++ b/types/wallet/base-wallet.d.ts @@ -0,0 +1,17 @@ +import { AbstractSigner } from "../providers/index.js"; +import type { SigningKey } from "../crypto/index.js"; +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { Provider, TransactionRequest } from "../providers/index.js"; +export declare class BaseWallet extends AbstractSigner { + #private; + readonly address: string; + constructor(privateKey: SigningKey, provider?: null | Provider); + get signingKey(): SigningKey; + get privateKey(): string; + getAddress(): Promise; + connect(provider: null | Provider): BaseWallet; + signTransaction(_tx: TransactionRequest): Promise; + signMessage(message: string | Uint8Array): Promise; + signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; +} +//# sourceMappingURL=base-wallet.d.ts.map \ No newline at end of file diff --git a/types/wallet/base-wallet.d.ts.map b/types/wallet/base-wallet.d.ts.map new file mode 100644 index 000000000..88bf0cc0a --- /dev/null +++ b/types/wallet/base-wallet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"base-wallet.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/base-wallet.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAIvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAI1E,qBAAa,UAAW,SAAQ,cAAc;;IAC1C,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;gBAId,UAAU,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ;IAS9D,IAAI,UAAU,IAAI,UAAU,CAA6B;IACzD,IAAI,UAAU,IAAI,MAAM,CAAuC;IAEzD,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC;IAEnC,OAAO,CAAC,QAAQ,EAAE,IAAI,GAAG,QAAQ,GAAG,UAAU;IAIxC,eAAe,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC;IAqBzD,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC;IAI1D,aAAa,CAAC,MAAM,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;CAuB1I"} \ No newline at end of file diff --git a/types/wallet/hdwallet.d.ts b/types/wallet/hdwallet.d.ts new file mode 100644 index 000000000..92d944c77 --- /dev/null +++ b/types/wallet/hdwallet.d.ts @@ -0,0 +1,60 @@ +import { SigningKey } from "../crypto/index.js"; +import { VoidSigner } from "../providers/index.js"; +import { Mnemonic } from "./mnemonic.js"; +import { BaseWallet } from "./base-wallet.js"; +import type { BytesLike, Numeric } from "../utils/index.js"; +import type { Provider } from "../providers/index.js"; +import type { Wordlist } from "../wordlists/index.js"; +export declare const defaultPath = "m/44'/60'/0'/0/0"; +export interface HDNodeWithPath { + path: string; +} +export declare class HDNodeWallet extends BaseWallet { + #private; + readonly publicKey: string; + readonly fingerprint: string; + readonly parentFingerprint: string; + readonly mnemonic: null | Mnemonic; + readonly chainCode: string; + readonly path: null | string; + readonly index: number; + readonly depth: number; + constructor(guard: any, signingKey: SigningKey, parentFingerprint: string, chainCode: string, path: null | string, index: number, depth: number, mnemonic: null | Mnemonic, provider: null | Provider); + connect(provider: null | Provider): HDNodeWallet; + get extendedKey(): string; + hasPath(): this is { + path: string; + }; + neuter(): HDNodeVoidWallet; + deriveChild(_index: Numeric): HDNodeWallet; + derivePath(path: string): HDNodeWallet; + static fromSeed(seed: BytesLike): HDNodeWallet; + static fromPhrase(phrase: string, password?: string, path?: null | string, wordlist?: Wordlist): HDNodeWallet; + static fromMnemonic(mnemonic: Mnemonic, path?: null | string): HDNodeWallet; + static fromExtendedKey(extendedKey: string): HDNodeWallet | HDNodeVoidWallet; + static createRandom(password?: string, path?: null | string, wordlist?: Wordlist): HDNodeWallet; +} +export declare class HDNodeVoidWallet extends VoidSigner { + readonly publicKey: string; + readonly fingerprint: string; + readonly parentFingerprint: string; + readonly chainCode: string; + readonly path: null | string; + readonly index: number; + readonly depth: number; + constructor(guard: any, address: string, publicKey: string, parentFingerprint: string, chainCode: string, path: null | string, index: number, depth: number, provider: null | Provider); + connect(provider: null | Provider): HDNodeVoidWallet; + get extendedKey(): string; + hasPath(): this is { + path: string; + }; + deriveChild(_index: Numeric): HDNodeVoidWallet; + derivePath(path: string): HDNodeVoidWallet; +} +export declare class HDNodeWalletManager { + #private; + constructor(phrase: string, password?: string, path?: string, locale?: Wordlist); + getSigner(index?: number): HDNodeWallet; +} +export declare function getAccountPath(_index: Numeric): string; +//# sourceMappingURL=hdwallet.d.ts.map \ No newline at end of file diff --git a/types/wallet/hdwallet.d.ts.map b/types/wallet/hdwallet.d.ts.map new file mode 100644 index 000000000..75c6873fe --- /dev/null +++ b/types/wallet/hdwallet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hdwallet.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/hdwallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuC,UAAU,EAAU,MAAM,oBAAoB,CAAC;AAC7F,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAOnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAGtD,eAAO,MAAM,WAAW,qBAAqB,CAAC;AAwF9C,MAAM,WAAW,cAAc;IAC3B,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,qBAAa,YAAa,SAAQ,UAAU;;IACxC,QAAQ,CAAC,SAAS,EAAG,MAAM,CAAC;IAE5B,QAAQ,CAAC,WAAW,EAAG,MAAM,CAAC;IAC9B,QAAQ,CAAC,iBAAiB,EAAG,MAAM,CAAC;IAEpC,QAAQ,CAAC,QAA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100644 index 000000000..64155da3a --- /dev/null +++ b/types/wallet/index.d.ts @@ -0,0 +1,7 @@ +export { defaultPath, getAccountPath, HDNodeWallet, HDNodeVoidWallet, HDNodeWalletManager, } from "./hdwallet.js"; +export { isCrowdsaleJson, decryptCrowdsaleJson } from "./json-crowdsale.js"; +export { isKeystoreJson, decryptKeystoreJsonSync, decryptKeystoreJson, encryptKeystoreJson } from "./json-keystore.js"; +export { Mnemonic } from "./mnemonic.js"; +export { Wallet } from "./wallet.js"; +export type { KeystoreAccountParams, KeystoreAccount, EncryptOptions } from "./json-keystore.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/wallet/index.d.ts.map b/types/wallet/index.d.ts.map new file mode 100644 index 000000000..699454f8a --- /dev/null +++ b/types/wallet/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,WAAW,EAEX,cAAc,EAEd,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,GACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EACH,cAAc,EACd,uBAAuB,EAAE,mBAAmB,EAC5C,mBAAmB,EACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,YAAY,EACR,qBAAqB,EAAE,eAAe,EACtC,cAAc,EACjB,MAAM,oBAAoB,CAAA"} \ No newline at end of file diff --git a/types/wallet/json-crowdsale.d.ts b/types/wallet/json-crowdsale.d.ts new file mode 100644 index 000000000..799c0e259 --- /dev/null +++ b/types/wallet/json-crowdsale.d.ts @@ -0,0 +1,7 @@ +export interface CrowdsaleAccount { + privateKey: string; + address: string; +} +export declare function isCrowdsaleJson(json: string): boolean; +export declare function decryptCrowdsaleJson(json: string, _password: string | Uint8Array): CrowdsaleAccount; +//# sourceMappingURL=json-crowdsale.d.ts.map \ No newline at end of file diff --git a/types/wallet/json-crowdsale.d.ts.map b/types/wallet/json-crowdsale.d.ts.map new file mode 100644 index 000000000..de1e72270 --- /dev/null +++ b/types/wallet/json-crowdsale.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json-crowdsale.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/json-crowdsale.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,gBAAgB;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMrD;AAGD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,UAAU,GAAG,gBAAgB,CA6BnG"} \ No newline at end of file diff --git a/types/wallet/json-keystore.d.ts b/types/wallet/json-keystore.d.ts new file mode 100644 index 000000000..25481d615 --- /dev/null +++ b/types/wallet/json-keystore.d.ts @@ -0,0 +1,37 @@ +import type { ProgressCallback } from "../crypto/index.js"; +import type { BytesLike } from "../utils/index.js"; +export declare type KeystoreAccountParams = { + privateKey: string; + address?: string; + mnemonic?: { + entropy: string; + path: string; + locale: string; + }; +}; +export declare type KeystoreAccount = { + address: string; + privateKey: string; + mnemonic?: { + entropy: string; + path: string; + locale: string; + }; +}; +export declare type EncryptOptions = { + iv?: BytesLike; + entropy?: BytesLike; + client?: string; + salt?: BytesLike; + uuid?: string; + scrypt?: { + N?: number; + r?: number; + p?: number; + }; +}; +export declare function isKeystoreJson(json: string): boolean; +export declare function decryptKeystoreJsonSync(json: string, _password: string | Uint8Array): KeystoreAccount; +export declare function decryptKeystoreJson(json: string, _password: string | Uint8Array, progress?: ProgressCallback): Promise; +export declare function encryptKeystoreJson(account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions, progressCallback?: ProgressCallback): Promise; +//# sourceMappingURL=json-keystore.d.ts.map \ No newline at end of file diff --git a/types/wallet/json-keystore.d.ts.map b/types/wallet/json-keystore.d.ts.map new file mode 100644 index 000000000..67f60cf8c --- /dev/null +++ b/types/wallet/json-keystore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json-keystore.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/json-keystore.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAOnD,oBAAY,qBAAqB,GAAG;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE;QACP,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,CAAC;KAClB,CAAC;CACL,CAAC;AAEF,oBAAY,eAAe,GAAG;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE;QACP,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,CAAC;KAClB,CAAC;CACL,CAAC;AAEF,oBAAY,cAAc,GAAG;IAC1B,EAAE,CAAC,EAAE,SAAS,CAAC;IACf,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE;QACL,CAAC,CAAC,EAAE,MAAM,CAAC;QACX,CAAC,CAAC,EAAE,MAAM,CAAC;QACX,CAAC,CAAC,EAAE,MAAM,CAAC;KACd,CAAA;CACH,CAAA;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAOpD;AAwHD,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,UAAU,GAAG,eAAe,CAiBrG;AAMD,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,UAAU,EAAE,QAAQ,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CAyB7I;AAGD,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,OAAO,CAAC,EAAE,cAAc,EAAE,gBAAgB,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CA0IjL"} \ No newline at end of file diff --git a/types/wallet/mnemonic.d.ts b/types/wallet/mnemonic.d.ts new file mode 100644 index 000000000..75c7877aa --- /dev/null +++ b/types/wallet/mnemonic.d.ts @@ -0,0 +1,16 @@ +import type { BytesLike } from "../utils/index.js"; +import type { Wordlist } from "../wordlists/index.js"; +export declare class Mnemonic { + readonly phrase: string; + readonly password: string; + readonly wordlist: Wordlist; + readonly entropy: string; + constructor(guard: any, entropy: string, phrase: string, password?: null | string, wordlist?: null | Wordlist); + computeSeed(): string; + static fromPhrase(phrase: string, password?: null | string, wordlist?: null | Wordlist): Mnemonic; + static fromEntropy(_entropy: BytesLike, password?: null | string, wordlist?: null | Wordlist): Mnemonic; + static entropyToPhrase(_entropy: BytesLike, wordlist?: null | Wordlist): string; + static phraseToEntropy(phrase: string, wordlist?: null | Wordlist): string; + static isValidMnemonic(phrase: string, wordlist?: null | Wordlist): boolean; +} +//# sourceMappingURL=mnemonic.d.ts.map \ No newline at end of file diff --git a/types/wallet/mnemonic.d.ts.map b/types/wallet/mnemonic.d.ts.map new file mode 100644 index 000000000..ff3fbb601 --- /dev/null +++ b/types/wallet/mnemonic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mnemonic.d.ts","sourceRoot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000..bf943c675 --- /dev/null +++ b/types/wallet/utils.d.ts @@ -0,0 +1,7 @@ +import type { BytesLike } from "../utils/index.js"; +export declare function looseArrayify(hexString: string): Uint8Array; +export declare function zpad(value: String | number, length: number): String; +export declare function getPassword(password: string | Uint8Array): Uint8Array; +export declare function spelunk(object: any, _path: string): T; +export declare function uuidV4(randomBytes: BytesLike): string; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/types/wallet/utils.d.ts.map b/types/wallet/utils.d.ts.map new file mode 100644 index 000000000..c658ebd97 --- /dev/null +++ b/types/wallet/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/utils.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAGnD,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,UAAU,CAK3D;AAED,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAInE;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,CAKrE;AAED,wBAAgB,OAAO,CAAC,CAAC,GAAG,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAiEjE;AAiCD,wBAAgB,MAAM,CAAC,WAAW,EAAE,SAAS,GAAG,MAAM,CAqBrD"} \ No newline at end of file diff --git a/types/wallet/wallet.d.ts b/types/wallet/wallet.d.ts new file mode 100644 index 000000000..7901e31e4 --- /dev/null +++ b/types/wallet/wallet.d.ts @@ -0,0 +1,20 @@ +import { SigningKey } from "../crypto/index.js"; +import { BaseWallet } from "./base-wallet.js"; +import { Mnemonic } from "./mnemonic.js"; +import type { ProgressCallback } from "../crypto/index.js"; +import type { Provider } from "../providers/index.js"; +import type { Wordlist } from "../wordlists/index.js"; +export declare class Wallet extends BaseWallet { + #private; + constructor(key: string | Mnemonic | SigningKey | BaseWallet, provider?: null | Provider); + get mnemonic(): null | Mnemonic; + connect(provider: null | Provider): Wallet; + encrypt(password: Uint8Array | string, options?: any, progressCallback?: ProgressCallback): Promise; + encryptSync(password: Uint8Array | string, options?: any): Promise; + static fromEncryptedJson(json: string, password: Uint8Array | string, progress?: ProgressCallback): Promise; + static fromEncryptedJsonSync(json: string, password: Uint8Array | string): Wallet; + static createRandom(provider?: null | Provider, password?: null | string, wordlist?: null | Wordlist): Wallet; + static fromMnemonic(mnemonic: Mnemonic, provider?: null | Provider): Wallet; + static fromPhrase(phrase: string, provider?: null | Provider, password?: string, wordlist?: Wordlist): Wallet; +} +//# sourceMappingURL=wallet.d.ts.map \ No newline at end of file diff --git a/types/wallet/wallet.d.ts.map b/types/wallet/wallet.d.ts.map new file mode 100644 index 000000000..082e6aac9 --- /dev/null +++ b/types/wallet/wallet.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["../../src.ts/wallet/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAI7D,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAM9C,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AA8CtD,qBAAa,MAAO,SAAQ,UAAU;;gBAGtB,GAAG,EAAE,MAAM,GAAG,QAAQ,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ;IAqCxF,IAAI,QAAQ,IAAI,IAAI,GAAG,QAAQ,CAA2B;IAE1D,OAAO,CAAC,QAAQ,EAAE,IAAI,GAAG,QAAQ,GAAG,MAAM;IAIpC,OAAO,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,gBAAgB,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAIjH,WAAW,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC;WAI7D,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,GAAG,MAAM,EAAE,QAAQ,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBzH,MAAM,CAAC,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,GAAG,MAAM,GAAG,MAAM;IAkBjF,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,MAAM,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ,GAAG,MAAM;IAI7G,MAAM,CAAC,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ,GAAG,MAAM;IAI3E,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ,EAAE,QAAQ,SAAK,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,MAAM;CAG5G"} \ No newline at end of file diff --git a/types/wordlists/bit-reader.d.ts b/types/wordlists/bit-reader.d.ts new file mode 100644 index 000000000..2f47f1d7e --- /dev/null +++ b/types/wordlists/bit-reader.d.ts @@ -0,0 +1,2 @@ +export declare function decodeBits(width: number, data: string): Array; +//# sourceMappingURL=bit-reader.d.ts.map \ No newline at end of file diff --git a/types/wordlists/bit-reader.d.ts.map b/types/wordlists/bit-reader.d.ts.map new file mode 100644 index 000000000..048870dd5 --- /dev/null +++ b/types/wordlists/bit-reader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bit-reader.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/bit-reader.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CA6BrE"} \ No newline at end of file diff --git a/types/wordlists/decode-owl.d.ts b/types/wordlists/decode-owl.d.ts new file mode 100644 index 000000000..14d7c3f54 --- /dev/null +++ b/types/wordlists/decode-owl.d.ts @@ -0,0 +1,3 @@ +export declare function decode(data: string, subs: string): Array; +export declare function decodeOwl(data: string): Array; +//# sourceMappingURL=decode-owl.d.ts.map \ No newline at end of file diff --git a/types/wordlists/decode-owl.d.ts.map b/types/wordlists/decode-owl.d.ts.map new file mode 100644 index 000000000..fe95e9bb1 --- /dev/null +++ b/types/wordlists/decode-owl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-owl.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/decode-owl.ts"],"names":[],"mappings":"AAqBA,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAsBhE;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAMrD"} \ No newline at end of file diff --git a/types/wordlists/decode-owla.d.ts b/types/wordlists/decode-owla.d.ts new file mode 100644 index 000000000..632a1a67c --- /dev/null +++ b/types/wordlists/decode-owla.d.ts @@ -0,0 +1,2 @@ +export declare function decodeOwlA(data: string, accents: string): Array; +//# sourceMappingURL=decode-owla.d.ts.map \ No newline at end of file diff --git a/types/wordlists/decode-owla.d.ts.map b/types/wordlists/decode-owla.d.ts.map new file mode 100644 index 000000000..06221820a --- /dev/null +++ b/types/wordlists/decode-owla.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-owla.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/decode-owla.ts"],"names":[],"mappings":"AAKA,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAwBvE"} \ No newline at end of file diff --git a/types/wordlists/generation/encode-latin.d.ts b/types/wordlists/generation/encode-latin.d.ts new file mode 100644 index 000000000..a646e8246 --- /dev/null +++ b/types/wordlists/generation/encode-latin.d.ts @@ -0,0 +1,25 @@ +export declare class BitWriter { + #private; + readonly width: number; + constructor(width: number); + write(value: number): void; + get length(): number; + get data(): string; +} +export interface AccentSet { + accent: number; + follows: string; + positions: Array; + positionsLength: number; + positionData: string; + positionDataLength: number; +} +export declare function extractAccents(words: Array): { + accents: Array; + words: Array; +}; +export declare function encodeOwl(words: Array): { + subs: string; + data: string; +}; +//# sourceMappingURL=encode-latin.d.ts.map \ No newline at end of file diff --git a/types/wordlists/generation/encode-latin.d.ts.map b/types/wordlists/generation/encode-latin.d.ts.map new file mode 100644 index 000000000..3aef41354 --- /dev/null +++ b/types/wordlists/generation/encode-latin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-latin.d.ts","sourceRoot":"","sources":["../../../src.ts/wordlists/generation/encode-latin.ts"],"names":[],"mappings":"AAuIA,qBAAa,SAAS;;IAClB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;gBAKX,KAAK,EAAE,MAAM;IAMzB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAW1B,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED,IAAI,IAAI,IAAI,MAAM,CA4BjB;CACJ;AAED,MAAM,WAAW,SAAS;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;CAC9B;AAWD,wBAAgB,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;CAAE,CAyExG;AAGD,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CA4C9E"} \ No newline at end of file diff --git a/types/wordlists/index.d.ts b/types/wordlists/index.d.ts new file mode 100644 index 000000000..67ce87c46 --- /dev/null +++ b/types/wordlists/index.d.ts @@ -0,0 +1,6 @@ +export { Wordlist } from "./wordlist.js"; +export { langEn, LangEn } from "./lang-en.js"; +export { wordlists } from "./wordlists.js"; +export { WordlistOwl } from "./wordlist-owl.js"; +export { WordlistOwlA } from "./wordlist-owla.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/types/wordlists/index.d.ts.map b/types/wordlists/index.d.ts.map new file mode 100644 index 000000000..945f48427 --- /dev/null +++ b/types/wordlists/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-cz.d.ts b/types/wordlists/lang-cz.d.ts new file mode 100644 index 000000000..6a65523d6 --- /dev/null +++ b/types/wordlists/lang-cz.d.ts @@ -0,0 +1,6 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +export declare class LangCz extends WordlistOwl { + constructor(); +} +export declare const langCz: LangCz; +//# sourceMappingURL=lang-cz.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-cz.d.ts.map b/types/wordlists/lang-cz.d.ts.map new file mode 100644 index 000000000..43435a45c --- /dev/null +++ b/types/wordlists/lang-cz.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-cz.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-cz.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAKhD,qBAAa,MAAO,SAAQ,WAAW;;CAEtC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-en.d.ts b/types/wordlists/lang-en.d.ts new file mode 100644 index 000000000..7735c6fea --- /dev/null +++ b/types/wordlists/lang-en.d.ts @@ -0,0 +1,6 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +export declare class LangEn extends WordlistOwl { + constructor(); +} +export declare const langEn: LangEn; +//# sourceMappingURL=lang-en.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-en.d.ts.map b/types/wordlists/lang-en.d.ts.map new file mode 100644 index 000000000..1230e7b69 --- /dev/null +++ b/types/wordlists/lang-en.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-en.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-en.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAKhD,qBAAa,MAAO,SAAQ,WAAW;;CAEtC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-es.d.ts b/types/wordlists/lang-es.d.ts new file mode 100644 index 000000000..41c469bf5 --- /dev/null +++ b/types/wordlists/lang-es.d.ts @@ -0,0 +1,6 @@ +import { WordlistOwlA } from "./wordlist-owla.js"; +export declare class LangEs extends WordlistOwlA { + constructor(); +} +export declare const langEs: LangEs; +//# sourceMappingURL=lang-es.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-es.d.ts.map b/types/wordlists/lang-es.d.ts.map new file mode 100644 index 000000000..440bd83e8 --- /dev/null +++ b/types/wordlists/lang-es.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-es.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-es.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAMlD,qBAAa,MAAO,SAAQ,YAAY;;CAEvC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-fr.d.ts b/types/wordlists/lang-fr.d.ts new file mode 100644 index 000000000..50e023ab1 --- /dev/null +++ b/types/wordlists/lang-fr.d.ts @@ -0,0 +1,6 @@ +import { WordlistOwlA } from "./wordlist-owla.js"; +export declare class LangFr extends WordlistOwlA { + constructor(); +} +export declare const langFr: LangFr; +//# sourceMappingURL=lang-fr.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-fr.d.ts.map b/types/wordlists/lang-fr.d.ts.map new file mode 100644 index 000000000..e0491ca39 --- /dev/null +++ b/types/wordlists/lang-fr.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-fr.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-fr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAMlD,qBAAa,MAAO,SAAQ,YAAY;;CAEvC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-it.d.ts b/types/wordlists/lang-it.d.ts new file mode 100644 index 000000000..b3001de71 --- /dev/null +++ b/types/wordlists/lang-it.d.ts @@ -0,0 +1,6 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +export declare class LangIt extends WordlistOwl { + constructor(); +} +export declare const langIt: LangIt; +//# sourceMappingURL=lang-it.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-it.d.ts.map b/types/wordlists/lang-it.d.ts.map new file mode 100644 index 000000000..015931461 --- /dev/null +++ b/types/wordlists/lang-it.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-it.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-it.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAKhD,qBAAa,MAAO,SAAQ,WAAW;;CAEtC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-ja.d.ts b/types/wordlists/lang-ja.d.ts new file mode 100644 index 000000000..0efd95755 --- /dev/null +++ b/types/wordlists/lang-ja.d.ts @@ -0,0 +1,11 @@ +import { Wordlist } from "./wordlist.js"; +declare class LangJa extends Wordlist { + constructor(); + getWord(index: number): string; + getWordIndex(word: string): number; + split(mnemonic: string): Array; + join(words: Array): string; +} +export declare const langJa: LangJa; +export {}; +//# sourceMappingURL=lang-ja.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-ja.d.ts.map b/types/wordlists/lang-ja.d.ts.map new file mode 100644 index 000000000..041ea5460 --- /dev/null +++ b/types/wordlists/lang-ja.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-ja.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-ja.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAgIzC,cAAM,MAAO,SAAQ,QAAQ;;IAGzB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAQ9B,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAIlC,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAKtC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM;CAGrC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-ko.d.ts b/types/wordlists/lang-ko.d.ts new file mode 100644 index 000000000..3b297761a --- /dev/null +++ b/types/wordlists/lang-ko.d.ts @@ -0,0 +1,9 @@ +import { Wordlist } from "./wordlist.js"; +declare class LangKo extends Wordlist { + constructor(); + getWord(index: number): string; + getWordIndex(word: string): number; +} +export declare const langKo: LangKo; +export {}; +//# sourceMappingURL=lang-ko.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-ko.d.ts.map b/types/wordlists/lang-ko.d.ts.map new file mode 100644 index 000000000..9463135f1 --- /dev/null +++ b/types/wordlists/lang-ko.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-ko.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-ko.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AA6DzC,cAAM,MAAO,SAAQ,QAAQ;;IAKzB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAQ9B,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAGrC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-pt.d.ts b/types/wordlists/lang-pt.d.ts new file mode 100644 index 000000000..00c57415f --- /dev/null +++ b/types/wordlists/lang-pt.d.ts @@ -0,0 +1,6 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +export declare class LangPt extends WordlistOwl { + constructor(); +} +export declare const langPt: LangPt; +//# sourceMappingURL=lang-pt.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-pt.d.ts.map b/types/wordlists/lang-pt.d.ts.map new file mode 100644 index 000000000..91f4a5e30 --- /dev/null +++ b/types/wordlists/lang-pt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-pt.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-pt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAKhD,qBAAa,MAAO,SAAQ,WAAW;;CAEtC;AAED,eAAO,MAAM,MAAM,QAAe,CAAC"} \ No newline at end of file diff --git a/types/wordlists/lang-zh.d.ts b/types/wordlists/lang-zh.d.ts new file mode 100644 index 000000000..90b383790 --- /dev/null +++ b/types/wordlists/lang-zh.d.ts @@ -0,0 +1,11 @@ +import { Wordlist } from "./wordlist.js"; +declare class LangZh extends Wordlist { + constructor(country: string); + getWord(index: number): string; + getWordIndex(word: string): number; + split(mnemonic: string): Array; +} +export declare const langZhCn: LangZh; +export declare const langZhTw: LangZh; +export {}; +//# sourceMappingURL=lang-zh.d.ts.map \ No newline at end of file diff --git a/types/wordlists/lang-zh.d.ts.map b/types/wordlists/lang-zh.d.ts.map new file mode 100644 index 000000000..d6e77bbd2 --- /dev/null +++ b/types/wordlists/lang-zh.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lang-zh.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/lang-zh.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAyDzC,cAAM,MAAO,SAAQ,QAAQ;gBACb,OAAO,EAAE,MAAM;IAE3B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAQ9B,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAIlC,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;CAIzC;AAED,eAAO,MAAM,QAAQ,QAAmB,CAAC;AACzC,eAAO,MAAM,QAAQ,QAAmB,CAAC"} \ No newline at end of file diff --git a/types/wordlists/wordlist-owl.d.ts b/types/wordlists/wordlist-owl.d.ts new file mode 100644 index 000000000..e3a01003d --- /dev/null +++ b/types/wordlists/wordlist-owl.d.ts @@ -0,0 +1,10 @@ +import { Wordlist } from "./wordlist.js"; +export declare class WordlistOwl extends Wordlist { + #private; + constructor(locale: string, data: string, checksum: string); + get _data(): string; + _decodeWords(): Array; + getWord(index: number): string; + getWordIndex(word: string): number; +} +//# sourceMappingURL=wordlist-owl.d.ts.map \ No newline at end of file diff --git a/types/wordlists/wordlist-owl.d.ts.map b/types/wordlists/wordlist-owl.d.ts.map new file mode 100644 index 000000000..b71ef08e3 --- /dev/null +++ b/types/wordlists/wordlist-owl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist-owl.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist-owl.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,qBAAa,WAAY,SAAQ,QAAQ;;gBAIzB,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAO1D,IAAI,KAAK,IAAI,MAAM,CAAuB;IAE1C,YAAY,IAAI,KAAK,CAAC,MAAM,CAAC;IAsB7B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAQ9B,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAGrC"} \ No newline at end of file diff --git a/types/wordlists/wordlist-owla.d.ts b/types/wordlists/wordlist-owla.d.ts new file mode 100644 index 000000000..d16c1627b --- /dev/null +++ b/types/wordlists/wordlist-owla.d.ts @@ -0,0 +1,8 @@ +import { WordlistOwl } from "./wordlist-owl.js"; +export declare class WordlistOwlA extends WordlistOwl { + #private; + constructor(locale: string, data: string, accent: string, checksum: string); + get _accent(): string; + _decodeWords(): Array; +} +//# sourceMappingURL=wordlist-owla.d.ts.map \ No newline at end of file diff --git a/types/wordlists/wordlist-owla.d.ts.map b/types/wordlists/wordlist-owla.d.ts.map new file mode 100644 index 000000000..1a944c43d --- /dev/null +++ b/types/wordlists/wordlist-owla.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist-owla.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist-owla.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,qBAAa,YAAa,SAAQ,WAAW;;gBAG7B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAK1E,IAAI,OAAO,IAAI,MAAM,CAAyB;IAE9C,YAAY,IAAI,KAAK,CAAC,MAAM,CAAC;CAGhC"} \ No newline at end of file diff --git a/types/wordlists/wordlist.d.ts b/types/wordlists/wordlist.d.ts new file mode 100644 index 000000000..0c575e59c --- /dev/null +++ b/types/wordlists/wordlist.d.ts @@ -0,0 +1,9 @@ +export declare abstract class Wordlist { + locale: string; + constructor(locale: string); + split(mnemonic: string): Array; + join(words: Array): string; + abstract getWord(index: number): string; + abstract getWordIndex(word: string): number; +} +//# sourceMappingURL=wordlist.d.ts.map \ No newline at end of file diff --git a/types/wordlists/wordlist.d.ts.map b/types/wordlists/wordlist.d.ts.map new file mode 100644 index 000000000..a86fd60f1 --- /dev/null +++ b/types/wordlists/wordlist.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlist.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/wordlist.ts"],"names":[],"mappings":"AAEA,8BAAsB,QAAQ;IAC1B,MAAM,EAAG,MAAM,CAAC;gBAEJ,MAAM,EAAE,MAAM;IAK1B,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAKtC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM;IAIlC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IACvC,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAC9C"} \ No newline at end of file diff --git a/types/wordlists/wordlists-browser.d.ts b/types/wordlists/wordlists-browser.d.ts new file mode 100644 index 000000000..d0dbd19c9 --- /dev/null +++ b/types/wordlists/wordlists-browser.d.ts @@ -0,0 +1,3 @@ +import type { Wordlist } from "./wordlist.js"; +export declare const wordlists: Record; +//# sourceMappingURL=wordlists-browser.d.ts.map \ No newline at end of file diff --git a/types/wordlists/wordlists-browser.d.ts.map b/types/wordlists/wordlists-browser.d.ts.map new file mode 100644 index 000000000..2bc8ae38c --- /dev/null +++ b/types/wordlists/wordlists-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists-browser.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists-browser.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAE7C,CAAC"} \ No newline at end of file diff --git a/types/wordlists/wordlists-extra.d.ts b/types/wordlists/wordlists-extra.d.ts new file mode 100644 index 000000000..e335b3464 --- /dev/null +++ b/types/wordlists/wordlists-extra.d.ts @@ -0,0 +1,3 @@ +import type { Wordlist } from "./wordlist.js"; +export declare const wordlists: Record; +//# sourceMappingURL=wordlists-extra.d.ts.map \ No newline at end of file diff --git a/types/wordlists/wordlists-extra.d.ts.map b/types/wordlists/wordlists-extra.d.ts.map new file mode 100644 index 000000000..37539d91a --- /dev/null +++ b/types/wordlists/wordlists-extra.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists-extra.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists-extra.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAE7C,CAAC"} \ No newline at end of file diff --git a/types/wordlists/wordlists.d.ts b/types/wordlists/wordlists.d.ts new file mode 100644 index 000000000..36d5264f0 --- /dev/null +++ b/types/wordlists/wordlists.d.ts @@ -0,0 +1,3 @@ +import type { Wordlist } from "./wordlist.js"; +export declare const wordlists: Record; +//# sourceMappingURL=wordlists.d.ts.map \ No newline at end of file diff --git a/types/wordlists/wordlists.d.ts.map b/types/wordlists/wordlists.d.ts.map new file mode 100644 index 000000000..07f8008b8 --- /dev/null +++ b/types/wordlists/wordlists.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wordlists.d.ts","sourceRoot":"","sources":["../../src.ts/wordlists/wordlists.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAE7C,CAAC"} \ No newline at end of file