@zama-fhe/sdk 3.5.0-alpha.5 → 3.5.0-alpha.6
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/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs"),o=require("./assertions.cjs");let s=require("viem"),c=require("zod/mini");function l(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var u=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},d=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},ee=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const te=[n._,t.X,e.n,y,t.q,t.K,u,n.g,t.Y];function b(r,i,a={}){if(te.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.Y(r.message,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new y(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new u({encryptedValue:e.g(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.g(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.h(r)?new n.g(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.X(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new y(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n._(i,{cause:r})}function ne(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.v(r,{cause:t})}const re=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function x(e,t,n,r=`0x`){return{address:e,abi:re,functionName:`transferAndCall`,args:[t,n,r]}}const S=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function C(e,t,n,r){return{address:e,abi:S,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function w(e,t,n){return{address:e,abi:S,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function T(e,t,n,r){return{address:e,abi:S,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function ie(e,t,n,r,i){return{address:e,abi:S,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const E=2n**64n-1n;function ae(e){return i.i(e.signer,e.provider,e)}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}function O(e){return(0,s.keccak256)((0,s.toBytes)(e))}const k={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function A(e){return(0,s.getAddress)(D(e.slice(-40)))}function j(e){return e}function M(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function N(e,t){return(0,s.getAddress)(D(M(e,t).slice(-40)))}function P(e,t){return BigInt(`0x`+M(e,t))}function F(e,t){return D(M(e,t))}function oe(e){return e.topics[0]!==k.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:j(e.topics[3])}}function I(e){return e.topics[0]!==k.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:P(e.data,0),encryptedWrappedAmount:F(e.data,1)}}function L(e){return e.topics[0]!==k.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0)}}function R(e){return e.topics[0]!==k.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0),cleartextAmount:P(e.data,1)}}function z(e){return oe(e)??I(e)??L(e)??R(e)}function se(e){let t=[];for(let n of e){let e=z(n);e&&t.push(e)}return t}function B(e){for(let t of e){let e=L(t);if(e)return e}return null}function ce(e){for(let t of e){let e=I(t);if(e)return e}return null}const le=[k.ConfidentialTransfer,k.Wrap,k.UnwrapRequested,k.UnwrapFinalized],V={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function H(e){return e.topics[0]!==V.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2),newExpirationDate:P(e.data,3)}}function U(e){return e.topics[0]!==V.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2)}}function W(e){return H(e)??U(e)}function ue(e){let t=[];for(let n of e){let e=W(n);e&&t.push(e)}return t}function de(e){for(let t of e){let e=H(t);if(e)return e}return null}function fe(e){for(let t of e){let e=U(t);if(e)return e}return null}const pe=[V.DelegatedForUserDecryption,V.RevokedDelegationForUserDecryption];var G=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.W(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await n.a(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.a(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,s.getAddress)((await n.i(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,s.getAddress)((await n.i(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},K=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.W(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.i(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.i(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},q=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.W(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.i(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.i(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{o.r(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw b(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.i(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},J=class{#e;constructor(e){this.#e=e}prepare(e,t){return this.#e.prepare(e,t)}},Y=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const me=new Y;function X(e){return`zama:pending-unshield:${i.l(e)}`}const he=c.z.union([c.z.pipe(i.d,c.z.transform(e=>({unwrapTxHash:e}))),c.z.pipe(c.z.object({version:c.z.literal(1),unwrapTxHash:i.d,unwrapRequestId:c.z.optional(i.d)}),c.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function ge(e,t,n,r){if(r===void 0){await e.set(X(t),n);return}await e.set(X(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function _e(e,t){return(await ve(e,t))?.unwrapTxHash??null}async function ve(e,t){let n=X(t),r=await e.get(n);if(r==null)return null;let i=he.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ye(e,t){await e.delete(X(t))}var be=class extends n.t{#e;#t=null;#n=null;#r(e){try{return o.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.B(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t._(n,(0,s.getAddress)(e),this.address))}async shield(r,i){let a=await n.i(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#s(),l=(0,s.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e._(t)})}if(u<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return o?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,s.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:x(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.i(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#s(),c=(0,s.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(o,c))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e._(t)})}if(l<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${o})`,{requested:r,available:l,token:o});let u;try{u=await this.sdk.provider.readContract(t._(o,c,this.address))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e._(t)})}if(u<r)throw new n.f(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${o}).`,{requested:r,available:u,token:o});let d=i?.to?(0,s.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.R(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,s.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.R(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,s.getAddress)(r.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.z(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.z(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.G(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);return this.#c(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){return _e(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,s.getAddress)((await n.i(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[o]=i;if(!o)throw new n.v(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,o,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,s.getAddress)((await n.i(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.c(r))throw new n._(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.a(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let n=B(e);if(!n)throw new t.G(`No UnwrapRequested event found in unwrap receipt`);return n.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.z(`unshield: savePendingUnshield`,()=>ge(this.sdk.storage,this.address,n),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.z(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a=await this.finalizeUnwrap(e);return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.z(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await t.z(`unshield: clearPendingUnshield`,()=>ye(this.sdk.storage,this.address),this.sdk.logger),a}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),o=(0,s.getAddress)((await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,o,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};const xe=c.z.union([c.z.bigint(),c.z.boolean(),i.u]),Se=c.z.array(c.z.string());var Ce=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=xe.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,s.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Se.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function we(e,t){let r=Te(e,t);if(!r)throw new n._(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function Te(e,t){let n=i.l(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const Ee=e=>new Promise(t=>setTimeout(t,e));var De=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,s.getAddress)(t);return this.#s(e,{requesterAddress:r,aclActorAddress:r,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n);return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,s.getAddress)(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#f(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0}))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof y))throw t;await Ee(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,s.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:o});for(let t of c)this.#l(t,e);return{items:c}}catch(e){if(n.l(e))throw e;if(c.length===1){let[n=this.#d()]=c;return n.error=this.#u(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,s.getAddress)(t)}),{items:c}}}let u=!1;return await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#l(e,n)}catch(r){if(n.l(r))throw u=!0,r;e.error=this.#u(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,s.getAddress)(t)})}}),a),{items:c}}async#o(t,n,r,i){let a=we(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a){if(r.length===0)return{};let o=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)})),c={},l=[];for(let e of o)n.c(e.encryptedValue)?c[e.encryptedValue]=0n:l.push(e);if(l.length===0)return c;let u=Array.from(new Set(o.map(e=>e.contractAddress))),d=Array.from(new Set(l.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(d)}catch(t){throw e.h(t)?this.#c(t,`the delegation pre-check`):t}let f=[];for(let e of l){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?f.push(e):c[e.encryptedValue]=t}if(f.length===0)return c;let p=await i.resolveCredentials(u),m=new Map;for(let e of f){let t=m.get(e.contractAddress);t?t.push(e.encryptedValue):m.set(e.contractAddress,[e.encryptedValue])}let h=[];for(let[e,t]of m)for(let r of n.s(t))h.push({contractAddress:e,encryptedValues:r});let g=Date.now(),_=f.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:_}),await n.r(h.map(({contractAddress:e,encryptedValues:t})=>async()=>{let r;try{r=await i.decryptContract({credentials:p,contractAddress:e,encryptedValues:t,options:a})}catch(t){throw b(t,i.errorMessage,{isDelegated:i.delegated,contractAddress:e,account:i.aclActorAddress})}for(let n=0;n<t.length;n++){let a=t[n],o=r[n]?.value;a!==void 0&&o!==void 0&&(c[a]=o,await this.#e.set(i.requesterAddress,e,a,o))}let o=t.filter(e=>c[e]===void 0);if(o.length>0)throw new n._(`${i.errorMessage}: relayer returned no clear value for ${o.length} of ${t.length} handle(s) on ${e}`,{cause:AggregateError(o.map(t=>new n._(`No clear value for handle ${t} on ${e}`)),`${o.length} handle(s) missing a clear value on ${e}`)})}),5);let e={};for(let t of _){let n=c[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-g,encryptedValues:_,result:e}),c}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e._(r),durationMs:Date.now()-g,encryptedValues:_}),b(n,i.errorMessage,{isDelegated:i.delegated})}}#c(t,r){return new n.g(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#l(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n._(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#u(t,n,r){return t instanceof e.r?t:b(t,n,r)}#d(){throw new n._(`Batch delegated decryption invariant failed: missing item`)}async#f(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function Oe(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const Z={AlreadyDelegatedOrRevokedInSameBlock:e=>new f(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new _(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new ee(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new g(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new v(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new p(`Cannot revoke: no active delegation exists.`,{cause:e})};function ke(e){return e in Z}function Ae(e,t){let n=Oe(e);if(n&&ke(n))return Z[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Z))if(r.includes(e))return n(t);return null}var je=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new v(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c=(0,s.getAddress)(r);if(o===c)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new g(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):E,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===u)throw new h(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:C(l,o,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),o=(0,s.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new p(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:w(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===E?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(T(r,(0,s.getAddress)(t),(0,s.getAddress)(n),(0,s.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof t.G))return;let n=Ae(e.cause??e,e);if(n)throw n}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof p||t instanceof m){let n=(0,s.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,s.getAddress)(e),i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),{isActive:o,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw c===0n?new p(`No active delegation from ${i} to ${a} for ${r}`):new m(`Delegation from ${i} to ${a} for ${r} has expired`)}},Me=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,s.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e._(n),durationMs:Date.now()-i},a),ne(n,`Encryption failed`)}}},Ne=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.z(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.z(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.z(`wallet account listener`,()=>n(e),this.#i)))}};const Pe=c.z.object({kind:c.z.literal(`ConfidentialTransfer`),from:i.u,token:i.u,to:i.u,amount:c.z.bigint()}),Fe=c.z.object({kind:c.z.literal(`ConfidentialTransferFrom`),from:i.u,token:i.u,owner:i.u,to:i.u,amount:c.z.bigint()}),Ie=c.z.object({kind:c.z.literal(`SetOperator`),from:i.u,token:i.u,operator:i.u,until:i.f}),Le=c.z.object({kind:c.z.literal(`Unwrap`),from:i.u,token:i.u,to:i.u,amount:c.z.bigint()}),Re=c.z.object({kind:c.z.literal(`UnwrapAll`),from:i.u,token:i.u,to:i.u}),Q=c.z.object({kind:c.z.literal(`FinalizeUnwrap`),from:i.u,wrapper:i.u,unwrapRequestIdOrAmount:i.d}),ze=c.z.object({kind:c.z.literal(`ApproveUnderlying`),from:i.u,underlying:i.u,spender:i.u,amount:c.z.bigint()}),Be=c.z.object({kind:c.z.literal(`Wrap`),from:i.u,wrapper:i.u,to:i.u,amount:c.z.bigint()}),Ve=i.d.check(c.z.refine(e=>e===`0x`||(0,s.size)(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),He=c.z.object({kind:c.z.literal(`TransferAndCall`),from:i.u,underlying:i.u,wrapper:i.u,amount:c.z.bigint(),recipientData:c.z.optional(Ve)}),Ue=c.z.object({kind:c.z.literal(`DelegateDecryption`),from:i.u,contractAddress:i.u,delegateAddress:i.u,expirationDate:c.z.optional(c.z.date())}),We=c.z.object({kind:c.z.literal(`RevokeDelegation`),from:i.u,contractAddress:i.u,delegateAddress:i.u});c.z.discriminatedUnion(`kind`,[Pe,Fe,Ie,Le,Re,Q,ze,Be,He,Ue,We]);const Ge=c.z.strictObject({maxFeePerGas:c.z.bigint(),maxPriorityFeePerGas:c.z.bigint()}),$=c.z.object({nonce:c.z.optional(c.z.int().check(c.z.nonnegative())),gasLimit:c.z.optional(c.z.bigint()),fees:c.z.optional(Ge)}),Ke=c.z.object({address:i.u,abi:c.z.array(c.z.unknown()),functionName:c.z.string(),args:c.z.array(c.z.unknown()),value:c.z.optional(c.z.bigint()),gas:c.z.optional(c.z.bigint())}),qe=c.z.extend($,{from:i.u,calldata:Ke});var Je=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(t,n){n&&=i.s($,n);let r=await this.#e.getChainId(),a=this.#t.chain.id;if(r!==a)throw new e.t(`Offline.prepare: provider is on chain ${r} but the SDK is configured for chain ${a}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${a} — point the provider at the same chain.`);let o=i.s(qe,{calldata:await this.#r(t),from:t.from,nonce:n?.nonce,gasLimit:n?.gasLimit,fees:n?.fees}),s=await this.#e.prepareTransaction(o);return{kind:t.kind,unsignedTx:s,from:o.from}}async#r(t){switch(t.kind){case`ConfidentialTransfer`:return this.#i(t);case`ConfidentialTransferFrom`:return this.#a(t);case`SetOperator`:return this.#o(t);case`Unwrap`:return this.#s(t);case`UnwrapAll`:return this.#c(t);case`FinalizeUnwrap`:return this.#l(t);case`ApproveUnderlying`:return this.#u(t);case`Wrap`:return this.#d(t);case`TransferAndCall`:return this.#f(t);case`DelegateDecryption`:return this.#p(t);case`RevokeDelegation`:return this.#m(t);default:throw new e.t(`OfflineService.prepare: unsupported transaction kind '${t.kind}'.`)}}async#i(e){e=i.s(Pe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransfer`);return t.D(e.token,e.to,o,a)}async#a(e){e=i.s(Fe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransferFrom`);return t.k(e.token,e.owner,e.to,o,a)}#o(e){return e=i.s(Ie,e),t.P(e.token,e.operator,e.until)}async#s(e){e=i.s(Le,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for Unwrap`);return t.I(e.token,e.from,e.to,o,a)}async#c(e){e=i.s(Re,e);let n=await this.#e.readContract(t.w(e.token,e.from));return t.L(e.token,e.from,e.to,n)}async#l(e){e=i.s(Q,e);let n=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw b(e,`Public decryption failed during FinalizeUnwrap`)}),r=n.clearValues[0]?.value;return o.t(r,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),t.A(e.wrapper,e.unwrapRequestIdOrAmount,r,n.checkSignaturesArgs.decryptionProof)}#u(e){return e=i.s(ze,e),t.v(e.underlying,e.spender,e.amount)}#d(e){return e=i.s(Be,e),t.R(e.wrapper,e.to,e.amount)}#f(e){return e=i.s(He,e),x(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=i.s(Ue,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new v(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new g(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):E;return C(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=i.s(We,e),w(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}},Ye=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e){this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Ce(e.storage,this.#i),this.#u=new je({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#n=t,this.#t=e.registryTTL,this.#l=new i.c({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),e.signer&&(this.#c=new De({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Me({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Ne({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Je({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new G({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new K({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new q({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new J(this.#d)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new be(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=pe,exports.AclPausedError=ee,exports.AclTopics=V,exports.BalanceCheckUnavailableError=n.u,exports.BaseSigner=i.t,exports.ChainMismatchError=n.h,exports.ChromeSessionStorage=Y,exports.ConfigurationError=e.t,exports.Decryption=q,exports.DecryptionFailedError=n._,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=_,exports.DelegationCooldownError=f,exports.DelegationDelegateEqualsContractError=g,exports.DelegationExpirationTooSoonError=v,exports.DelegationExpiredError=m,exports.DelegationExpiryUnchangedError=h,exports.DelegationNotFoundError=p,exports.DelegationNotPropagatedError=y,exports.DelegationSelfNotAllowedError=d,exports.Delegations=K,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.d,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.v,exports.IndexedDBStorage=i.h,exports.InsufficientAllowanceError=n.f,exports.InsufficientConfidentialBalanceError=n.p,exports.InsufficientERC20BalanceError=n.m,exports.InvalidTransportKeyPairError=t.Y,exports.MemoryStorage=i.p,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.X,exports.NotEntitledError=u,exports.Offline=J,exports.Permits=G,exports.RelayerRequestFailedError=e.n,exports.RpcRateLimitError=n.g,exports.SignerNotConfiguredError=t.B,exports.SignerRequiredError=t.V,exports.SigningFailedError=t.K,exports.SigningRejectedError=t.q,exports.TOKEN_TOPICS=le,exports.Token=n.t,exports.Topics=k,exports.TransactionRevertedError=t.G,exports.TransportKeyPairExpiredError=t.Z,exports.WalletAccountNotReadyError=t.H,exports.WalletNotConnectedError=t.U,exports.WrappedToken=be,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.o,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Ye,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=me,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ae,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=W,exports.decodeAclEvents=ue,exports.decodeConfidentialTransfer=oe,exports.decodeDelegatedForUserDecryption=H,exports.decodeOnChainEvent=z,exports.decodeOnChainEvents=se,exports.decodeRevokedDelegationForUserDecryption=U,exports.decodeUnwrapFinalized=R,exports.decodeUnwrapRequested=L,exports.decodeWrap=I,exports.delegateForUserDecryptionContract=C,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=de,exports.findRevokedDelegationForUserDecryption=fe,exports.findUnwrapRequested=B,exports.findWrap=ce,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=T,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.g,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.c,exports.isHandleDelegatedContract=ie,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=l,exports.memoryStorage=i.m,exports.nameContract=t.S,exports.polygonAmoy=a.c,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=w,exports.sepolia=a.l,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=x,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.wrapContract=t.R;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs"),o=require("./assertions.cjs");let s=require("viem"),c=require("zod/mini");function l(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var u=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},d=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},ee=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const te=[n._,t.X,e.n,y,t.q,t.K,u,n.g,t.Y];function b(r,i,a={}){if(te.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.Y(r.message,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new y(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new u({encryptedValue:e.g(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.g(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.h(r)?new n.g(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.X(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new y(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n._(i,{cause:r})}function ne(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.v(r,{cause:t})}const re=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function x(e,t,n,r=`0x`){return{address:e,abi:re,functionName:`transferAndCall`,args:[t,n,r]}}const S=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function C(e,t,n,r){return{address:e,abi:S,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function w(e,t,n){return{address:e,abi:S,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function T(e,t,n,r){return{address:e,abi:S,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function ie(e,t,n,r,i){return{address:e,abi:S,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const E=2n**64n-1n;function ae(e){return i.i(e.signer,e.provider,e)}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}function O(e){return(0,s.keccak256)((0,s.toBytes)(e))}const k={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function A(e){return(0,s.getAddress)(D(e.slice(-40)))}function j(e){return e}function M(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function N(e,t){return(0,s.getAddress)(D(M(e,t).slice(-40)))}function P(e,t){return BigInt(`0x`+M(e,t))}function F(e,t){return D(M(e,t))}function oe(e){return e.topics[0]!==k.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:j(e.topics[3])}}function I(e){return e.topics[0]!==k.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:P(e.data,0),encryptedWrappedAmount:F(e.data,1)}}function L(e){return e.topics[0]!==k.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0)}}function R(e){return e.topics[0]!==k.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:j(e.topics[2]),encryptedAmount:F(e.data,0),cleartextAmount:P(e.data,1)}}function z(e){return oe(e)??I(e)??L(e)??R(e)}function se(e){let t=[];for(let n of e){let e=z(n);e&&t.push(e)}return t}function B(e){for(let t of e){let e=L(t);if(e)return e}return null}function ce(e){for(let t of e){let e=I(t);if(e)return e}return null}const le=[k.ConfidentialTransfer,k.Wrap,k.UnwrapRequested,k.UnwrapFinalized],V={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function H(e){return e.topics[0]!==V.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2),newExpirationDate:P(e.data,3)}}function U(e){return e.topics[0]!==V.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:N(e.data,0),delegationCounter:P(e.data,1),oldExpirationDate:P(e.data,2)}}function W(e){return H(e)??U(e)}function ue(e){let t=[];for(let n of e){let e=W(n);e&&t.push(e)}return t}function de(e){for(let t of e){let e=H(t);if(e)return e}return null}function fe(e){for(let t of e){let e=U(t);if(e)return e}return null}const pe=[V.DelegatedForUserDecryption,V.RevokedDelegationForUserDecryption];var G=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.W(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await n.a(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.a(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,s.getAddress)((await n.i(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,s.getAddress)((await n.i(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},K=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.W(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.i(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.i(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},q=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.W(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.i(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.i(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let n=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),r={};return n.checkSignaturesArgs.handlesList.forEach((e,t)=>{o.r(n.clearValues[t],`result.clearValues[${t}]`),r[e]=n.clearValues[t].value}),{clearValues:r,abiEncodedClearValues:n.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:n.checkSignaturesArgs.decryptionProof}}catch(e){throw b(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.i(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},J=class{#e;constructor(e){this.#e=e}prepare(e,t){return this.#e.prepare(e,t)}},Y=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const me=new Y;function X(e){return`zama:pending-unshield:${i.l(e)}`}const he=c.z.union([c.z.pipe(i.d,c.z.transform(e=>({unwrapTxHash:e}))),c.z.pipe(c.z.object({version:c.z.literal(1),unwrapTxHash:i.d,unwrapRequestId:c.z.optional(i.d)}),c.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function ge(e,t,n,r){if(r===void 0){await e.set(X(t),n);return}await e.set(X(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function _e(e,t){return(await ve(e,t))?.unwrapTxHash??null}async function ve(e,t){let n=X(t),r=await e.get(n);if(r==null)return null;let i=he.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ye(e,t){await e.delete(X(t))}var be=class extends n.t{#e;#t=null;#n=null;#r(e){try{return o.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.B(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t._(n,(0,s.getAddress)(e),this.address))}async shield(r,i){let a=await n.i(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#s(),l=(0,s.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e._(t)})}if(u<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return o?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,s.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:x(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.i(`wrap`,this.sdk.signer,this.sdk.provider),o=await this.#s(),c=(0,s.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(o,c))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 balance for wrap validation (token: ${o})`,{cause:e._(t)})}if(l<r)throw new n.m(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${o})`,{requested:r,available:l,token:o});let u;try{u=await this.sdk.provider.readContract(t._(o,c,this.address))}catch(t){throw t instanceof e.r?t:new n.d(`Could not read ERC-20 allowance for wrap validation (token: ${o})`,{cause:e._(t)})}if(u<r)throw new n.f(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${o}).`,{requested:r,available:u,token:o});let d=i?.to?(0,s.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.R(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,s.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.R(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,s.getAddress)(r.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.z(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.z(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(n,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(n)}catch(n){throw n instanceof e.r?n:new t.G(`Failed to get unwrap receipt`,{cause:n})}let a=this.#o(i.logs);return this.#c(a,n,crypto.randomUUID(),r)}async getPendingUnshield(){return _e(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,s.getAddress)((await n.i(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[o]=i;if(!o)throw new n.v(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,o,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,s.getAddress)((await n.i(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.c(r))throw new n._(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.a(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let n=B(e);if(!n)throw new t.G(`No UnwrapRequested event found in unwrap receipt`);return n.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.z(`unshield: savePendingUnshield`,()=>ge(this.sdk.storage,this.address,n),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.z(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a=await this.finalizeUnwrap(e);return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.z(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await t.z(`unshield: clearPendingUnshield`,()=>ye(this.sdk.storage,this.address),this.sdk.logger),a}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),o=(0,s.getAddress)((await n.i(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,o,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}};const xe=c.z.union([c.z.bigint(),c.z.boolean(),i.u]),Se=c.z.array(c.z.string());var Ce=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=xe.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,s.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,s.getAddress)(e)}:${(0,s.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Se.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function we(e,t){let r=Te(e,t);if(!r)throw new n._(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function Te(e,t){let n=i.l(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const Ee=e=>new Promise(t=>setTimeout(t,e));var De=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,s.getAddress)(t);return this.#s(e,{requesterAddress:r,aclActorAddress:r,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n);return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,s.getAddress)(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#f(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0}))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof y))throw t;await Ee(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,s.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:o});for(let t of c)this.#l(t,e);return{items:c}}catch(e){if(n.l(e))throw e;if(c.length===1){let[n=this.#d()]=c;return n.error=this.#u(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,s.getAddress)(t)}),{items:c}}}let u=!1;return await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#l(e,n)}catch(r){if(n.l(r))throw u=!0,r;e.error=this.#u(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,s.getAddress)(t)})}}),a),{items:c}}async#o(t,n,r,i){let a=we(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a){if(r.length===0)return{};let o=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,s.getAddress)(e.contractAddress)})),c={},l=[];for(let e of o)n.c(e.encryptedValue)?c[e.encryptedValue]=0n:l.push(e);if(l.length===0)return c;let u=Array.from(new Set(o.map(e=>e.contractAddress))),d=Array.from(new Set(l.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(d)}catch(t){throw e.h(t)?this.#c(t,`the delegation pre-check`):t}let f=[];for(let e of l){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?f.push(e):c[e.encryptedValue]=t}if(f.length===0)return c;let p=await i.resolveCredentials(u),m=new Map;for(let e of f){let t=m.get(e.contractAddress);t?t.push(e.encryptedValue):m.set(e.contractAddress,[e.encryptedValue])}let h=[];for(let[e,t]of m)for(let r of n.s(t))h.push({contractAddress:e,encryptedValues:r});let g=Date.now(),_=f.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:_}),await n.r(h.map(({contractAddress:e,encryptedValues:t})=>async()=>{let r;try{r=await i.decryptContract({credentials:p,contractAddress:e,encryptedValues:t,options:a})}catch(t){throw b(t,i.errorMessage,{isDelegated:i.delegated,contractAddress:e,account:i.aclActorAddress})}for(let n=0;n<t.length;n++){let a=t[n],o=r[n]?.value;a!==void 0&&o!==void 0&&(c[a]=o,await this.#e.set(i.requesterAddress,e,a,o))}let o=t.filter(e=>c[e]===void 0);if(o.length>0)throw new n._(`${i.errorMessage}: relayer returned no clear value for ${o.length} of ${t.length} handle(s) on ${e}`,{cause:AggregateError(o.map(t=>new n._(`No clear value for handle ${t} on ${e}`)),`${o.length} handle(s) missing a clear value on ${e}`)})}),5);let e={};for(let t of _){let n=c[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-g,encryptedValues:_,result:e}),c}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e._(r),durationMs:Date.now()-g,encryptedValues:_}),b(n,i.errorMessage,{isDelegated:i.delegated})}}#c(t,r){return new n.g(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#l(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n._(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#u(t,n,r){return t instanceof e.r?t:b(t,n,r)}#d(){throw new n._(`Batch delegated decryption invariant failed: missing item`)}async#f(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function Oe(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const Z={AlreadyDelegatedOrRevokedInSameBlock:e=>new f(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new _(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new ee(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new d(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new g(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new v(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new h(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new p(`Cannot revoke: no active delegation exists.`,{cause:e})};function ke(e){return Object.hasOwn(Z,e)}function Ae(e,t){let n=Oe(e);if(n&&ke(n))return Z[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Z))if(r.includes(e))return n(t);return null}var je=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new v(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(t),o=(0,s.getAddress)(n),c=(0,s.getAddress)(r);if(o===c)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===a)throw new g(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):E,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===u)throw new h(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:a,config:C(l,o,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),o=(0,s.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new p(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:i,config:w(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===E?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(T(r,(0,s.getAddress)(t),(0,s.getAddress)(n),(0,s.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof t.G))return;let n=Ae(e.cause??e,e);if(n)throw n}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof p||t instanceof m){let n=(0,s.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,s.getAddress)(e),i=(0,s.getAddress)(t),a=(0,s.getAddress)(n),{isActive:o,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw c===0n?new p(`No active delegation from ${i} to ${a} for ${r}`):new m(`Delegation from ${i} to ${a} for ${r} has expired`)}},Me=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,s.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e._(n),durationMs:Date.now()-i},a),ne(n,`Encryption failed`)}}},Ne=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.z(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.z(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.z(`wallet account listener`,()=>n(e),this.#i)))}};const Pe=c.z.object({kind:c.z.literal(`ConfidentialTransfer`),from:i.u,token:i.u,to:i.u,amount:c.z.bigint()}),Fe=c.z.object({kind:c.z.literal(`ConfidentialTransferFrom`),from:i.u,token:i.u,owner:i.u,to:i.u,amount:c.z.bigint()}),Ie=c.z.object({kind:c.z.literal(`SetOperator`),from:i.u,token:i.u,operator:i.u,until:i.f}),Le=c.z.object({kind:c.z.literal(`Unwrap`),from:i.u,token:i.u,to:i.u,amount:c.z.bigint()}),Re=c.z.object({kind:c.z.literal(`UnwrapAll`),from:i.u,token:i.u,to:i.u}),Q=c.z.object({kind:c.z.literal(`FinalizeUnwrap`),from:i.u,wrapper:i.u,unwrapRequestIdOrAmount:i.d}),ze=c.z.object({kind:c.z.literal(`ApproveUnderlying`),from:i.u,underlying:i.u,spender:i.u,amount:c.z.bigint()}),Be=c.z.object({kind:c.z.literal(`Wrap`),from:i.u,wrapper:i.u,to:i.u,amount:c.z.bigint()}),Ve=i.d.check(c.z.refine(e=>e===`0x`||(0,s.size)(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),He=c.z.object({kind:c.z.literal(`TransferAndCall`),from:i.u,underlying:i.u,wrapper:i.u,amount:c.z.bigint(),recipientData:c.z.optional(Ve)}),Ue=c.z.object({kind:c.z.literal(`DelegateDecryption`),from:i.u,contractAddress:i.u,delegateAddress:i.u,expirationDate:c.z.optional(c.z.date())}),We=c.z.object({kind:c.z.literal(`RevokeDelegation`),from:i.u,contractAddress:i.u,delegateAddress:i.u});c.z.discriminatedUnion(`kind`,[Pe,Fe,Ie,Le,Re,Q,ze,Be,He,Ue,We]);const Ge=c.z.strictObject({maxFeePerGas:c.z.bigint(),maxPriorityFeePerGas:c.z.bigint()}),$=c.z.object({nonce:c.z.optional(c.z.int().check(c.z.nonnegative())),gasLimit:c.z.optional(c.z.bigint()),fees:c.z.optional(Ge)}),Ke=c.z.object({address:i.u,abi:c.z.array(c.z.unknown()),functionName:c.z.string(),args:c.z.array(c.z.unknown()),value:c.z.optional(c.z.bigint()),gas:c.z.optional(c.z.bigint())}),qe=c.z.extend($,{from:i.u,calldata:Ke});var Je=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(t,n){n&&=i.s($,n);let r=await this.#e.getChainId(),a=this.#t.chain.id;if(r!==a)throw new e.t(`Offline.prepare: provider is on chain ${r} but the SDK is configured for chain ${a}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${a} — point the provider at the same chain.`);let o=i.s(qe,{calldata:await this.#r(t),from:t.from,nonce:n?.nonce,gasLimit:n?.gasLimit,fees:n?.fees}),s=await this.#e.prepareTransaction(o);return{kind:t.kind,unsignedTx:s,from:o.from}}async#r(t){switch(t.kind){case`ConfidentialTransfer`:return this.#i(t);case`ConfidentialTransferFrom`:return this.#a(t);case`SetOperator`:return this.#o(t);case`Unwrap`:return this.#s(t);case`UnwrapAll`:return this.#c(t);case`FinalizeUnwrap`:return this.#l(t);case`ApproveUnderlying`:return this.#u(t);case`Wrap`:return this.#d(t);case`TransferAndCall`:return this.#f(t);case`DelegateDecryption`:return this.#p(t);case`RevokeDelegation`:return this.#m(t);default:throw new e.t(`OfflineService.prepare: unsupported transaction kind '${t.kind}'.`)}}async#i(e){e=i.s(Pe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransfer`);return t.D(e.token,e.to,o,a)}async#a(e){e=i.s(Fe,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for ConfidentialTransferFrom`);return t.k(e.token,e.owner,e.to,o,a)}#o(e){return e=i.s(Ie,e),t.P(e.token,e.operator,e.until)}async#s(e){e=i.s(Le,e);let{encryptedValues:r,inputProof:a}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from}),o=r[0];if(!o)throw new n.v(`Encryption returned no handles for Unwrap`);return t.I(e.token,e.from,e.to,o,a)}async#c(e){e=i.s(Re,e);let n=await this.#e.readContract(t.w(e.token,e.from));return t.L(e.token,e.from,e.to,n)}async#l(e){e=i.s(Q,e);let n=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount]}).catch(e=>{throw b(e,`Public decryption failed during FinalizeUnwrap`)}),r=n.clearValues[0]?.value;return o.t(r,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),t.A(e.wrapper,e.unwrapRequestIdOrAmount,r,n.checkSignaturesArgs.decryptionProof)}#u(e){return e=i.s(ze,e),t.v(e.underlying,e.spender,e.amount)}#d(e){return e=i.s(Be,e),t.R(e.wrapper,e.to,e.amount)}#f(e){return e=i.s(He,e),x(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=i.s(Ue,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new v(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new d(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new g(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):E;return C(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=i.s(We,e),w(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}},Ye=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e){this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new Ce(e.storage,this.#i),this.#u=new je({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#n=t,this.#t=e.registryTTL,this.#l=new i.c({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),e.signer&&(this.#c=new De({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new Me({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Ne({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Je({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new G({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new K({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new q({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new J(this.#d)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new be(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};exports.ACL_TOPICS=pe,exports.AclPausedError=ee,exports.AclTopics=V,exports.BalanceCheckUnavailableError=n.u,exports.BaseSigner=i.t,exports.ChainMismatchError=n.h,exports.ChromeSessionStorage=Y,exports.ConfigurationError=e.t,exports.Decryption=q,exports.DecryptionFailedError=n._,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=_,exports.DelegationCooldownError=f,exports.DelegationDelegateEqualsContractError=g,exports.DelegationExpirationTooSoonError=v,exports.DelegationExpiredError=m,exports.DelegationExpiryUnchangedError=h,exports.DelegationNotFoundError=p,exports.DelegationNotPropagatedError=y,exports.DelegationSelfNotAllowedError=d,exports.Delegations=K,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.d,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.v,exports.IndexedDBStorage=i.h,exports.InsufficientAllowanceError=n.f,exports.InsufficientConfidentialBalanceError=n.p,exports.InsufficientERC20BalanceError=n.m,exports.InvalidTransportKeyPairError=t.Y,exports.MemoryStorage=i.p,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.X,exports.NotEntitledError=u,exports.Offline=J,exports.Permits=G,exports.RelayerRequestFailedError=e.n,exports.RpcRateLimitError=n.g,exports.SignerNotConfiguredError=t.B,exports.SignerRequiredError=t.V,exports.SigningFailedError=t.K,exports.SigningRejectedError=t.q,exports.TOKEN_TOPICS=le,exports.Token=n.t,exports.Topics=k,exports.TransactionRevertedError=t.G,exports.TransportKeyPairExpiredError=t.Z,exports.WalletAccountNotReadyError=t.H,exports.WalletNotConnectedError=t.U,exports.WrappedToken=be,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.o,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Ye,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=me,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ae,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=W,exports.decodeAclEvents=ue,exports.decodeConfidentialTransfer=oe,exports.decodeDelegatedForUserDecryption=H,exports.decodeOnChainEvent=z,exports.decodeOnChainEvents=se,exports.decodeRevokedDelegationForUserDecryption=U,exports.decodeUnwrapFinalized=R,exports.decodeUnwrapRequested=L,exports.decodeWrap=I,exports.delegateForUserDecryptionContract=C,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=de,exports.findRevokedDelegationForUserDecryption=fe,exports.findUnwrapRequested=B,exports.findWrap=ce,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=T,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.g,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.c,exports.isHandleDelegatedContract=ie,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=l,exports.memoryStorage=i.m,exports.nameContract=t.S,exports.polygonAmoy=a.c,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=w,exports.sepolia=a.l,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=x,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.wrapContract=t.R;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|