@zama-fhe/sdk 3.6.0 → 3.7.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/chains.cjs +1 -1
- package/dist/cjs/chains.cjs.map +1 -1
- package/dist/cjs/ethers/index.cjs +1 -1
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/fhevm-relayer.cjs +2 -2
- package/dist/cjs/fhevm-relayer.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/token.cjs +1 -1
- package/dist/cjs/token.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/base-signer--sBO2qJp.js +2 -0
- package/dist/esm/base-signer--sBO2qJp.js.map +1 -0
- package/dist/esm/{base-signer-Iu5Lszrf.d.ts → base-signer-S2Ogf6L4.d.ts} +2 -2
- package/dist/esm/chains/index.d.ts +1 -1
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/chains-DEpKup1n.js +2 -0
- package/dist/esm/chains-DEpKup1n.js.map +1 -0
- package/dist/esm/cleartext/index.d.ts +2 -2
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-iE4sWgSP.js → cleartext-DcbDCDXj.js} +2 -2
- package/dist/esm/{cleartext-iE4sWgSP.js.map → cleartext-DcbDCDXj.js.map} +1 -1
- package/dist/esm/{cleartext-B2DI8fgm.d.ts → cleartext-pv2blbFU.d.ts} +2 -2
- package/dist/esm/encrypt.worker.js +51 -51
- package/dist/esm/{encryption-BKoalB4o.js → encryption-DJljZ2oV.js} +2 -2
- package/dist/esm/{encryption-BKoalB4o.js.map → encryption-DJljZ2oV.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +5 -5
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/fhevm-relayer-CPmCytDX.js +8 -0
- package/dist/esm/fhevm-relayer-CPmCytDX.js.map +1 -0
- package/dist/esm/{index-BCh3VaZo.d.ts → index-DRrrBtMX.d.ts} +2000 -1115
- package/dist/esm/{index-ijgDL4IC.d.ts → index-Gk1S0gjO.d.ts} +14 -1
- package/dist/esm/{index-S6QjPkZE.d.ts → index-tfvbrVa2.d.ts} +4 -4
- package/dist/esm/index.d.ts +108 -8
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +4 -4
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/query/index.d.ts +4 -537
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-B6Zo6EkX.js +2 -0
- package/dist/esm/relayer-B6Zo6EkX.js.map +1 -0
- package/dist/esm/token-BMQ6xlrk.js +2 -0
- package/dist/esm/{token-BejFVO8m.js.map → token-BMQ6xlrk.js.map} +1 -1
- package/dist/esm/{types-D3W3J65M.d.ts → types-BOyFfG7D.d.ts} +42 -7
- package/dist/esm/{types-Ce9Lhvrf.d.ts → types-BRIpBy9n.d.ts} +3 -3
- package/dist/esm/{types-CFDG6lIJ.d.ts → types-OXQqX_kH.d.ts} +3 -3
- package/dist/esm/{validation-BRu06AM_.js → validation-DWe2k89s.js} +2 -2
- package/dist/esm/{validation-BRu06AM_.js.map → validation-DWe2k89s.js.map} +1 -1
- package/dist/esm/viem/index.d.ts +5 -5
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +1 -1
- package/dist/esm/web/index.js +1 -1
- package/dist/esm/wrappers-registry-BfQr2QHn.js +2 -0
- package/dist/esm/wrappers-registry-BfQr2QHn.js.map +1 -0
- package/package.json +2 -2
- package/dist/esm/base-signer-DGIEzavu.js +0 -2
- package/dist/esm/base-signer-DGIEzavu.js.map +0 -1
- package/dist/esm/chains-ByyCdrrd.js +0 -2
- package/dist/esm/chains-ByyCdrrd.js.map +0 -1
- package/dist/esm/fhevm-relayer-Cm-ZR1vP.js +0 -8
- package/dist/esm/fhevm-relayer-Cm-ZR1vP.js.map +0 -1
- package/dist/esm/relayer-CVKO9GmQ.js +0 -2
- package/dist/esm/relayer-CVKO9GmQ.js.map +0 -1
- package/dist/esm/token-BejFVO8m.js +0 -2
- package/dist/esm/wrappers-registry-BLe7PkZi.js +0 -2
- package/dist/esm/wrappers-registry-BLe7PkZi.js.map +0 -1
package/dist/cjs/chains.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={id:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`},t={id:137,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://polygon-bor-rpc.publicnode.com`,aclContractAddress:`0x6737F17e31cf26a1b62fb0362acC5a16CB156F49`,kmsContractAddress:`0x14e609595474874Dd6b6128376E336EfADfdBE37`,inputVerifierContractAddress:`0xf40BD204B035522EaAc8E5afAdc55113Acac96ca`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xc8908569868758dAF814B5a8b96bBc44D1653d54`},n={id:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`},r={id:80002,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://polygon-amoy-bor-rpc.publicnode.com`,aclContractAddress:`0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985`,kmsContractAddress:`0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041`,inputVerifierContractAddress:`0x6e5A7D8b0c645467Cba7e62D6624917085118631`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0xF486c3D4F4562760A43883e72E8D6f6Cf2EFdA94`},i={id:560048,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.hoodi.ethpandaops.io`,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,kmsContractAddress:`0x822BE20679CfAfdc352F05dEdfe12a07E912212e`,inputVerifierContractAddress:`0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`},a={id:364301,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.ingen.t-rex.network`,aclContractAddress:`0x09a4710BfBe7B557cD5CFE88BB31e9b5b85C419b`,kmsContractAddress:`0xd885DEa6a924785fCcdf9CE993FEe27EA11832e6`,inputVerifierContractAddress:`0x90f05B10db153365D8cB143EA17f5E5714D0bCD5`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x7FC3D79EF9d01fA318CF2Aa5D91dDC492383Be0F`,executorAddress:`0x1B05DE5b67b8f8363DC04E3a5996a616f11f8C7B`},o={id:97,gatewayChainId:10901,relayerUrl:``,network:`https://bsc-testnet.bnbchain.org`,aclContractAddress:`0x52470e945521E247Cb4754088a836Dc4b838AFBE`,kmsContractAddress:`0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F`,inputVerifierContractAddress:`0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC`,executorAddress:`0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54`},s={id:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},c=s,l={[e.id]:e,[t.id]:t,[n.id]:n,[r.id]:r,[i.id]:i,[a.id]:a,[o.id]:o,[s.id]:s};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return n}});
|
|
1
|
+
const e={id:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`,protocolConfigContractAddress:`0xD8236B57394f90726b26aB25D38CeAC776E1a7C4`},t={id:137,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://polygon-bor-rpc.publicnode.com`,aclContractAddress:`0x6737F17e31cf26a1b62fb0362acC5a16CB156F49`,kmsContractAddress:`0x14e609595474874Dd6b6128376E336EfADfdBE37`,inputVerifierContractAddress:`0xf40BD204B035522EaAc8E5afAdc55113Acac96ca`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xc8908569868758dAF814B5a8b96bBc44D1653d54`,protocolConfigContractAddress:`0x17f62Ab3A1Ea519703cD597410147A30Fa1a7f1e`},n={id:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`,protocolConfigContractAddress:`0x51f9AFBc89Ea792e1a21a12AB802ab58D4dbee83`},r={id:80002,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://polygon-amoy-bor-rpc.publicnode.com`,aclContractAddress:`0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985`,kmsContractAddress:`0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041`,inputVerifierContractAddress:`0x6e5A7D8b0c645467Cba7e62D6624917085118631`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0xF486c3D4F4562760A43883e72E8D6f6Cf2EFdA94`,protocolConfigContractAddress:`0x4CcF009Aba90D04f52b31fc7aDdE240578aFe10F`},i={id:560048,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.hoodi.ethpandaops.io`,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,kmsContractAddress:`0x822BE20679CfAfdc352F05dEdfe12a07E912212e`,inputVerifierContractAddress:`0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`},a={id:364301,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.ingen.t-rex.network`,aclContractAddress:`0x09a4710BfBe7B557cD5CFE88BB31e9b5b85C419b`,kmsContractAddress:`0xd885DEa6a924785fCcdf9CE993FEe27EA11832e6`,inputVerifierContractAddress:`0x90f05B10db153365D8cB143EA17f5E5714D0bCD5`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x7FC3D79EF9d01fA318CF2Aa5D91dDC492383Be0F`,executorAddress:`0x1B05DE5b67b8f8363DC04E3a5996a616f11f8C7B`},o={id:97,gatewayChainId:10901,relayerUrl:``,network:`https://bsc-testnet.bnbchain.org`,aclContractAddress:`0x52470e945521E247Cb4754088a836Dc4b838AFBE`,kmsContractAddress:`0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F`,inputVerifierContractAddress:`0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC`,executorAddress:`0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54`},s={id:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},c=s,l={[e.id]:e,[t.id]:t,[n.id]:n,[r.id]:r,[i.id]:i,[a.id]:a,[o.id]:o,[s.id]:s};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return n}});
|
|
2
2
|
//# sourceMappingURL=chains.cjs.map
|
package/dist/cjs/chains.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chains.cjs","names":[],"sources":["../../src/chains/configs.ts"],"sourcesContent":["import type { FheChain } from \"./types\";\n\n/**\n * Mainnet network configuration (chainId 1).\n */\nexport const mainnet = {\n id: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n} as const satisfies FheChain;\n\n/**\n * Polygon mainnet network configuration (chainId 137).\n */\nexport const polygon = {\n id: 137,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://polygon-bor-rpc.publicnode.com\",\n aclContractAddress: \"0x6737F17e31cf26a1b62fb0362acC5a16CB156F49\",\n kmsContractAddress: \"0x14e609595474874Dd6b6128376E336EfADfdBE37\",\n inputVerifierContractAddress: \"0xf40BD204B035522EaAc8E5afAdc55113Acac96ca\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xc8908569868758dAF814B5a8b96bBc44D1653d54\",\n} as const satisfies FheChain;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n */\nexport const sepolia = {\n id: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n} as const satisfies FheChain;\n\n/**\n * Polygon Amoy testnet network configuration (chainId 80002).\n */\nexport const polygonAmoy = {\n id: 80002,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://polygon-amoy-bor-rpc.publicnode.com\",\n aclContractAddress: \"0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985\",\n kmsContractAddress: \"0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041\",\n inputVerifierContractAddress: \"0x6e5A7D8b0c645467Cba7e62D6624917085118631\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0xF486c3D4F4562760A43883e72E8D6f6Cf2EFdA94\",\n} as const satisfies FheChain;\n\n/**\n * Hoodi testnet configuration (chainId 560048).\n *\n * Hoodi does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const hoodi = {\n id: 560048,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.hoodi.ethpandaops.io\",\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n kmsContractAddress: \"0x822BE20679CfAfdc352F05dEdfe12a07E912212e\",\n inputVerifierContractAddress: \"0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n} as const satisfies FheChain;\n\n/**\n * T-Rex InGen testnet configuration (chainId 364301).\n *\n * InGen does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const ingenTestnet = {\n id: 364301,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.ingen.t-rex.network\",\n aclContractAddress: \"0x09a4710BfBe7B557cD5CFE88BB31e9b5b85C419b\",\n kmsContractAddress: \"0xd885DEa6a924785fCcdf9CE993FEe27EA11832e6\",\n inputVerifierContractAddress: \"0x90f05B10db153365D8cB143EA17f5E5714D0bCD5\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x7FC3D79EF9d01fA318CF2Aa5D91dDC492383Be0F\",\n executorAddress: \"0x1B05DE5b67b8f8363DC04E3a5996a616f11f8C7B\",\n} as const satisfies FheChain;\n\n/**\n * BNB Smart Chain testnet configuration (chainId 97, Chapel).\n *\n * BSC testnet does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const bscTestnet = {\n id: 97,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://bsc-testnet.bnbchain.org\",\n aclContractAddress: \"0x52470e945521E247Cb4754088a836Dc4b838AFBE\",\n kmsContractAddress: \"0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F\",\n inputVerifierContractAddress: \"0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC\",\n executorAddress: \"0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54\",\n} as const satisfies FheChain;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n */\nexport const hardhat = {\n id: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} as const satisfies FheChain;\n\n/** Alias for {@link hardhat}. */\nexport const anvil = hardhat;\n\n/**\n * Built-in chain configurations keyed by chain ID.\n */\nexport const chains: Record<number, FheChain> = {\n [mainnet.id]: mainnet,\n [polygon.id]: polygon,\n [sepolia.id]: sepolia,\n [polygonAmoy.id]: polygonAmoy,\n [hoodi.id]: hoodi,\n [ingenTestnet.id]: ingenTestnet,\n [bscTestnet.id]: bscTestnet,\n [hardhat.id]: hardhat,\n} as const;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"chains.cjs","names":[],"sources":["../../src/chains/configs.ts"],"sourcesContent":["import type { FheChain } from \"./types\";\n\n// `protocolConfigContractAddress` (required for V2/wildcard permit signing to\n// succeed) is wired in below for every built-in config with a deployed\n// `ProtocolConfig` contract. `hoodi`, `ingenTestnet`, `bscTestnet`, and\n// `hardhat`/`anvil` don't have one deployed yet, so they omit it — V1 permits\n// don't need it at all, and V2/wildcard permits simply aren't usable on those\n// presets until one exists. Pass it in a custom `FheChain` for any other\n// network whose deployed `ProtocolConfig` address you already know.\n\n/**\n * Mainnet network configuration (chainId 1).\n */\nexport const mainnet = {\n id: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n protocolConfigContractAddress: \"0xD8236B57394f90726b26aB25D38CeAC776E1a7C4\",\n} as const satisfies FheChain;\n\n/**\n * Polygon mainnet network configuration (chainId 137).\n */\nexport const polygon = {\n id: 137,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://polygon-bor-rpc.publicnode.com\",\n aclContractAddress: \"0x6737F17e31cf26a1b62fb0362acC5a16CB156F49\",\n kmsContractAddress: \"0x14e609595474874Dd6b6128376E336EfADfdBE37\",\n inputVerifierContractAddress: \"0xf40BD204B035522EaAc8E5afAdc55113Acac96ca\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xc8908569868758dAF814B5a8b96bBc44D1653d54\",\n protocolConfigContractAddress: \"0x17f62Ab3A1Ea519703cD597410147A30Fa1a7f1e\",\n} as const satisfies FheChain;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n */\nexport const sepolia = {\n id: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n protocolConfigContractAddress: \"0x51f9AFBc89Ea792e1a21a12AB802ab58D4dbee83\",\n} as const satisfies FheChain;\n\n/**\n * Polygon Amoy testnet network configuration (chainId 80002).\n */\nexport const polygonAmoy = {\n id: 80002,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://polygon-amoy-bor-rpc.publicnode.com\",\n aclContractAddress: \"0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985\",\n kmsContractAddress: \"0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041\",\n inputVerifierContractAddress: \"0x6e5A7D8b0c645467Cba7e62D6624917085118631\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0xF486c3D4F4562760A43883e72E8D6f6Cf2EFdA94\",\n protocolConfigContractAddress: \"0x4CcF009Aba90D04f52b31fc7aDdE240578aFe10F\",\n} as const satisfies FheChain;\n\n/**\n * Hoodi testnet configuration (chainId 560048).\n *\n * Hoodi does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const hoodi = {\n id: 560048,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.hoodi.ethpandaops.io\",\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n kmsContractAddress: \"0x822BE20679CfAfdc352F05dEdfe12a07E912212e\",\n inputVerifierContractAddress: \"0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n} as const satisfies FheChain;\n\n/**\n * T-Rex InGen testnet configuration (chainId 364301).\n *\n * InGen does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const ingenTestnet = {\n id: 364301,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.ingen.t-rex.network\",\n aclContractAddress: \"0x09a4710BfBe7B557cD5CFE88BB31e9b5b85C419b\",\n kmsContractAddress: \"0xd885DEa6a924785fCcdf9CE993FEe27EA11832e6\",\n inputVerifierContractAddress: \"0x90f05B10db153365D8cB143EA17f5E5714D0bCD5\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x7FC3D79EF9d01fA318CF2Aa5D91dDC492383Be0F\",\n executorAddress: \"0x1B05DE5b67b8f8363DC04E3a5996a616f11f8C7B\",\n} as const satisfies FheChain;\n\n/**\n * BNB Smart Chain testnet configuration (chainId 97, Chapel).\n *\n * BSC testnet does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const bscTestnet = {\n id: 97,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://bsc-testnet.bnbchain.org\",\n aclContractAddress: \"0x52470e945521E247Cb4754088a836Dc4b838AFBE\",\n kmsContractAddress: \"0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F\",\n inputVerifierContractAddress: \"0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC\",\n executorAddress: \"0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54\",\n} as const satisfies FheChain;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n */\nexport const hardhat = {\n id: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} as const satisfies FheChain;\n\n/** Alias for {@link hardhat}. */\nexport const anvil = hardhat;\n\n/**\n * Built-in chain configurations keyed by chain ID.\n */\nexport const chains: Record<number, FheChain> = {\n [mainnet.id]: mainnet,\n [polygon.id]: polygon,\n [sepolia.id]: sepolia,\n [polygonAmoy.id]: polygonAmoy,\n [hoodi.id]: hoodi,\n [ingenTestnet.id]: ingenTestnet,\n [bscTestnet.id]: bscTestnet,\n [hardhat.id]: hardhat,\n} as const;\n"],"mappings":"AAaA,MAAa,EAAU,CACrB,GAAI,EACJ,eAAgB,OAChB,WAAY,mCACZ,QAAS,sCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAi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CACpC,0CAA2C,6CAC3C,gBAAiB,IAAA,GACjB,gBAAiB,4CACnB,EAGa,EAAQ,EAKR,EAAmC,EAC7C,EAAQ,IAAK,GACb,EAAQ,IAAK,GACb,EAAQ,IAAK,GACb,EAAY,IAAK,GACjB,EAAM,IAAK,GACX,EAAa,IAAK,GAClB,EAAW,IAAK,GAChB,EAAQ,IAAK,CAChB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../relayer.cjs"),t=require("../wrappers-registry.cjs"),n=require("../base-signer.cjs"),r=require("../assertions.cjs"),i=require("../eip1193-subscribe.cjs");let a=require("viem"),o=require("ethers");function s(e){return{to:e.address,data:(0,a.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function c(e,t){let n=await e.call(s(t));if(!(0,a.isHex)(n))throw TypeError(`Expected hex string, got: ${n}`);return(0,a.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:n})}async function l(e,t){let n=await e.sendTransaction(s(t));if(!(0,a.isHex)(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function u(e,n,r){return c(e,t.S(n,r))}function d(e,n){return c(e,t.N(n))}function f(e,n,r){return c(e,t.m(n,r))}function p(e,n,r,i,a){return l(e,t.T(n,r,i,a))}function m(e,n,r,i,a,o){return l(e,t.P(n,r,i,a,o))}function h(e,n,r,i,a){return l(e,t.F(n,r,i,a))}function g(e,n,r,i,a){return l(e,t.O(n,r,i,a))}function _(e,n,r,i){return l(e,t.M(n,r,i))}function v(e,n,r,i){return l(e,t.L(n,r,i))}function y(e,n){return c(e,t.i(n))}function b(e,n){return c(e,t.a(n))}function x(e,n,r,i){return c(e,t.o(n,r,i))}function S(e,n,r){return c(e,t.r(n,r))}function C(e,n,r){return c(e,t.t(n,r))}function w(e,n,r){return c(e,t.n(n,r))}function T(e,n,r){return c(e,t.s(n,r))}var E=class{#e;constructor(e){`ethereum`in e?this.#e=new o.BrowserProvider(e.ethereum):this.#e=e.provider}async getChainId(){let e=await this.#e.getNetwork();return Number(e.chainId)}async readContract(e){return c(this.#e,{address:e.address,abi:e.abi,functionName:e.functionName,args:e.args})}async getBlockTimestamp(){let t=await this.#e.getBlock(`latest`);if(!t)throw new e.t(`EthersProvider.getBlockTimestamp: failed to fetch latest block`);if(t.timestamp===null)throw new e.t(`EthersProvider.getBlockTimestamp: latest block has no timestamp`);return BigInt(t.timestamp)}async waitForTransactionReceipt(e){let n=await this.#e.waitForTransaction(e);if(!n)throw new t.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../relayer.cjs"),t=require("../wrappers-registry.cjs"),n=require("../base-signer.cjs"),r=require("../assertions.cjs"),i=require("../eip1193-subscribe.cjs");let a=require("viem"),o=require("ethers");function s(e){return{to:e.address,data:(0,a.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function c(e,t){let n=await e.call(s(t));if(!(0,a.isHex)(n))throw TypeError(`Expected hex string, got: ${n}`);return(0,a.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:n})}async function l(e,t){let n=await e.sendTransaction(s(t));if(!(0,a.isHex)(n.hash))throw TypeError(`Expected hex string, got: ${n.hash}`);return n.hash}function u(e,n,r){return c(e,t.S(n,r))}function d(e,n){return c(e,t.N(n))}function f(e,n,r){return c(e,t.m(n,r))}function p(e,n,r,i,a){return l(e,t.T(n,r,i,a))}function m(e,n,r,i,a,o){return l(e,t.P(n,r,i,a,o))}function h(e,n,r,i,a){return l(e,t.F(n,r,i,a))}function g(e,n,r,i,a){return l(e,t.O(n,r,i,a))}function _(e,n,r,i){return l(e,t.M(n,r,i))}function v(e,n,r,i){return l(e,t.L(n,r,i))}function y(e,n){return c(e,t.i(n))}function b(e,n){return c(e,t.a(n))}function x(e,n,r,i){return c(e,t.o(n,r,i))}function S(e,n,r){return c(e,t.r(n,r))}function C(e,n,r){return c(e,t.t(n,r))}function w(e,n,r){return c(e,t.n(n,r))}function T(e,n,r){return c(e,t.s(n,r))}var E=class{#e;constructor(e){`ethereum`in e?this.#e=new o.BrowserProvider(e.ethereum):this.#e=e.provider}async getChainId(){let e=await this.#e.getNetwork();return Number(e.chainId)}async readContract(e){return c(this.#e,{address:e.address,abi:e.abi,functionName:e.functionName,args:e.args})}async getBlockTimestamp(){let t=await this.#e.getBlock(`latest`);if(!t)throw new e.t(`EthersProvider.getBlockTimestamp: failed to fetch latest block`);if(t.timestamp===null)throw new e.t(`EthersProvider.getBlockTimestamp: latest block has no timestamp`);return BigInt(t.timestamp)}async waitForTransactionReceipt(e){let n=await this.#e.waitForTransaction(e);if(!n)throw new t.it(`EthersProvider.waitForTransactionReceipt: no receipt found for tx ${e}. The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.`);return{logs:n.logs.map(e=>({address:e.address,topics:e.topics.filter(e=>e!==null),data:e.data}))}}async prepareTransaction(n){let{from:i,calldata:a}=n,s=new o.ethers.Interface(a.abi),c=[];s.forEachFunction(e=>{e.name===a.functionName&&c.push(e)});let l=a.args.length,u=c.length===1?c[0]:c.find(e=>e.inputs.length===l);if(!u)throw Error(`Function ${a.functionName}(${l} args) not found in ABI`);let d=s.encodeFunctionData(u,a.args);r.n(d,`data`);let f=a.value??0n,p=this.#e.getNetwork(),m=n.nonce===void 0?this.#e.getTransactionCount(i,`pending`):Promise.resolve(n.nonce),h=n.gasLimit===void 0?a.gas??this.#e.estimateGas({from:i,to:a.address,data:d,value:f}).catch(e=>{throw new t.it(`EthersProvider.prepareTransaction: gas estimation reverted for ${a.functionName} on ${a.address}`,{cause:e})}):Promise.resolve(n.gasLimit),g=n.fees??this.#e.getFeeData(),[_,v,y,b]=await Promise.all([p,m,h,g]),x=b.maxFeePerGas,S=b.maxPriorityFeePerGas;if(x===null||S===null)throw new e.t(`EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). The connected chain may not support EIP-1559 type-2 transactions.`);return o.Transaction.from({type:2,chainId:Number(_.chainId),nonce:v,to:a.address,data:d,value:f,gasLimit:y,maxFeePerGas:x,maxPriorityFeePerGas:S}).unsignedSerialized}},D=class extends n.t{#e;#t;#n;#r;#i;constructor(e){super(),`ethereum`in e?(this.#e=new o.BrowserProvider(e.ethereum),this.#n=e.ethereum,this.#r=i.t({provider:e.ethereum,getInitialWalletAccount:()=>this.#l(),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}})):(this.#t=e.signer,this.#r=()=>{},t.U(`refresh wallet account`,async()=>{await this.refreshWalletAccount()}))}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n&&!this.walletAccount.isReady())throw new t.tt(e);if(!n)throw new t.nt(e);return n}refreshWalletAccount(){return this.#n?this.#c():this.#t?this.#s(this.#t):Promise.resolve(void 0)}onDispose(){this.#r()}async#a(){if(this.#t)return this.#t;if(!this.#e)throw new t.$(`resolveSigner`);return this.#e.getSigner()}async#o(e){let t=e.provider;if(!t)return;let[n,r]=await Promise.all([e.getAddress(),t.getNetwork()]);return{address:(0,a.getAddress)(n),chainId:Number(r.chainId)}}async signTypedData(e){let t=await this.#a(),{domain:n,types:r,message:i}=e,{EIP712Domain:o,...s}=r,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(n,c,i);if(!(0,a.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#a(),n=new o.Contract(e.address,e.abi,t),r={};e.value!==void 0&&(r.value=e.value),e.gas!==void 0&&(r.gasLimit=e.gas);let i=await n.getFunction(e.functionName)(...e.args,r);if(!(0,a.isHex)(i.hash))throw TypeError(`Expected hex string, got: ${i.hash}`);return i.hash}async#s(e){return this.#i??=this.#o(e).then(e=>(this.walletAccount.setSnapshot(e),e)).finally(()=>{this.#i=void 0}),this.#i}async#c(){let e=await this.#l();return this.walletAccount.setSnapshot(e),e}async#l(){let e=this.#n;if(!e)return;let[t,n]=await Promise.all([e.request({method:`eth_accounts`}),e.request({method:`eth_chainId`})]);if(!Array.isArray(t)||typeof t[0]!=`string`)return;let r=Number(n);if(!(!Number.isSafeInteger(r)||r<=0))return{address:(0,a.getAddress)(t[0]),chainId:r}}};function O(e){if(`signer`in e&&e.signer){let t=new D({signer:e.signer});if(!e.signer.provider)throw Error(`createConfig requires a Signer with an attached provider for chain reads`);return n.i(t,new E({provider:e.signer.provider}),e)}return n.i(new D({ethereum:e.ethereum}),`provider`in e&&e.provider?new E({provider:e.provider}):new E({ethereum:e.ethereum}),e)}exports.BaseSigner=n.t,exports.EthersProvider=E,exports.EthersSigner=D,Object.defineProperty(exports,"ProviderRpcError",{enumerable:!0,get:function(){return a.ProviderRpcError}}),exports.ZamaSDKEvents=t.Z,exports.createConfig=O,exports.readConfidentialBalanceOfContract=u,exports.readConfidentialTokenAddressContract=C,exports.readIsConfidentialTokenValidContract=T,exports.readSupportsInterfaceContract=f,exports.readTokenAddressContract=w,exports.readTokenPairContract=S,exports.readTokenPairsContract=y,exports.readTokenPairsLengthContract=b,exports.readTokenPairsSliceContract=x,exports.readUnderlyingTokenContract=d,exports.writeConfidentialTransferContract=p,exports.writeFinalizeUnwrapContract=g,exports.writeSetOperatorContract=_,exports.writeUnwrapContract=m,exports.writeUnwrapFromBalanceContract=h,exports.writeWrapContract=v;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract","#readProvider","BrowserProvider","ConfigurationError","TransactionRevertedError","Transaction","BaseSigner","#browserProvider","#directSigner","#eip1193","#unsubscribeProvider","BrowserProvider","eip1193Subscribe","#loadBrowserWalletAccount","swallow","WalletAccountNotReadyError","WalletNotConnectedError","#refreshFromEthereum","#refreshFromSigner","#resolveSigner","SignerNotConfiguredError","#walletAccountFromSigner","Contract","#accountPromise","buildZamaConfig"],"sources":["../../../src/ethers/contracts.ts","../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts"],"sourcesContent":["import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { EncryptedValue } from \"../relayer/types\";\n\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\n/** Minimal transaction request accepted by the ethers contract helpers. */\nexport interface EthersTransactionRequest {\n /** Target contract address. */\n to: Address;\n /** ABI-encoded call data. */\n data: Hex;\n /** Optional gas limit for the transaction. */\n gasLimit?: bigint;\n /** Optional native-token value to send with the call, in wei. */\n value?: bigint;\n}\n\n/** Minimal transaction response returned by an {@link EthersTransactionSigner}. */\nexport interface EthersTransactionResponse {\n /** Hash of the submitted transaction. */\n hash: string;\n}\n\n/** Minimal read-only ethers provider shape used by the read contract helpers. */\nexport interface EthersCallProvider {\n /** Performs an `eth_call` and resolves to the raw hex return data. */\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\n/** Minimal ethers signer shape used by the write contract helpers. */\nexport interface EthersTransactionSigner extends EthersCallProvider {\n /** Signs and broadcasts a transaction, resolving to the transaction response. */\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\n/**\n * Performs an `eth_call` through an ethers provider and decodes the result with viem, so every\n * ethers-backed read — the generic {@link EthersProvider.readContract} and the pre-built\n * `readXxxContract` helpers alike — produces viem-identical shapes (small ints as `number`, named\n * tuples as keyed objects, empty output as `undefined`). ethers is the transport only; viem owns\n * encoding and decoding.\n *\n * @internal\n */\nexport async function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via an ethers provider. */\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via an ethers provider. */\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via an ethers provider. */\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via an ethers signer. */\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(\n signer,\n confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n );\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via an ethers signer. */\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via an ethers signer. */\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via an ethers signer. */\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n );\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via an ethers signer. */\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via an ethers signer. */\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via an ethers provider. */\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via an ethers provider. */\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via an ethers provider. */\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via an ethers provider. */\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via an ethers provider. */\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via an ethers provider. */\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via an ethers provider. */\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n","import { ethers, BrowserProvider, Transaction } from \"ethers\";\nimport type {\n Abi,\n Address,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport { ConfigurationError, TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { assertHex } from \"../utils/assertions\";\nimport { ethersRead } from \"./contracts\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n /**\n * Execute a read-only call and return the decoded result.\n *\n * ethers is the transport only: the call goes out over `provider.call`, and viem does the\n * encoding and decoding (via {@link ethersRead}). That keeps the result identical to\n * `ViemProvider` — the return-type contract both providers implement — rather than re-deriving\n * viem's decoding rules (small ints as `number`, named tuples as keyed objects, empty output as\n * `undefined`) from ethers' own decoded values.\n */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return ethersRead(this.#readProvider, {\n address: config.address,\n abi: config.abi as readonly unknown[],\n functionName: config.functionName,\n args: config.args as readonly unknown[],\n });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: failed to fetch latest block\",\n );\n }\n if (block.timestamp === null) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: latest block has no timestamp\",\n );\n }\n return BigInt(block.timestamp);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new TransactionRevertedError(\n `EthersProvider.waitForTransactionReceipt: no receipt found for tx ${hash}. ` +\n \"The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.\",\n );\n }\n return {\n logs: receipt.logs.map((log) => ({\n address: log.address as Hex,\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const iface = new ethers.Interface(calldata.abi as unknown as ethers.InterfaceAbi);\n // Resolve overloaded ABI entries by name + arity. ethers'\n // `getFunction(key, values)` allows for an \"overrides\" object as the\n // last arg, so a 2-arg fragment still matches a 3-value call and\n // overloads like ERC-7984 `confidentialTransfer(address,bytes32)` vs\n // `confidentialTransfer(address,bytes32,bytes)` aren't disambiguated.\n const candidates: ethers.FunctionFragment[] = [];\n iface.forEachFunction((frag) => {\n if (frag.name === calldata.functionName) {\n candidates.push(frag);\n }\n });\n const argLength = (calldata.args as readonly unknown[]).length;\n const fragment =\n candidates.length === 1\n ? candidates[0]\n : candidates.find((frag) => frag.inputs.length === argLength);\n if (!fragment) {\n throw new Error(`Function ${calldata.functionName}(${argLength} args) not found in ABI`);\n }\n const data = iface.encodeFunctionData(fragment, calldata.args as readonly unknown[]);\n assertHex(data, \"data\");\n\n const value = calldata.value ?? 0n;\n // Wrap estimateGas — pre-flight revert is the high-value failure mode.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const networkPromise = this.#readProvider.getNetwork();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#readProvider.getTransactionCount(from, \"pending\");\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#readProvider\n .estimateGas({ from, to: calldata.address, data, value })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `EthersProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName as string} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feeDataPromise = args.fees ?? this.#readProvider.getFeeData();\n const [network, nonce, gasLimit, feeData] = await Promise.all([\n networkPromise,\n noncePromise,\n gasPromise,\n feeDataPromise,\n ]);\n const maxFeePerGas = feeData.maxFeePerGas;\n const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;\n if (maxFeePerGas === null || maxPriorityFeePerGas === null) {\n throw new ConfigurationError(\n \"EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). \" +\n \"The connected chain may not support EIP-1559 type-2 transactions.\",\n );\n }\n const tx = Transaction.from({\n type: 2,\n chainId: Number(network.chainId),\n nonce,\n to: calldata.address,\n data,\n value,\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n });\n return tx.unsignedSerialized as Hex;\n }\n}\n","import {\n BrowserProvider,\n Contract,\n type InterfaceAbi,\n type Signer,\n type TypedDataDomain,\n} from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { swallow } from \"../utils\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and wallet events update `walletAccount`.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * The initial wallet account is discovered asynchronously and emitted through\n * `walletAccount` once available.\n *\n * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner extends BaseSigner {\n readonly #browserProvider?: BrowserProvider;\n readonly #directSigner?: Signer;\n readonly #eip1193?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n #accountPromise: Promise<WalletAccount | undefined> | undefined;\n\n constructor(config: EthersSignerConfig) {\n super();\n if (\"ethereum\" in config) {\n this.#browserProvider = new BrowserProvider(config.ethereum);\n this.#eip1193 = config.ethereum;\n this.#unsubscribeProvider = eip1193Subscribe({\n provider: config.ethereum,\n getInitialWalletAccount: () => this.#loadBrowserWalletAccount(),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n } else {\n this.#directSigner = config.signer;\n this.#unsubscribeProvider = () => {};\n // The signer is constructed before `createConfig`, so it cannot reach the\n // SDK-wide logger; this best-effort refresh stays silent. A failed refresh\n // still surfaces via the typed WalletAccountNotReadyError on next use.\n void swallow(\"refresh wallet account\", async () => {\n await this.refreshWalletAccount();\n });\n }\n }\n\n /**\n * Return the connected wallet account, or throw {@link WalletAccountNotReadyError}\n * while the initial async lookup is pending, or {@link WalletNotConnectedError}\n * when no wallet is connected.\n */\n override requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account && !this.walletAccount.isReady()) {\n throw new WalletAccountNotReadyError(operation);\n }\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n /** Re-fetch the wallet account from the provider or signer and update `walletAccount`. */\n refreshWalletAccount(): Promise<WalletAccount | undefined> {\n if (this.#eip1193) {\n return this.#refreshFromEthereum();\n }\n if (this.#directSigner) {\n return this.#refreshFromSigner(this.#directSigner);\n }\n return Promise.resolve(undefined);\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n\n async #resolveSigner(): Promise<Signer> {\n if (this.#directSigner) {\n return this.#directSigner;\n }\n if (!this.#browserProvider) {\n throw new SignerNotConfiguredError(\"resolveSigner\");\n }\n return this.#browserProvider.getSigner();\n }\n\n async #walletAccountFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n return { address: getAddress(address), chainId: Number(network.chainId) };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([name, fields]) => [name, [...fields]]),\n );\n const sig = await signer.signTypedData(domain as TypedDataDomain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const contract = new Contract(config.address, config.abi as InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const fn = contract.getFunction(config.functionName);\n const tx = await fn(...(config.args as readonly unknown[]), overrides);\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async #refreshFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n this.#accountPromise ??= this.#walletAccountFromSigner(signer)\n .then((account) => {\n this.walletAccount.setSnapshot(account);\n return account;\n })\n .finally(() => {\n this.#accountPromise = undefined;\n });\n return this.#accountPromise;\n }\n\n async #refreshFromEthereum(): Promise<WalletAccount | undefined> {\n const account = await this.#loadBrowserWalletAccount();\n this.walletAccount.setSnapshot(account);\n return account;\n }\n\n async #loadBrowserWalletAccount(): Promise<WalletAccount | undefined> {\n const ethereum = this.#eip1193;\n if (!ethereum) {\n return undefined;\n }\n const [accounts, chainIdValue] = await Promise.all([\n ethereum.request({ method: \"eth_accounts\" }),\n ethereum.request({ method: \"eth_chainId\" }),\n ]);\n if (!Array.isArray(accounts) || typeof accounts[0] !== \"string\") {\n return undefined;\n }\n const chainId = Number(chainIdValue);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n return undefined;\n }\n return { address: getAddress(accounts[0]), chainId };\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n"],"mappings":"0RAqEA,SAAS,EAAqB,EAA4D,CACxF,MAAO,CACL,GAAI,EAAO,QACX,MAAA,EAAA,EAAA,mBAAA,CAAyB,CACvB,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,KAAM,EAAO,IACf,CAAC,EACD,GAAI,EAAO,MAAQ,IAA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AAO,CAAE,SAAA,EAAA,EAAA,WAAA,CAAoB,EAAS,EAAE,EAAG,SAAQ,CACrD,CACF,ECxMA,SAAgB,EACd,EACY,CACZ,GAAI,WAAY,GAAU,EAAO,OAAQ,CACvC,IAAM,EAAS,IAAI,EAAa,CAAE,OAAQ,EAAO,MAAO,CAAC,EACzD,GAAI,CAAC,EAAO,OAAO,SACjB,MAAU,MAAM,0EAA0E,EAG5F,OAAOe,EAAAA,EAAgB,EAAQ,IADV,EAAe,CAAE,SAAU,EAAO,OAAO,QAAS,CACjC,EAAG,CAAM,CACjD,CAOA,OAAOA,EAAAA,EAAgB,IALJ,EAAa,CAAE,SAAU,EAAO,QAAS,CAKhC,EAH1B,aAAc,GAAU,EAAO,SAC3B,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EAChD,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EACb,CAAM,CACjD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract","#readProvider","BrowserProvider","ConfigurationError","TransactionRevertedError","Transaction","BaseSigner","#browserProvider","#directSigner","#eip1193","#unsubscribeProvider","BrowserProvider","eip1193Subscribe","#loadBrowserWalletAccount","swallow","WalletAccountNotReadyError","WalletNotConnectedError","#refreshFromEthereum","#refreshFromSigner","#resolveSigner","SignerNotConfiguredError","#walletAccountFromSigner","Contract","#accountPromise","buildZamaConfig"],"sources":["../../../src/ethers/contracts.ts","../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts"],"sourcesContent":["import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { EncryptedValue } from \"../relayer/types\";\n\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\n/** Minimal transaction request accepted by the ethers contract helpers. */\nexport interface EthersTransactionRequest {\n /** Target contract address. */\n to: Address;\n /** ABI-encoded call data. */\n data: Hex;\n /** Optional gas limit for the transaction. */\n gasLimit?: bigint;\n /** Optional native-token value to send with the call, in wei. */\n value?: bigint;\n}\n\n/** Minimal transaction response returned by an {@link EthersTransactionSigner}. */\nexport interface EthersTransactionResponse {\n /** Hash of the submitted transaction. */\n hash: string;\n}\n\n/** Minimal read-only ethers provider shape used by the read contract helpers. */\nexport interface EthersCallProvider {\n /** Performs an `eth_call` and resolves to the raw hex return data. */\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\n/** Minimal ethers signer shape used by the write contract helpers. */\nexport interface EthersTransactionSigner extends EthersCallProvider {\n /** Signs and broadcasts a transaction, resolving to the transaction response. */\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\n/**\n * Performs an `eth_call` through an ethers provider and decodes the result with viem, so every\n * ethers-backed read — the generic {@link EthersProvider.readContract} and the pre-built\n * `readXxxContract` helpers alike — produces viem-identical shapes (small ints as `number`, named\n * tuples as keyed objects, empty output as `undefined`). ethers is the transport only; viem owns\n * encoding and decoding.\n *\n * @internal\n */\nexport async function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via an ethers provider. */\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via an ethers provider. */\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via an ethers provider. */\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via an ethers signer. */\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(\n signer,\n confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n );\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via an ethers signer. */\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via an ethers signer. */\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via an ethers signer. */\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n );\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via an ethers signer. */\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via an ethers signer. */\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via an ethers provider. */\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via an ethers provider. */\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via an ethers provider. */\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via an ethers provider. */\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via an ethers provider. */\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via an ethers provider. */\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via an ethers provider. */\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n","import { ethers, BrowserProvider, Transaction } from \"ethers\";\nimport type {\n Abi,\n Address,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport { ConfigurationError, TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { assertHex } from \"../utils/assertions\";\nimport { ethersRead } from \"./contracts\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n /**\n * Execute a read-only call and return the decoded result.\n *\n * ethers is the transport only: the call goes out over `provider.call`, and viem does the\n * encoding and decoding (via {@link ethersRead}). That keeps the result identical to\n * `ViemProvider` — the return-type contract both providers implement — rather than re-deriving\n * viem's decoding rules (small ints as `number`, named tuples as keyed objects, empty output as\n * `undefined`) from ethers' own decoded values.\n */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return ethersRead(this.#readProvider, {\n address: config.address,\n abi: config.abi as readonly unknown[],\n functionName: config.functionName,\n args: config.args as readonly unknown[],\n });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: failed to fetch latest block\",\n );\n }\n if (block.timestamp === null) {\n throw new ConfigurationError(\n \"EthersProvider.getBlockTimestamp: latest block has no timestamp\",\n );\n }\n return BigInt(block.timestamp);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new TransactionRevertedError(\n `EthersProvider.waitForTransactionReceipt: no receipt found for tx ${hash}. ` +\n \"The transaction may have been dropped from the mempool, or the RPC's wait timeout elapsed.\",\n );\n }\n return {\n logs: receipt.logs.map((log) => ({\n address: log.address as Hex,\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const iface = new ethers.Interface(calldata.abi as unknown as ethers.InterfaceAbi);\n // Resolve overloaded ABI entries by name + arity. ethers'\n // `getFunction(key, values)` allows for an \"overrides\" object as the\n // last arg, so a 2-arg fragment still matches a 3-value call and\n // overloads like ERC-7984 `confidentialTransfer(address,bytes32)` vs\n // `confidentialTransfer(address,bytes32,bytes)` aren't disambiguated.\n const candidates: ethers.FunctionFragment[] = [];\n iface.forEachFunction((frag) => {\n if (frag.name === calldata.functionName) {\n candidates.push(frag);\n }\n });\n const argLength = (calldata.args as readonly unknown[]).length;\n const fragment =\n candidates.length === 1\n ? candidates[0]\n : candidates.find((frag) => frag.inputs.length === argLength);\n if (!fragment) {\n throw new Error(`Function ${calldata.functionName}(${argLength} args) not found in ABI`);\n }\n const data = iface.encodeFunctionData(fragment, calldata.args as readonly unknown[]);\n assertHex(data, \"data\");\n\n const value = calldata.value ?? 0n;\n // Wrap estimateGas — pre-flight revert is the high-value failure mode.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const networkPromise = this.#readProvider.getNetwork();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#readProvider.getTransactionCount(from, \"pending\");\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#readProvider\n .estimateGas({ from, to: calldata.address, data, value })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `EthersProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName as string} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feeDataPromise = args.fees ?? this.#readProvider.getFeeData();\n const [network, nonce, gasLimit, feeData] = await Promise.all([\n networkPromise,\n noncePromise,\n gasPromise,\n feeDataPromise,\n ]);\n const maxFeePerGas = feeData.maxFeePerGas;\n const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;\n if (maxFeePerGas === null || maxPriorityFeePerGas === null) {\n throw new ConfigurationError(\n \"EthersProvider.prepareTransaction: EIP-1559 fee data unavailable (provider returned null maxFeePerGas). \" +\n \"The connected chain may not support EIP-1559 type-2 transactions.\",\n );\n }\n const tx = Transaction.from({\n type: 2,\n chainId: Number(network.chainId),\n nonce,\n to: calldata.address,\n data,\n value,\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n });\n return tx.unsignedSerialized as Hex;\n }\n}\n","import {\n BrowserProvider,\n Contract,\n type InterfaceAbi,\n type Signer,\n type TypedDataDomain,\n} from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { swallow } from \"../utils\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and wallet events update `walletAccount`.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * The initial wallet account is discovered asynchronously and emitted through\n * `walletAccount` once available.\n *\n * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner extends BaseSigner {\n readonly #browserProvider?: BrowserProvider;\n readonly #directSigner?: Signer;\n readonly #eip1193?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n #accountPromise: Promise<WalletAccount | undefined> | undefined;\n\n constructor(config: EthersSignerConfig) {\n super();\n if (\"ethereum\" in config) {\n this.#browserProvider = new BrowserProvider(config.ethereum);\n this.#eip1193 = config.ethereum;\n this.#unsubscribeProvider = eip1193Subscribe({\n provider: config.ethereum,\n getInitialWalletAccount: () => this.#loadBrowserWalletAccount(),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n } else {\n this.#directSigner = config.signer;\n this.#unsubscribeProvider = () => {};\n // The signer is constructed before `createConfig`, so it cannot reach the\n // SDK-wide logger; this best-effort refresh stays silent. A failed refresh\n // still surfaces via the typed WalletAccountNotReadyError on next use.\n void swallow(\"refresh wallet account\", async () => {\n await this.refreshWalletAccount();\n });\n }\n }\n\n /**\n * Return the connected wallet account, or throw {@link WalletAccountNotReadyError}\n * while the initial async lookup is pending, or {@link WalletNotConnectedError}\n * when no wallet is connected.\n */\n override requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account && !this.walletAccount.isReady()) {\n throw new WalletAccountNotReadyError(operation);\n }\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n /** Re-fetch the wallet account from the provider or signer and update `walletAccount`. */\n refreshWalletAccount(): Promise<WalletAccount | undefined> {\n if (this.#eip1193) {\n return this.#refreshFromEthereum();\n }\n if (this.#directSigner) {\n return this.#refreshFromSigner(this.#directSigner);\n }\n return Promise.resolve(undefined);\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n\n async #resolveSigner(): Promise<Signer> {\n if (this.#directSigner) {\n return this.#directSigner;\n }\n if (!this.#browserProvider) {\n throw new SignerNotConfiguredError(\"resolveSigner\");\n }\n return this.#browserProvider.getSigner();\n }\n\n async #walletAccountFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n return { address: getAddress(address), chainId: Number(network.chainId) };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([name, fields]) => [name, [...fields]]),\n );\n const sig = await signer.signTypedData(domain as TypedDataDomain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const contract = new Contract(config.address, config.abi as InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const fn = contract.getFunction(config.functionName);\n const tx = await fn(...(config.args as readonly unknown[]), overrides);\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async #refreshFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n this.#accountPromise ??= this.#walletAccountFromSigner(signer)\n .then((account) => {\n this.walletAccount.setSnapshot(account);\n return account;\n })\n .finally(() => {\n this.#accountPromise = undefined;\n });\n return this.#accountPromise;\n }\n\n async #refreshFromEthereum(): Promise<WalletAccount | undefined> {\n const account = await this.#loadBrowserWalletAccount();\n this.walletAccount.setSnapshot(account);\n return account;\n }\n\n async #loadBrowserWalletAccount(): Promise<WalletAccount | undefined> {\n const ethereum = this.#eip1193;\n if (!ethereum) {\n return undefined;\n }\n const [accounts, chainIdValue] = await Promise.all([\n ethereum.request({ method: \"eth_accounts\" }),\n ethereum.request({ method: \"eth_chainId\" }),\n ]);\n if (!Array.isArray(accounts) || typeof accounts[0] !== \"string\") {\n return undefined;\n }\n const chainId = Number(chainIdValue);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n return undefined;\n }\n return { address: getAddress(accounts[0]), chainId };\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n"],"mappings":"0RAqEA,SAAS,EAAqB,EAA4D,CACxF,MAAO,CACL,GAAI,EAAO,QACX,MAAA,EAAA,EAAA,mBAAA,CAAyB,CACvB,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,KAAM,EAAO,IACf,CAAC,EACD,GAAI,EAAO,MAAQ,IAAA,GAAuC,CAAC,EAA5B,CAAE,SAAU,EAAO,GAAI,EACtD,GAAI,EAAO,QAAU,IAAA,GAAsC,CAAC,EAA3B,CAAE,MAAO,EAAO,KAAM,CACzD,CACF,CAWA,eAAsB,EACpB,EACA,EACY,CACZ,IAAM,EAAO,MAAM,EAAS,KAAK,EAAqB,CAAM,CAAC,EAC7D,GAAI,EAAA,EAAA,EAAA,MAAA,CAAO,CAAI,EACb,MAAU,UAAU,6BAA6B,GAAM,EAEzD,OAAA,EAAA,EAAA,qBAAA,CAA4B,CAC1B,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,MACF,CAAC,CACH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Aa,CAAE,SAAU,EAAO,QAAS,CAKhC,EAH1B,aAAc,GAAU,EAAO,SAC3B,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EAChD,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EACb,CAAM,CACjD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=require("./relayer.cjs"),n=require("./encryption.cjs"),r=require("./applied-runtime.cjs");let i=require("viem"),a=require("@fhevm/sdk/actions/base"),o=require("@fhevm/sdk/viem"),s=require("@fhevm/sdk/viem/cleartext");function c(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}
|
|
1
|
+
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=require("./relayer.cjs"),n=require("./encryption.cjs"),r=require("./applied-runtime.cjs");let i=require("viem"),a=require("@fhevm/sdk/actions/base"),o=require("@fhevm/sdk/viem"),s=require("@fhevm/sdk/viem/cleartext");function c(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:e.protocolConfigContractAddress?{address:e.protocolConfigContractAddress}:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2019 Google LLC
|
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
|
6
6
|
*/
|
|
7
|
-
var l=e(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n.Comlink={}))})(e,(function(e){"use strict";let t=Symbol(`Comlink.proxy`),n=Symbol(`Comlink.endpoint`),r=Symbol(`Comlink.releaseProxy`),i=Symbol(`Comlink.finalizer`),a=Symbol(`Comlink.thrown`),o=e=>typeof e==`object`&&!!e||typeof e==`function`,s=new Map([[`proxy`,{canHandle:e=>o(e)&&e[t],serialize(e){let{port1:t,port2:n}=new MessageChannel;return l(e,t),[n,[n]]},deserialize(e){return e.start(),f(e)}}],[`throw`,{canHandle:e=>o(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(Error(e.value.message),e.value):e.value}}]]);function c(e,t){for(let n of e)if(t===n||n===`*`||n instanceof RegExp&&n.test(t))return!0;return!1}function l(e,t=globalThis,n=[`*`]){t.addEventListener(`message`,function r(o){if(!o||!o.data)return;if(!c(n,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}let{id:s,type:u,path:f}=Object.assign({path:[]},o.data),p=(o.data.argumentList||[]).map(D),m;try{let t=f.slice(0,-1).reduce((e,t)=>e[t],e),n=f.reduce((e,t)=>e[t],e);switch(u){case`GET`:m=n;break;case`SET`:t[f.slice(-1)[0]]=D(o.data.value),m=!0;break;case`APPLY`:m=n.apply(t,p);break;case`CONSTRUCT`:m=w(new n(...p));break;case`ENDPOINT`:{let{port1:t,port2:n}=new MessageChannel;l(e,n),m=C(t,[t])}break;case`RELEASE`:m=void 0;break;default:return}}catch(e){m={value:e,[a]:0}}Promise.resolve(m).catch(e=>({value:e,[a]:0})).then(n=>{let[a,o]=E(n);t.postMessage(Object.assign(Object.assign({},a),{id:s}),o),u===`RELEASE`&&(t.removeEventListener(`message`,r),d(t),i in e&&typeof e[i]==`function`&&e[i]())}).catch(e=>{let[n,r]=E({value:TypeError(`Unserializable return value`),[a]:0});t.postMessage(Object.assign(Object.assign({},n),{id:s}),r)})}),t.start&&t.start()}function u(e){return e.constructor.name===`MessagePort`}function d(e){u(e)&&e.close()}function f(e,t){let n=new Map;return e.addEventListener(`message`,function(e){let{data:t}=e;if(!t||!t.id)return;let r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}}),y(e,n,[],t)}function p(e){if(e)throw Error(`Proxy has been released and is not useable`)}function m(e){return O(e,new Map,{type:`RELEASE`}).then(()=>{d(e)})}let h=new WeakMap,g=`FinalizationRegistry`in globalThis&&new FinalizationRegistry(e=>{let t=(h.get(e)||0)-1;h.set(e,t),t===0&&m(e)});function _(e,t){let n=(h.get(t)||0)+1;h.set(t,n),g&&g.register(e,t,e)}function v(e){g&&g.unregister(e)}function y(e,t,i=[],a=function(){}){let o=!1,s=new Proxy(a,{get(n,a){if(p(o),a===r)return()=>{v(s),m(e),t.clear(),o=!0};if(a===`then`){if(i.length===0)return{then:()=>s};let n=O(e,t,{type:`GET`,path:i.map(e=>e.toString())}).then(D);return n.then.bind(n)}return y(e,t,[...i,a])},set(n,r,a){p(o);let[s,c]=E(a);return O(e,t,{type:`SET`,path:[...i,r].map(e=>e.toString()),value:s},c).then(D)},apply(r,a,s){p(o);let c=i[i.length-1];if(c===n)return O(e,t,{type:`ENDPOINT`}).then(D);if(c===`bind`)return y(e,t,i.slice(0,-1));let[l,u]=x(s);return O(e,t,{type:`APPLY`,path:i.map(e=>e.toString()),argumentList:l},u).then(D)},construct(n,r){p(o);let[a,s]=x(r);return O(e,t,{type:`CONSTRUCT`,path:i.map(e=>e.toString()),argumentList:a},s).then(D)}});return _(s,e),s}function b(e){return Array.prototype.concat.apply([],e)}function x(e){let t=e.map(E);return[t.map(e=>e[0]),b(t.map(e=>e[1]))]}let S=new WeakMap;function C(e,t){return S.set(e,t),e}function w(e){return Object.assign(e,{[t]:!0})}function T(e,t=globalThis,n=`*`){return{postMessage:(t,r)=>e.postMessage(t,n,r),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function E(e){for(let[t,n]of s)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:`HANDLER`,name:t,value:r},i]}return[{type:`RAW`,value:e},S.get(e)||[]]}function D(e){switch(e.type){case`HANDLER`:return s.get(e.name).deserialize(e.value);case`RAW`:return e.value}}function O(e,t,n,r){return new Promise(i=>{let a=k();t.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},n),r)})}function k(){return[,,,,].fill(0).map(()=>Math.floor(Math.random()*(2**53-1)).toString(16)).join(`-`)}e.createEndpoint=n,e.expose=l,e.finalizer=i,e.proxy=w,e.proxyMarker=t,e.releaseProxy=r,e.transfer=C,e.transferHandlers=s,e.windowEndpoint=T,e.wrap=f}))}))();function u(e){return typeof e==`object`&&!!e&&e.wireError===!0}const d=[`statusCode`,`status`,`retryAfter`,`timeoutMs`,`relayerApiError`,`code`,`data`,`shortMessage`,`details`,`error`,`info`];function f(e){try{return structuredClone(e),!0}catch{return!1}}function p(e){let n=e.response;return t.x(n?.headers)}function m(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function h(e){let n={};for(let t of d){let r=e[t];r!==void 0&&f(r)&&(n[t]=r)}if(!t.y(n.retryAfter)){let t=p(e);t!==void 0&&(n.retryAfter=t)}return n}function g(e,t=6){if(u(e))return e;let n=e=>t>0&&e!==void 0?g(e,t-1):void 0;if(e instanceof Error)return{wireError:!0,name:e.name,message:e.message,stack:e.stack,props:h(e),cause:n(e.cause)};if(typeof e==`object`&&e){let{message:t,cause:r}=e;return{wireError:!0,name:`Error`,message:typeof t==`string`?t:m(e),stack:void 0,props:h(e),cause:n(r)}}return{wireError:!0,name:`Error`,message:typeof e==`string`?e:m(e),stack:void 0,props:{},cause:void 0}}function _(e){let t=Error(e.message,e.cause?{cause:_(e.cause)}:{});return t.name=e.name,e.stack!==void 0&&(t.stack=e.stack),Object.assign(t,e.props),t}function v(){throw Error(`The encrypt worker is only available in the ESM build.`)}const y={spawn:1e4,init:3e5},b=new WeakSet;var x=class extends Error{crashed;constructor(e,t){super(e,t),this.name=`WorkerUnavailableError`,this.crashed=t?.crashed??!1}};function S(e){if(typeof e!=`object`||!e)return!1;let{name:t,message:n}=e;return t===`DataCloneError`||t===`TypeError`&&typeof n==`string`&&n.includes(`Unserializable return value`)}function C(e){if(e?.aborted)throw e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}const w={count:0,last:void 0,warnedFor:-1};function T(e){if(e===void 0)return{key:e,transfers:[]};let t=e.publicKeyBytes.bytes,n=e.crsBytes.bytes;if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))return{key:e,transfers:[]};let r=t.slice(),i=n.slice();return{key:{...e,publicKeyBytes:{...e.publicKeyBytes,bytes:r},crsBytes:{...e.crsBytes,bytes:i}},transfers:[r.buffer,i.buffer]}}function E(){let e,t=new Promise((t,n)=>{e=n});return t.catch(()=>{}),{initPromise:void 0,worker:void 0,api:void 0,doomed:t,doom:e}}var D=class{#e;#t;#n=!1;#r=w;#i=0;#a=new Map;#o;#s=0;#c=!1;constructor(e){this.#e=e}init=()=>{let e=this.#t??=E();if(e.initPromise===void 0){let t=this.#f(()=>this.#u(e)).catch(n=>{throw e.initPromise===t&&(e.initPromise=void 0),n});e.initPromise=t}return e.initPromise};encryptValue=e=>this.#f(()=>this.#l(t=>t.encryptValue(e),(t,n,r)=>t.encryptValue(n,{...e,options:r}),e.options));encryptValues=e=>this.#f(()=>this.#l(t=>t.encryptValues(e),(t,n,r)=>t.encryptValues(n,{...e,options:r}),e.options));dispose(){this.#c=!0,this.#p()}async#l(e,t,n){let{signal:r,onProgress:i,...a}=n??{};C(r),await this.init(),C(r);let o=this.#t,s=o?.api;if(this.#o!==void 0&&(this.#n||s===void 0))return e(await this.#o);if(o===void 0||s===void 0)return e(await this.#b(o,this.#r.last??new x(`Encrypt worker not running.`)));let c=this.#i++,l=()=>void s.abort(c).catch(()=>{});r?.addEventListener(`abort`,l,{once:!0}),i&&this.#a.set(c,i);try{let e=await this.#v(o,t(s,c,a));return this.#r=w,e}catch(t){if(t instanceof x)return e(await this.#b(o,t));throw t}finally{this.#a.delete(c),r?.removeEventListener(`abort`,l)}}async#u(e){if(this.#n)return;let t=this.#e.blockedReason;if(t!==void 0){await this.#b(e,new x(t));return}let n=await this.#e.prefetchKey();try{let t=await this.#h(e),r=this.#e.network,i=typeof r==`string`?null:(0,l.proxy)(async e=>{try{return await r.request(e)}catch(e){throw g(e)}}),a=(0,l.proxy)((e,t)=>{try{this.#e.logger[e](t)}catch(e){this.#d(`logger`,e)}}),o=(0,l.proxy)((e,t)=>{try{this.#a.get(e)?.(t)}catch(e){this.#d(`onProgress`,e)}}),s=T(n);await this.#v(e,t.init((0,l.transfer)({...this.#e.initPayload,clientOptions:{...this.#e.initPayload.clientOptions,fheEncryptionKey:s.key},rpcUrl:typeof r==`string`?r:void 0},s.transfers),i,a,o),{ms:this.#e.timeouts.init,operation:`init`}),e.api=t,this.#r={...this.#r,last:void 0}}catch(t){if(!(t instanceof x))throw this.#y(e,new x(`Encrypt worker init failed.`)),t;await this.#b(e,t)}}#d(e,t){let n=t instanceof Error?t.message:String(t);try{this.#e.logger.warn(`Encrypt offload ${e} callback threw: ${n}`)}catch{}}async#f(e){this.#s++;try{return await e()}finally{this.#s--,this.#p()}}#p(){!this.#c||this.#s>0||(this.#c=!1,this.#t?.worker?.terminate(),this.#t=void 0,this.#o=void 0,this.#n=!1,this.#r=w)}#m(){let e=this.#e.workerSource;if(e===void 0)return v();if(typeof e==`function`){let t=e();return b.has(t)&&this.#e.logger.warnAlways(`The offloadWorker factory returned a worker it already handed out; each call must construct a fresh Worker.`),b.add(t),t}return new Worker(e,{type:`module`,name:`zama-fhe-encrypt`})}async#h(e){let t;try{t=this.#m()}catch(e){throw new x(e instanceof Error?e.message:String(e),{cause:e})}e.worker=t;let n=await this.#g(e,t);return this.#_(e,t),n}#g(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`message`,o),t.removeEventListener(`error`,s)},a=setTimeout(()=>{i(),r(new x(`Encrypt worker did not start within ${this.#e.timeouts.spawn}ms.`))},this.#e.timeouts.spawn),o=e=>{e.data===`zama-encrypt-worker-ready`&&(i(),n((0,l.wrap)(t)))},s=t=>{i();let n=t.message||`Encrypt worker error.`;r(new x(n)),this.#y(e,new x(n))};t.addEventListener(`message`,o),t.addEventListener(`error`,s)})}#_(e,t){t.addEventListener(`error`,t=>{if(this.#t!==e)return;let n=new x(t.message||`Encrypt worker error.`,{crashed:!0});this.#r={...this.#r,count:this.#r.count+1,last:n},this.#y(e,n)})}async#v(e,t,n){let r=n===void 0?void 0:setTimeout(()=>{this.#y(e,new x(`Encrypt worker ${n.operation} timed out after ${n.ms}ms.`))},n.ms);try{return await Promise.race([t.catch(e=>{let t=u(e)?_(e):e;throw S(t)?new x(t.message,{cause:t}):t}),e.doomed])}finally{r!==void 0&&clearTimeout(r)}}#y(e,t){e!==void 0&&(this.#t===e&&(this.#t=void 0),e.worker?.terminate(),e.worker=void 0,e.api=void 0,e.initPromise=void 0,e.doom(t))}async#b(e,t){let r=t instanceof Error?t.message:String(t);if(this.#e.strict)throw this.#y(e,new x(`Encrypt worker unavailable.`)),new n.n(`Encrypt offload required (offloadEncrypt: true) but unavailable: ${r}`,{cause:t});let{transient:i,pinning:a}=this.#x(t);if(this.#n||=!i,this.#y(e,new x(`Encrypt worker degraded to inline.`)),this.#S(r,i,a),this.#o===void 0){let e=(async()=>{let e=this.#e.createInlineClient();return await e.init(),e})().catch(t=>{throw this.#o===e&&(this.#o=void 0),this.#e.logger.warnAlways(`Encrypt inline fallback failed to initialize: ${t instanceof Error?t.message:String(t)}`),t});this.#o=e}return this.#o}#x(e){let t=e instanceof x&&e.crashed&&this.#r.count<2;return{transient:t,pinning:!t&&!this.#n}}#S(e,t,n){if(!n&&this.#r.warnedFor===this.#r.count)return;this.#r={...this.#r,warnedFor:this.#r.count};let r=t?`in-flight encryption falls back`:`encryption falls back`;this.#e.logger.warnAlways(`Encrypt offload unavailable, ${r} to the calling thread: ${e}`)}},O=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:t,debug:n,batchRpcCalls:r,moduleVersions:a,fheEncryptionKey:l}=e.options??{},u=this.#e.auth?A(this.#e.auth):void 0,d={publicClient:(0,i.createPublicClient)({transport:typeof this.#e.network==`string`?(0,i.http)(this.#e.network):(0,i.custom)(this.#e.network)}),chain:c(this.#e),options:{batchRpcCalls:r,moduleVersions:a,fheEncryptionKey:l}};this.#i={...u!==void 0&&{auth:u},...t!==void 0&&{timeout:t},...n!==void 0&&{debug:n}};let f=()=>this.#t.fetchFheEncryptionKeyBytes({options:this.#i}),p=e=>({init:async()=>{await f(),await e.init()},encryptValue:t=>e.encryptValue(t),encryptValues:t=>e.encryptValues(t),fetchFheEncryptionKeyBytes:t=>e.fetchFheEncryptionKeyBytes(t)});e.cleartext?(this.#t=(0,s.createFhevmCleartextBaseClient)(d),this.#n=(0,s.createFhevmCleartextDecryptClient)(d),this.#r=p((0,s.createFhevmCleartextEncryptClient)(d))):(this.#t=(0,o.createFhevmBaseClient)(d),this.#n=(0,o.createFhevmDecryptClient)(d),this.#r=this.#o(e,d,{prefetchKey:f,createInlineClient:()=>p((0,o.createFhevmEncryptClient)(d))}))}#o(e,t,n){let i=e.offloadEncrypt??!1,a=i===!0,o=typeof Worker==`function`&&(e.offloadWorker!==void 0||!1);if(i===!1||!(a||o))return n.createInlineClient();let s=r.t(),c=k(s);if(c!==void 0&&!a)return e.logger.warnAlways(`Encryption runs on the calling thread: ${c}.`),n.createInlineClient();let l=new D({initPayload:{chain:t.chain,clientOptions:t.options,runtime:s??{}},network:this.#e.network,prefetchKey:n.prefetchKey,createInlineClient:n.createInlineClient,logger:e.logger,timeouts:e.offloadTimeouts??y,workerSource:e.offloadWorker,blockedReason:c,strict:a});return{init:()=>l.init(),encryptValue:e=>l.encryptValue(e),encryptValues:e=>l.encryptValues(e),fetchFheEncryptionKeyBytes:e=>this.#t.fetchFheEncryptionKeyBytes(e),dispose:()=>l.dispose()}}get chain(){return this.#e}#s=()=>(this.#a??=this.#r.init().catch(e=>{throw this.#a=void 0,e}),this.#a);dispose=()=>{this.#a=void 0,this.#r.dispose?.()};decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#s(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#s(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#t.init(),this.#t.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));createUnsignedLegacyDecryptionPermitEip712=e=>(0,a.createUnsignedLegacyDecryptionPermitEip712)(this.#t,e);serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function k(e){if(r.n())return`a runtime locateFile cannot cross the encrypt worker boundary`;if(e===void 0&&(0,o.hasFhevmRuntimeConfig)())return`a runtime config set outside createConfig cannot be replicated in the encrypt worker realm`}function A(e){let n=e.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:e.value,header:e.header};case`ApiKeyCookie`:return{type:n,value:e.value,cookie:e.cookie};case`BearerToken`:return{type:n,token:e.token};default:throw new t.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return O}});
|
|
7
|
+
var l=e(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n.Comlink={}))})(e,(function(e){"use strict";let t=Symbol(`Comlink.proxy`),n=Symbol(`Comlink.endpoint`),r=Symbol(`Comlink.releaseProxy`),i=Symbol(`Comlink.finalizer`),a=Symbol(`Comlink.thrown`),o=e=>typeof e==`object`&&!!e||typeof e==`function`,s=new Map([[`proxy`,{canHandle:e=>o(e)&&e[t],serialize(e){let{port1:t,port2:n}=new MessageChannel;return l(e,t),[n,[n]]},deserialize(e){return e.start(),f(e)}}],[`throw`,{canHandle:e=>o(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(Error(e.value.message),e.value):e.value}}]]);function c(e,t){for(let n of e)if(t===n||n===`*`||n instanceof RegExp&&n.test(t))return!0;return!1}function l(e,t=globalThis,n=[`*`]){t.addEventListener(`message`,function r(o){if(!o||!o.data)return;if(!c(n,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}let{id:s,type:u,path:f}=Object.assign({path:[]},o.data),p=(o.data.argumentList||[]).map(D),m;try{let t=f.slice(0,-1).reduce((e,t)=>e[t],e),n=f.reduce((e,t)=>e[t],e);switch(u){case`GET`:m=n;break;case`SET`:t[f.slice(-1)[0]]=D(o.data.value),m=!0;break;case`APPLY`:m=n.apply(t,p);break;case`CONSTRUCT`:m=w(new n(...p));break;case`ENDPOINT`:{let{port1:t,port2:n}=new MessageChannel;l(e,n),m=C(t,[t])}break;case`RELEASE`:m=void 0;break;default:return}}catch(e){m={value:e,[a]:0}}Promise.resolve(m).catch(e=>({value:e,[a]:0})).then(n=>{let[a,o]=E(n);t.postMessage(Object.assign(Object.assign({},a),{id:s}),o),u===`RELEASE`&&(t.removeEventListener(`message`,r),d(t),i in e&&typeof e[i]==`function`&&e[i]())}).catch(e=>{let[n,r]=E({value:TypeError(`Unserializable return value`),[a]:0});t.postMessage(Object.assign(Object.assign({},n),{id:s}),r)})}),t.start&&t.start()}function u(e){return e.constructor.name===`MessagePort`}function d(e){u(e)&&e.close()}function f(e,t){let n=new Map;return e.addEventListener(`message`,function(e){let{data:t}=e;if(!t||!t.id)return;let r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}}),y(e,n,[],t)}function p(e){if(e)throw Error(`Proxy has been released and is not useable`)}function m(e){return O(e,new Map,{type:`RELEASE`}).then(()=>{d(e)})}let h=new WeakMap,g=`FinalizationRegistry`in globalThis&&new FinalizationRegistry(e=>{let t=(h.get(e)||0)-1;h.set(e,t),t===0&&m(e)});function _(e,t){let n=(h.get(t)||0)+1;h.set(t,n),g&&g.register(e,t,e)}function v(e){g&&g.unregister(e)}function y(e,t,i=[],a=function(){}){let o=!1,s=new Proxy(a,{get(n,a){if(p(o),a===r)return()=>{v(s),m(e),t.clear(),o=!0};if(a===`then`){if(i.length===0)return{then:()=>s};let n=O(e,t,{type:`GET`,path:i.map(e=>e.toString())}).then(D);return n.then.bind(n)}return y(e,t,[...i,a])},set(n,r,a){p(o);let[s,c]=E(a);return O(e,t,{type:`SET`,path:[...i,r].map(e=>e.toString()),value:s},c).then(D)},apply(r,a,s){p(o);let c=i[i.length-1];if(c===n)return O(e,t,{type:`ENDPOINT`}).then(D);if(c===`bind`)return y(e,t,i.slice(0,-1));let[l,u]=x(s);return O(e,t,{type:`APPLY`,path:i.map(e=>e.toString()),argumentList:l},u).then(D)},construct(n,r){p(o);let[a,s]=x(r);return O(e,t,{type:`CONSTRUCT`,path:i.map(e=>e.toString()),argumentList:a},s).then(D)}});return _(s,e),s}function b(e){return Array.prototype.concat.apply([],e)}function x(e){let t=e.map(E);return[t.map(e=>e[0]),b(t.map(e=>e[1]))]}let S=new WeakMap;function C(e,t){return S.set(e,t),e}function w(e){return Object.assign(e,{[t]:!0})}function T(e,t=globalThis,n=`*`){return{postMessage:(t,r)=>e.postMessage(t,n,r),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function E(e){for(let[t,n]of s)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:`HANDLER`,name:t,value:r},i]}return[{type:`RAW`,value:e},S.get(e)||[]]}function D(e){switch(e.type){case`HANDLER`:return s.get(e.name).deserialize(e.value);case`RAW`:return e.value}}function O(e,t,n,r){return new Promise(i=>{let a=k();t.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},n),r)})}function k(){return[,,,,].fill(0).map(()=>Math.floor(Math.random()*(2**53-1)).toString(16)).join(`-`)}e.createEndpoint=n,e.expose=l,e.finalizer=i,e.proxy=w,e.proxyMarker=t,e.releaseProxy=r,e.transfer=C,e.transferHandlers=s,e.windowEndpoint=T,e.wrap=f}))}))();function u(e){return typeof e==`object`&&!!e&&e.wireError===!0}const d=[`statusCode`,`status`,`retryAfter`,`timeoutMs`,`relayerApiError`,`code`,`data`,`shortMessage`,`details`,`error`,`info`];function f(e){try{return structuredClone(e),!0}catch{return!1}}function p(e){let n=e.response;return t.C(n?.headers)}function m(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function h(e){let n={};for(let t of d){let r=e[t];r!==void 0&&f(r)&&(n[t]=r)}if(!t.x(n.retryAfter)){let t=p(e);t!==void 0&&(n.retryAfter=t)}return n}function g(e,t=6){if(u(e))return e;let n=e=>t>0&&e!==void 0?g(e,t-1):void 0;if(e instanceof Error)return{wireError:!0,name:e.name,message:e.message,stack:e.stack,props:h(e),cause:n(e.cause)};if(typeof e==`object`&&e){let{message:t,cause:r}=e;return{wireError:!0,name:`Error`,message:typeof t==`string`?t:m(e),stack:void 0,props:h(e),cause:n(r)}}return{wireError:!0,name:`Error`,message:typeof e==`string`?e:m(e),stack:void 0,props:{},cause:void 0}}function _(e){let t=Error(e.message,e.cause?{cause:_(e.cause)}:{});return t.name=e.name,e.stack!==void 0&&(t.stack=e.stack),Object.assign(t,e.props),t}function v(){throw Error(`The encrypt worker is only available in the ESM build.`)}const y={spawn:1e4,init:3e5},b=new WeakSet;var x=class extends Error{crashed;constructor(e,t){super(e,t),this.name=`WorkerUnavailableError`,this.crashed=t?.crashed??!1}};function S(e){if(typeof e!=`object`||!e)return!1;let{name:t,message:n}=e;return t===`DataCloneError`||t===`TypeError`&&typeof n==`string`&&n.includes(`Unserializable return value`)}function C(e){if(e?.aborted)throw e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}const w={count:0,last:void 0,warnedFor:-1};function T(e){if(e===void 0)return{key:e,transfers:[]};let t=e.publicKeyBytes.bytes,n=e.crsBytes.bytes;if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))return{key:e,transfers:[]};let r=t.slice(),i=n.slice();return{key:{...e,publicKeyBytes:{...e.publicKeyBytes,bytes:r},crsBytes:{...e.crsBytes,bytes:i}},transfers:[r.buffer,i.buffer]}}function E(){let e,t=new Promise((t,n)=>{e=n});return t.catch(()=>{}),{initPromise:void 0,worker:void 0,api:void 0,doomed:t,doom:e}}var D=class{#e;#t;#n=!1;#r=w;#i=0;#a=new Map;#o;#s=0;#c=!1;constructor(e){this.#e=e}init=()=>{let e=this.#t??=E();if(e.initPromise===void 0){let t=this.#f(()=>this.#u(e)).catch(n=>{throw e.initPromise===t&&(e.initPromise=void 0),n});e.initPromise=t}return e.initPromise};encryptValue=e=>this.#f(()=>this.#l(t=>t.encryptValue(e),(t,n,r)=>t.encryptValue(n,{...e,options:r}),e.options));encryptValues=e=>this.#f(()=>this.#l(t=>t.encryptValues(e),(t,n,r)=>t.encryptValues(n,{...e,options:r}),e.options));dispose(){this.#c=!0,this.#p()}async#l(e,t,n){let{signal:r,onProgress:i,...a}=n??{};C(r),await this.init(),C(r);let o=this.#t,s=o?.api;if(this.#o!==void 0&&(this.#n||s===void 0))return e(await this.#o);if(o===void 0||s===void 0)return e(await this.#b(o,this.#r.last??new x(`Encrypt worker not running.`)));let c=this.#i++,l=()=>void s.abort(c).catch(()=>{});r?.addEventListener(`abort`,l,{once:!0}),i&&this.#a.set(c,i);try{let e=await this.#v(o,t(s,c,a));return this.#r=w,e}catch(t){if(t instanceof x)return e(await this.#b(o,t));throw t}finally{this.#a.delete(c),r?.removeEventListener(`abort`,l)}}async#u(e){if(this.#n)return;let t=this.#e.blockedReason;if(t!==void 0){await this.#b(e,new x(t));return}let n=await this.#e.prefetchKey();try{let t=await this.#h(e),r=this.#e.network,i=typeof r==`string`?null:(0,l.proxy)(async e=>{try{return await r.request(e)}catch(e){throw g(e)}}),a=(0,l.proxy)((e,t)=>{try{this.#e.logger[e](t)}catch(e){this.#d(`logger`,e)}}),o=(0,l.proxy)((e,t)=>{try{this.#a.get(e)?.(t)}catch(e){this.#d(`onProgress`,e)}}),s=T(n);await this.#v(e,t.init((0,l.transfer)({...this.#e.initPayload,clientOptions:{...this.#e.initPayload.clientOptions,fheEncryptionKey:s.key},rpcUrl:typeof r==`string`?r:void 0},s.transfers),i,a,o),{ms:this.#e.timeouts.init,operation:`init`}),e.api=t,this.#r={...this.#r,last:void 0}}catch(t){if(!(t instanceof x))throw this.#y(e,new x(`Encrypt worker init failed.`)),t;await this.#b(e,t)}}#d(e,t){let n=t instanceof Error?t.message:String(t);try{this.#e.logger.warn(`Encrypt offload ${e} callback threw: ${n}`)}catch{}}async#f(e){this.#s++;try{return await e()}finally{this.#s--,this.#p()}}#p(){!this.#c||this.#s>0||(this.#c=!1,this.#t?.worker?.terminate(),this.#t=void 0,this.#o=void 0,this.#n=!1,this.#r=w)}#m(){let e=this.#e.workerSource;if(e===void 0)return v();if(typeof e==`function`){let t=e();return b.has(t)&&this.#e.logger.warnAlways(`The offloadWorker factory returned a worker it already handed out; each call must construct a fresh Worker.`),b.add(t),t}return new Worker(e,{type:`module`,name:`zama-fhe-encrypt`})}async#h(e){let t;try{t=this.#m()}catch(e){throw new x(e instanceof Error?e.message:String(e),{cause:e})}e.worker=t;let n=await this.#g(e,t);return this.#_(e,t),n}#g(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`message`,o),t.removeEventListener(`error`,s)},a=setTimeout(()=>{i(),r(new x(`Encrypt worker did not start within ${this.#e.timeouts.spawn}ms.`))},this.#e.timeouts.spawn),o=e=>{e.data===`zama-encrypt-worker-ready`&&(i(),n((0,l.wrap)(t)))},s=t=>{i();let n=t.message||`Encrypt worker error.`;r(new x(n)),this.#y(e,new x(n))};t.addEventListener(`message`,o),t.addEventListener(`error`,s)})}#_(e,t){t.addEventListener(`error`,t=>{if(this.#t!==e)return;let n=new x(t.message||`Encrypt worker error.`,{crashed:!0});this.#r={...this.#r,count:this.#r.count+1,last:n},this.#y(e,n)})}async#v(e,t,n){let r=n===void 0?void 0:setTimeout(()=>{this.#y(e,new x(`Encrypt worker ${n.operation} timed out after ${n.ms}ms.`))},n.ms);try{return await Promise.race([t.catch(e=>{let t=u(e)?_(e):e;throw S(t)?new x(t.message,{cause:t}):t}),e.doomed])}finally{r!==void 0&&clearTimeout(r)}}#y(e,t){e!==void 0&&(this.#t===e&&(this.#t=void 0),e.worker?.terminate(),e.worker=void 0,e.api=void 0,e.initPromise=void 0,e.doom(t))}async#b(e,t){let r=t instanceof Error?t.message:String(t);if(this.#e.strict)throw this.#y(e,new x(`Encrypt worker unavailable.`)),new n.n(`Encrypt offload required (offloadEncrypt: true) but unavailable: ${r}`,{cause:t});let{transient:i,pinning:a}=this.#x(t);if(this.#n||=!i,this.#y(e,new x(`Encrypt worker degraded to inline.`)),this.#S(r,i,a),this.#o===void 0){let e=(async()=>{let e=this.#e.createInlineClient();return await e.init(),e})().catch(t=>{throw this.#o===e&&(this.#o=void 0),this.#e.logger.warnAlways(`Encrypt inline fallback failed to initialize: ${t instanceof Error?t.message:String(t)}`),t});this.#o=e}return this.#o}#x(e){let t=e instanceof x&&e.crashed&&this.#r.count<2;return{transient:t,pinning:!t&&!this.#n}}#S(e,t,n){if(!n&&this.#r.warnedFor===this.#r.count)return;this.#r={...this.#r,warnedFor:this.#r.count};let r=t?`in-flight encryption falls back`:`encryption falls back`;this.#e.logger.warnAlways(`Encrypt offload unavailable, ${r} to the calling thread: ${e}`)}},O=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:t,debug:n,batchRpcCalls:r,moduleVersions:a,fheEncryptionKey:l}=e.options??{},u=this.#e.auth?A(this.#e.auth):void 0,d={publicClient:(0,i.createPublicClient)({transport:typeof this.#e.network==`string`?(0,i.http)(this.#e.network):(0,i.custom)(this.#e.network)}),chain:c(this.#e),options:{batchRpcCalls:r,moduleVersions:a,fheEncryptionKey:l}};this.#i={...u!==void 0&&{auth:u},...t!==void 0&&{timeout:t},...n!==void 0&&{debug:n}};let f=()=>this.#t.fetchFheEncryptionKeyBytes({options:this.#i}),p=e=>({init:async()=>{await f(),await e.init()},encryptValue:t=>e.encryptValue(t),encryptValues:t=>e.encryptValues(t),fetchFheEncryptionKeyBytes:t=>e.fetchFheEncryptionKeyBytes(t)});e.cleartext?(this.#t=(0,s.createFhevmCleartextBaseClient)(d),this.#n=(0,s.createFhevmCleartextDecryptClient)(d),this.#r=p((0,s.createFhevmCleartextEncryptClient)(d))):(this.#t=(0,o.createFhevmBaseClient)(d),this.#n=(0,o.createFhevmDecryptClient)(d),this.#r=this.#o(e,d,{prefetchKey:f,createInlineClient:()=>p((0,o.createFhevmEncryptClient)(d))}))}#o(e,t,n){let i=e.offloadEncrypt??!1,a=i===!0,o=typeof Worker==`function`&&(e.offloadWorker!==void 0||!1);if(i===!1||!(a||o))return n.createInlineClient();let s=r.t(),c=k(s);if(c!==void 0&&!a)return e.logger.warnAlways(`Encryption runs on the calling thread: ${c}.`),n.createInlineClient();let l=new D({initPayload:{chain:t.chain,clientOptions:t.options,runtime:s??{}},network:this.#e.network,prefetchKey:n.prefetchKey,createInlineClient:n.createInlineClient,logger:e.logger,timeouts:e.offloadTimeouts??y,workerSource:e.offloadWorker,blockedReason:c,strict:a});return{init:()=>l.init(),encryptValue:e=>l.encryptValue(e),encryptValues:e=>l.encryptValues(e),fetchFheEncryptionKeyBytes:e=>this.#t.fetchFheEncryptionKeyBytes(e),dispose:()=>l.dispose()}}get chain(){return this.#e}#s=()=>(this.#a??=this.#r.init().catch(e=>{throw this.#a=void 0,e}),this.#a);dispose=()=>{this.#a=void 0,this.#r.dispose?.()};decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#s(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#s(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#t.init(),this.#t.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));signUnifiedDecryptionPermit=async e=>(await this.#t.init(),this.#t.signUnifiedDecryptionPermit(e));createUnsignedLegacyDecryptionPermitEip712=e=>(0,a.createUnsignedLegacyDecryptionPermitEip712)(this.#t,e);createUnsignedUnifiedDecryptionPermitEip712=e=>(0,a.createUnsignedUnifiedDecryptionPermitEip712)(this.#t,e);canUseUnifiedDecryptionPermit=e=>(0,a.canUseUnifiedDecryptionPermit)(this.#t,{options:{...this.#i,...e?.options}});serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function k(e){if(r.n())return`a runtime locateFile cannot cross the encrypt worker boundary`;if(e===void 0&&(0,o.hasFhevmRuntimeConfig)())return`a runtime config set outside createConfig cannot be replicated in the encrypt worker realm`}function A(e){let n=e.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:e.value,header:e.header};case`ApiKeyCookie`:return{type:n,value:e.value,cookie:e.cookie};case`BearerToken`:return{type:n,token:e.token};default:throw new t.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return O}});
|
|
8
8
|
//# sourceMappingURL=fhevm-relayer.cjs.map
|