@zama-fhe/sdk 3.3.0-alpha.8 → 3.3.0
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/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/esm/{index-DBchRNlE.d.ts → index-C1Mtc8Rw.d.ts} +27 -43
- package/dist/esm/index.d.ts +11 -7
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +17 -2
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/package.json +54 -52
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("./wrappers-registry.cjs"),n=require("./encryption.cjs"),r=require("./token.cjs"),i=require("./relayer-cleartext.cjs"),a=require("./timeout.cjs"),o=require("./assertions.cjs"),s=require("./base-signer.cjs"),c=require("./validation.cjs"),l=require("./chains.cjs");let u=require("viem"),d=require("zod/mini");function f(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var p=class extends e.r{constructor(t,n){super(e.i.TransportKeyPairExpired,t,n),this.name=`TransportKeyPairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidTransportKeyPair,t,n),this.name=`InvalidTransportKeyPairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},x=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},C=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},w=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},T=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function E(s,c,l={}){if(s instanceof n.t||s instanceof h||s instanceof e.n||s instanceof T||s instanceof t.W||s instanceof t.U||s instanceof i.n||s instanceof r.b||s instanceof a.n||s instanceof a.t)return s;let u=s instanceof Error?s.message:c;if(s instanceof Error&&o.d(s.message))return l.isDelegated?new T(`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:s}):new i.n({encryptedValue:o.m(s.message)??``,contractAddress:l.contractAddress??``,account:l.account??``},{cause:s});if(o.l(s))return new r.b(u,{cause:s,retryAfter:o.c(s)});let d=o.s(s);return d===void 0&&o.p(s)?new r.b(u,{cause:s,retryAfter:o.c(s)}):d===400?new h(s instanceof Error?s.message:`No ciphertext for this account`,{cause:s}):l.isDelegated&&d===500?new T(`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:s}):d===void 0?new n.t(c,{cause:s}):new e.n(u,d,{cause:s,retryAfter:o.c(s)})}function ee(t,r){if(t instanceof e.r)return t;let i=o.s(t);return i===void 0?new n.n(r,{cause:t}):new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:o.c(t)})}function te(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}const ne=[{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 O(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}function re(e){return s.i(e.signer,e.provider,e)}var k=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return t.H(this.#r,e)}async decryptValues(e){let t=this.#i(`decryptValues`),n=await r.s(`decryptValues`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecryptValues(e,t,n=t,i){let a=this.#i(`delegatedDecryptValues`),o=await r.s(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedUserDecrypt(e,t,o.address,n,i)}async decryptPublicValues(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw E(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await r.s(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:i,waitForPropagation:a})}},A=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.H(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.s(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.s(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}},j=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.H(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await r.c(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#a(`grantDelegationPermit`);await r.c(`grantDelegationPermit`,this.#e,this.#t),await n.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 n=this.#a(`revokePermits`),i=(0,u.getAddress)((await r.s(`revokePermits`,this.#e,this.#t)).address);try{await n.revokePermits(e)}finally{await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(i),this.#i)}}async clear(){let e=this.#a(`clear`),n=(0,u.getAddress)((await r.s(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(n),this.#i)}}};const ie=d.z.union([d.z.bigint(),d.z.boolean(),s.p]),ae=d.z.array(d.z.string());var oe=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=ie.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,u.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,u.getAddress)(e)}:${(0,u.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=ae.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 se(e,t){let r=N(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return M(e,r)}function ce(e,t){let r=N(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...M(e,r),delegatorAddress:r.delegatorAddress}}function M(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function N(e,t){let n=s.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}const le=e=>new Promise(t=>setTimeout(t,e));var ue=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=(0,u.getAddress)(t);return this.#o(e,{requesterAddress:n,aclActorAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...se(e,t),signerAddress:n}),errorMessage:`Failed to decrypt encrypted values`})}async delegatedUserDecrypt(e,t,n,r,i){let a=(0,u.getAddress)(t),o=(0,u.getAddress)(n);return this.#a(i?.waitForPropagation??!0,()=>this.#o(e,{requesterAddress:(0,u.getAddress)(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#d(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...ce(e,t),delegateAddress:o}),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 T))throw t;await le(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,u.getAddress)(e.contractAddress)}));if(s.length===0)return{items:s};let c=(0,u.getAddress)(i);try{let e=await this.delegatedUserDecrypt(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:o});for(let t of s)this.#c(t,e);return{items:s}}catch(e){if(r.m(e))throw e;if(s.length===1){let[n=this.#u()]=s;return n.error=this.#l(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,u.getAddress)(t)}),{items:s}}}let l=!1;return await r.a(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1});this.#c(e,r)}catch(n){if(r.m(n))throw l=!0,n;e.error=this.#l(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,u.getAddress)(t)})}}),a),{items:s}}async#o(t,n){if(t.length===0)return{};let i=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},s=[];for(let e of i)r.i(e.encryptedValue)?a[e.encryptedValue]=0n:s.push(e);if(s.length===0)return a;let c=Array.from(new Set(i.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw o.p(e)?this.#s(e,`the delegation pre-check`):e}let d=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?d.push(e):a[e.encryptedValue]=t}if(d.length===0)return a;let f=await n.resolveCredentials(c),p=new Map;for(let e of d){let t=p.get(e.contractAddress);t?t.push(e.encryptedValue):p.set(e.contractAddress,[e.encryptedValue])}let m=Date.now(),h=d.map(e=>e.encryptedValue);try{this.#i({type:r.o.DecryptStart,encryptedValues:h}),await r.a([...p.entries()].map(([e,t])=>async()=>{let r;try{r=await n.decryptContract({credentials:f,contractAddress:e,encryptedValues:t})}catch(t){throw E(t,n.errorMessage,{isDelegated:n.delegated,contractAddress:e,account:n.aclActorAddress})}for(let[t,i]of Object.entries(r))a[t]=i,await this.#e.set(n.requesterAddress,e,t,i)}),5);let e={};for(let t of h){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.o.DecryptEnd,durationMs:Date.now()-m,encryptedValues:h,result:e}),a}catch(t){let i=t instanceof e.r&&t.cause instanceof Error?t.cause:t;throw this.#i({type:r.o.DecryptError,error:o.h(i),durationMs:Date.now()-m,encryptedValues:h}),E(t,n.errorMessage,{isDelegated:n.delegated})}}#s(e,t){return new r.b(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:o.c(e)})}#c(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#l(t,n,r){return t instanceof e.r?t:E(t,n,r)}#u(){throw new n.t(`Batch delegated decryption invariant failed: missing item`)}async#d(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 de(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 P={AlreadyDelegatedOrRevokedInSameBlock:e=>new _(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new S(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new C(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new g(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new w(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new b(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new v(`Cannot revoke: no active delegation exists.`,{cause:e})};function fe(e){return e in P}function pe(e,t){let n=de(e);if(n&&fe(n))return P[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(P))if(r.includes(e))return n(t);return null}var me=class{#e;#t;#n;#r;constructor({provider:e,relayer:t,emitEvent:n=()=>{},logger:r}){this.#e=e,this.#t=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new w(`Expiration date must be at least 1 hour in the future`);let o=(0,u.getAddress)(t),s=(0,u.getAddress)(n),c=(0,u.getAddress)(i);if(s===c)throw new g(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new x(`Delegate address cannot be the same as the contract address (${o}).`);let l=await this.#t.getAclAddress(),d=a?BigInt(Math.floor(a.getTime()/1e3)):r.l,f;try{f=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===d)throw new b(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:t,config:r.u(l,s,o,d)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=(0,u.getAddress)(t),o=(0,u.getAddress)(n),s=(0,u.getAddress)(i),c=await this.#t.getAclAddress(),l;try{l=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new v(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:r.p(c,o,a)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===r.l?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=await this.#t.getAclAddress();return this.#e.readContract(r.d(i,(0,u.getAddress)(t),(0,u.getAddress)(n),(0,u.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:n,config:i}){try{return await r.n({operation:e,signer:t,provider:this.#e,config:i,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof r.x))return;let t=pe(e.cause??e,e);if(t)throw t}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 v||t instanceof y){let n=(0,u.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let i=(0,u.getAddress)(e),a=(0,u.getAddress)(t),o=(0,u.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new v(`No active delegation from ${a} to ${o} for ${i}`);if(s!==r.l&&s<=await this.#e.getBlockTimestamp())throw new y(`Delegation from ${a} to ${o} for ${i} has expired`)}},he=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(e){let t=Date.now();try{this.#t({type:r.o.EncryptStart},e.contractAddress);let n=await this.#e.encrypt(e);return this.#t({type:r.o.EncryptEnd,durationMs:Date.now()-t},e.contractAddress),n}catch(n){throw this.#t({type:r.o.EncryptError,error:o.h(n),durationMs:Date.now()-t},e.contractAddress),ee(n,`Encryption failed`)}}},ge=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.relayer,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.L(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.L(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.L(`wallet account listener`,()=>n(e),this.#i)))}};function F(e){return(0,u.keccak256)((0,u.toBytes)(e))}const I={ConfidentialTransfer:F(`ConfidentialTransfer(address,address,bytes32)`),Wrap:F(`Wrap(address,uint256,bytes32)`),UnwrapRequested:F(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:F(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function L(e){return(0,u.getAddress)(D(e.slice(-40)))}function R(e){return e}function z(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function B(e,t){return(0,u.getAddress)(D(z(e,t).slice(-40)))}function V(e,t){return BigInt(`0x`+z(e,t))}function H(e,t){return D(z(e,t))}function U(e){return e.topics[0]!==I.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:L(e.topics[1]),to:L(e.topics[2]),encryptedAmount:R(e.topics[3])}}function W(e){return e.topics[0]!==I.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:L(e.topics[1]),roundedAmount:V(e.data,0),encryptedWrappedAmount:H(e.data,1)}}function G(e){return e.topics[0]!==I.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:L(e.topics[1]),unwrapRequestId:R(e.topics[2]),encryptedAmount:H(e.data,0)}}function K(e){return e.topics[0]!==I.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:L(e.topics[1]),unwrapRequestId:R(e.topics[2]),encryptedAmount:H(e.data,0),cleartextAmount:V(e.data,1)}}function q(e){return U(e)??W(e)??G(e)??K(e)}function _e(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=G(t);if(e)return e}return null}function ve(e){for(let t of e){let e=W(t);if(e)return e}return null}const ye=[I.ConfidentialTransfer,I.Wrap,I.UnwrapRequested,I.UnwrapFinalized],Y={DelegatedForUserDecryption:F(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:F(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:L(e.topics[1]),delegate:L(e.topics[2]),contractAddress:B(e.data,0),delegationCounter:V(e.data,1),oldExpirationDate:V(e.data,2),newExpirationDate:V(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:L(e.topics[1]),delegate:L(e.topics[2]),contractAddress:B(e.data,0),delegationCounter:V(e.data,1),oldExpirationDate:V(e.data,2)}}function be(e){return X(e)??Z(e)}function xe(e){let t=[];for(let n of e){let e=be(n);e&&t.push(e)}return t}function Se(e){for(let t of e){let e=X(t);if(e)return e}return null}function Ce(e){for(let t of e){let e=Z(t);if(e)return e}return null}const we=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];var Q=class extends r.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.R(e,{cause:n})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(t.p(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#o();return this.sdk.provider.readContract(t.h(n,(0,u.getAddress)(e),this.address))}async shield(n,i){let a=await r.s(`shield`,this.sdk.signer,this.sdk.provider),s=await this.isPayable(),c=await this.#o(),l=(0,u.getAddress)(a.address),d;try{d=await this.sdk.provider.readContract(t._(c,l))}catch(t){throw t instanceof e.r?t:new r.g(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:o.h(t)})}if(d<n)throw new r.v(`Insufficient ERC-20 balance: requested ${n}, available ${d} (token: ${c})`,{requested:n,available:d,token:c});return s?this.#i(n,c,l,i):this.#a(n,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,u.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:O(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#c(e,i===`max`,r);let a=r?.to?(0,u.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.I(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let n=await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#o(),a=(0,u.getAddress)(n.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t.h(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.g(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.L(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#s(l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.L(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#s(r.txHash,n,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async unwrap(e){this.#r(`unwrap`);let i=(0,u.getAddress)((await r.s(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i}),[s]=a;if(!s)throw new n.n(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`unwrap`,config:t.P(this.address,i,i,s,o)})}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,u.getAddress)((await r.s(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),i=await this.readConfidentialBalanceOf(e);if(r.i(i))throw new n.t(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:t.F(this.address,e,e,i)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await r.c(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e]),i=n.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.O(this.address,e,i,n.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.N(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(n,i,a){this.emit({type:r.o.UnshieldPhase1Submitted,txHash:n,operationId:i});let o;try{o=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new r.x(`Failed to get unshield receipt`,{cause:t})}let s=J(o.logs);if(!s)throw new r.x(`No UnwrapRequested event found in unshield receipt`);this.emit({type:r.o.UnshieldPhase2Started,operationId:i}),t.L(`unshield: onFinalizing`,()=>a?.onFinalizing?.(),this.sdk.logger);let c=await this.finalizeUnwrap(s.unwrapRequestId??s.encryptedAmount);return this.emit({type:r.o.UnshieldPhase2Submitted,txHash:c.txHash,operationId:i}),t.L(`unshield: onFinalizeSubmitted`,()=>a?.onFinalizeSubmitted?.(c.txHash),this.sdk.logger),c}async#c(e,n,i){this.#r(`approveUnderlying`);let a=await this.#o(),o=(0,u.getAddress)((await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),s=await this.sdk.provider.readContract(t.h(a,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(a,this.address,0n)});let c=n?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.g(a,this.address,c),onSubmitted:i?.onApprovalSubmitted})}},Te=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#n=e.onEvent??function(){},this.#r=e.logger,this.#i=new oe(e.storage,this.#r),this.#l=new me({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this),logger:this.#r});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new s.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#t=t,this.#e=e.registryTTL,e.signer&&(this.#c=new s.d({relayer:this.relayer,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage,logger:this.#r}),this.#s=new ue({cache:this.#i,credentialService:this.#c,delegationService:this.#l,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#o=new he({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#a=new ge({signer:e.signer,relayer:this.relayer,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.permits=new j({signer:this.signer,provider:this.provider,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.delegations=new A({signer:this.signer,provider:this.provider,delegationService:this.#l}),this.decryption=new k({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#s})}onWalletAccountChange(e){return this.#a.onWalletAccountChange(e)}get logger(){return this.#r}emitEvent(e,t){try{this.#n({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#r.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new s.o({provider:this.provider,registryAddresses:{...this.#t,...e},registryTTL:this.#e})}async encrypt(e){return this.#o.encrypt(e)}createToken(e){return new r.t(this,e)}createWrappedToken(e){return new Q(this,e)}dispose(){this.#a.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${s.f(e)}`}const Ee=d.z.union([d.z.pipe(s.m,d.z.transform(e=>({unwrapTxHash:e}))),d.z.pipe(d.z.object({version:d.z.literal(1),unwrapTxHash:s.m,unwrapRequestId:d.z.optional(s.m)}),d.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function De(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Oe(e,t){return(await ke(e,t))?.unwrapTxHash??null}async function ke(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Ee.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Ae(e,t){await e.delete($(t))}var je=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 je;exports.ACL_TOPICS=we,exports.AclPausedError=C,exports.AclTopics=Y,exports.BalanceCheckUnavailableError=r.h,exports.BaseSigner=s.t,exports.ChainMismatchError=r.y,exports.ChromeSessionStorage=je,exports.ConfigurationError=e.t,exports.Decryption=k,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=s.a,exports.DelegationContractIsSelfError=S,exports.DelegationCooldownError=_,exports.DelegationDelegateEqualsContractError=x,exports.DelegationExpirationTooSoonError=w,exports.DelegationExpiredError=y,exports.DelegationExpiryUnchangedError=b,exports.DelegationNotFoundError=v,exports.DelegationNotPropagatedError=T,exports.DelegationSelfNotAllowedError=g,exports.Delegations=A,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=r.g,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=c.n,exports.InsufficientConfidentialBalanceError=r._,exports.InsufficientERC20BalanceError=r.v,exports.InvalidTransportKeyPairError=m,exports.MemoryStorage=s.l,exports.MutableWalletAccountStore=s.n,exports.NoCiphertextError=h,exports.NotEntitledError=i.n,exports.Permits=j,exports.RelayerRequestFailedError=e.n,exports.RpcRateLimitError=r.b,exports.SignerNotConfiguredError=t.R,exports.SignerRequiredError=t.z,exports.SigningFailedError=t.U,exports.SigningRejectedError=t.W,exports.TOKEN_TOPICS=ye,exports.Token=r.t,exports.Topics=I,exports.TransactionRevertedError=r.x,exports.TransportKeyPairExpiredError=p,exports.WalletAccountNotReadyError=t.B,exports.WalletNotConnectedError=t.V,exports.WorkerRecycledError=a.t,exports.WorkerTimeoutError=a.n,exports.WrappedToken=Q,exports.WrappersRegistry=s.o,exports.ZERO_ENCRYPTED_VALUE=r.r,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Te,exports.ZamaSDKEvents=r.o,exports.allowanceContract=t.h,exports.anvil=l.t,exports.approveContract=t.g,exports.balanceOfContract=t._,exports.bscTestnet=l.n,exports.chains=l.r,exports.chromeSessionStorage=Me,exports.clearPendingUnshield=Ae,exports.cleartext=te,exports.confidentialBalanceOfContract=t.S,exports.confidentialTotalSupplyContract=t.C,exports.confidentialTransferContract=t.T,exports.confidentialTransferFromContract=t.D,exports.createConfig=re,exports.createWalletAccountStore=s.r,exports.decimalsContract=t.v,exports.decodeAclEvent=be,exports.decodeAclEvents=xe,exports.decodeConfidentialTransfer=U,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=_e,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=K,exports.decodeUnwrapRequested=G,exports.decodeWrap=W,exports.delegateForUserDecryptionContract=r.u,exports.finalizeUnwrapContract=t.O,exports.findDelegatedForUserDecryption=Se,exports.findRevokedDelegationForUserDecryption=Ce,exports.findUnwrapRequested=J,exports.findWrap=ve,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=r.d,exports.getTokenAddressContract=t.n,exports.getTokenPairContract=t.r,exports.getTokenPairsContract=t.i,exports.getTokenPairsLengthContract=t.a,exports.getTokenPairsSliceContract=t.o,exports.hardhat=l.i,exports.hoodi=l.a,exports.indexedDBStorage=c.r,exports.inferredTotalSupplyContract=t.k,exports.ingenTestnet=l.o,exports.isConfidentialTokenContract=t.d,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.f,exports.isEncryptedValueZero=r.i,exports.isHandleDelegatedContract=r.f,exports.isOperatorContract=t.A,exports.loadPendingUnshield=Oe,exports.loadPendingUnshieldRequest=ke,exports.mainnet=l.s,exports.matchZamaError=f,exports.memoryStorage=s.u,exports.nameContract=t.b,exports.rateContract=t.j,exports.resolveChainRelayers=s.s,exports.resolveStorage=s.c,exports.revokeDelegationContract=r.p,exports.savePendingUnshield=De,exports.sepolia=l.c,exports.setOperatorContract=t.M,exports.supportsInterfaceContract=t.m,exports.symbolContract=t.x,exports.transferAndCallContract=O,exports.underlyingContract=t.N,exports.unwrapContract=t.P,exports.unwrapFromBalanceContract=t.F,exports.wrapContract=t.I;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./encryption.cjs"),r=require("./token.cjs"),i=require("./relayer-cleartext.cjs"),a=require("./timeout.cjs"),o=require("./assertions.cjs"),s=require("./base-signer.cjs"),c=require("./validation.cjs"),l=require("./chains.cjs");let u=require("viem"),d=require("zod/mini");function f(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var p=class extends e.r{constructor(t,n){super(e.i.TransportKeyPairExpired,t,n),this.name=`TransportKeyPairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidTransportKeyPair,t,n),this.name=`InvalidTransportKeyPairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},x=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},C=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},w=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},T=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function E(s,c,l={}){if(s instanceof n.t||s instanceof h||s instanceof e.n||s instanceof T||s instanceof t.W||s instanceof t.U||s instanceof i.n||s instanceof r.b||s instanceof a.n||s instanceof a.t)return s;let u=s instanceof Error?s.message:c;if(s instanceof Error&&o.d(s.message))return l.isDelegated?new T(`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:s}):new i.n({encryptedValue:o.m(s.message)??``,contractAddress:l.contractAddress??``,account:l.account??``},{cause:s});if(o.l(s))return new r.b(u,{cause:s,retryAfter:o.c(s)});let d=o.s(s);return d===void 0&&o.p(s)?new r.b(u,{cause:s,retryAfter:o.c(s)}):d===400?new h(s instanceof Error?s.message:`No ciphertext for this account`,{cause:s}):l.isDelegated&&d===500?new T(`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:s}):d===void 0?new n.t(c,{cause:s}):new e.n(u,d,{cause:s,retryAfter:o.c(s)})}function ee(t,r){if(t instanceof e.r)return t;let i=o.s(t);return i===void 0?new n.n(r,{cause:t}):new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:o.c(t)})}function te(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}const ne=[{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 O(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}function re(e){return s.i(e.signer,e.provider,e)}var k=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return t.H(this.#r,e)}async decryptValues(e){let t=this.#i(`decryptValues`),n=await r.s(`decryptValues`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecryptValues(e,t,n=t,i){let a=this.#i(`delegatedDecryptValues`),o=await r.s(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedUserDecrypt(e,t,o.address,n,i)}async decryptPublicValues(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw E(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await r.s(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:i,waitForPropagation:a})}},A=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.H(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.s(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.s(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}},j=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.H(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await r.c(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#a(`grantDelegationPermit`);await r.c(`grantDelegationPermit`,this.#e,this.#t),await n.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 n=this.#a(`revokePermits`),i=(0,u.getAddress)((await r.s(`revokePermits`,this.#e,this.#t)).address);try{await n.revokePermits(e)}finally{await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(i),this.#i)}}async clear(){let e=this.#a(`clear`),n=(0,u.getAddress)((await r.s(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(n),this.#i)}}};const ie=d.z.union([d.z.bigint(),d.z.boolean(),s.p]),ae=d.z.array(d.z.string());var oe=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=ie.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,u.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,u.getAddress)(e)}:${(0,u.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=ae.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 se(e,t){let r=N(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return M(e,r)}function ce(e,t){let r=N(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...M(e,r),delegatorAddress:r.delegatorAddress}}function M(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function N(e,t){let n=s.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}const le=e=>new Promise(t=>setTimeout(t,e));var ue=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=(0,u.getAddress)(t);return this.#o(e,{requesterAddress:n,aclActorAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...se(e,t),signerAddress:n}),errorMessage:`Failed to decrypt encrypted values`})}async delegatedUserDecrypt(e,t,n,r,i){let a=(0,u.getAddress)(t),o=(0,u.getAddress)(n);return this.#a(i?.waitForPropagation??!0,()=>this.#o(e,{requesterAddress:(0,u.getAddress)(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#d(e,{delegatorAddress:a,delegateAddress:o}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...ce(e,t),delegateAddress:o}),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 T))throw t;await le(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,u.getAddress)(e.contractAddress)}));if(s.length===0)return{items:s};let c=(0,u.getAddress)(i);try{let e=await this.delegatedUserDecrypt(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:o});for(let t of s)this.#c(t,e);return{items:s}}catch(e){if(r.m(e))throw e;if(s.length===1){let[n=this.#u()]=s;return n.error=this.#l(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,u.getAddress)(t)}),{items:s}}}let l=!1;return await r.a(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1});this.#c(e,r)}catch(n){if(r.m(n))throw l=!0,n;e.error=this.#l(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,u.getAddress)(t)})}}),a),{items:s}}async#o(t,n){if(t.length===0)return{};let i=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},s=[];for(let e of i)r.i(e.encryptedValue)?a[e.encryptedValue]=0n:s.push(e);if(s.length===0)return a;let c=Array.from(new Set(i.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw o.p(e)?this.#s(e,`the delegation pre-check`):e}let d=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?d.push(e):a[e.encryptedValue]=t}if(d.length===0)return a;let f=await n.resolveCredentials(c),p=new Map;for(let e of d){let t=p.get(e.contractAddress);t?t.push(e.encryptedValue):p.set(e.contractAddress,[e.encryptedValue])}let m=Date.now(),h=d.map(e=>e.encryptedValue);try{this.#i({type:r.o.DecryptStart,encryptedValues:h}),await r.a([...p.entries()].map(([e,t])=>async()=>{let r;try{r=await n.decryptContract({credentials:f,contractAddress:e,encryptedValues:t})}catch(t){throw E(t,n.errorMessage,{isDelegated:n.delegated,contractAddress:e,account:n.aclActorAddress})}for(let[t,i]of Object.entries(r))a[t]=i,await this.#e.set(n.requesterAddress,e,t,i)}),5);let e={};for(let t of h){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.o.DecryptEnd,durationMs:Date.now()-m,encryptedValues:h,result:e}),a}catch(t){let i=t instanceof e.r&&t.cause instanceof Error?t.cause:t;throw this.#i({type:r.o.DecryptError,error:o.h(i),durationMs:Date.now()-m,encryptedValues:h}),E(t,n.errorMessage,{isDelegated:n.delegated})}}#s(e,t){return new r.b(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:o.c(e)})}#c(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#l(t,n,r){return t instanceof e.r?t:E(t,n,r)}#u(){throw new n.t(`Batch delegated decryption invariant failed: missing item`)}async#d(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 de(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 P={AlreadyDelegatedOrRevokedInSameBlock:e=>new _(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new S(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new C(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new g(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new w(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new b(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new v(`Cannot revoke: no active delegation exists.`,{cause:e})};function fe(e){return e in P}function pe(e,t){let n=de(e);if(n&&fe(n))return P[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(P))if(r.includes(e))return n(t);return null}var me=class{#e;#t;#n;#r;constructor({provider:e,relayer:t,emitEvent:n=()=>{},logger:r}){this.#e=e,this.#t=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new w(`Expiration date must be at least 1 hour in the future`);let o=(0,u.getAddress)(t),s=(0,u.getAddress)(n),c=(0,u.getAddress)(i);if(s===c)throw new g(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new x(`Delegate address cannot be the same as the contract address (${o}).`);let l=await this.#t.getAclAddress(),d=a?BigInt(Math.floor(a.getTime()/1e3)):r.l,f;try{f=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===d)throw new b(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:t,config:r.u(l,s,o,d)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=(0,u.getAddress)(t),o=(0,u.getAddress)(n),s=(0,u.getAddress)(i),c=await this.#t.getAclAddress(),l;try{l=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new v(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:r.p(c,o,a)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===r.l?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=await this.#t.getAclAddress();return this.#e.readContract(r.d(i,(0,u.getAddress)(t),(0,u.getAddress)(n),(0,u.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:n,config:i}){try{return await r.n({operation:e,signer:t,provider:this.#e,config:i,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof r.x))return;let t=pe(e.cause??e,e);if(t)throw t}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 v||t instanceof y){let n=(0,u.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let i=(0,u.getAddress)(e),a=(0,u.getAddress)(t),o=(0,u.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new v(`No active delegation from ${a} to ${o} for ${i}`);if(s!==r.l&&s<=await this.#e.getBlockTimestamp())throw new y(`Delegation from ${a} to ${o} for ${i} has expired`)}},he=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(e){let t=Date.now();try{this.#t({type:r.o.EncryptStart},e.contractAddress);let n=await this.#e.encrypt(e);return this.#t({type:r.o.EncryptEnd,durationMs:Date.now()-t},e.contractAddress),n}catch(n){throw this.#t({type:r.o.EncryptError,error:o.h(n),durationMs:Date.now()-t},e.contractAddress),ee(n,`Encryption failed`)}}},ge=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.relayer,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.L(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.L(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.L(`wallet account listener`,()=>n(e),this.#i)))}};function F(e){return(0,u.keccak256)((0,u.toBytes)(e))}const I={ConfidentialTransfer:F(`ConfidentialTransfer(address,address,bytes32)`),Wrap:F(`Wrap(address,uint256,bytes32)`),UnwrapRequested:F(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:F(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function L(e){return(0,u.getAddress)(D(e.slice(-40)))}function R(e){return e}function z(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function B(e,t){return(0,u.getAddress)(D(z(e,t).slice(-40)))}function V(e,t){return BigInt(`0x`+z(e,t))}function H(e,t){return D(z(e,t))}function U(e){return e.topics[0]!==I.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:L(e.topics[1]),to:L(e.topics[2]),encryptedAmount:R(e.topics[3])}}function W(e){return e.topics[0]!==I.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:L(e.topics[1]),roundedAmount:V(e.data,0),encryptedWrappedAmount:H(e.data,1)}}function G(e){return e.topics[0]!==I.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:L(e.topics[1]),unwrapRequestId:R(e.topics[2]),encryptedAmount:H(e.data,0)}}function K(e){return e.topics[0]!==I.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:L(e.topics[1]),unwrapRequestId:R(e.topics[2]),encryptedAmount:H(e.data,0),cleartextAmount:V(e.data,1)}}function q(e){return U(e)??W(e)??G(e)??K(e)}function _e(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=G(t);if(e)return e}return null}function ve(e){for(let t of e){let e=W(t);if(e)return e}return null}const ye=[I.ConfidentialTransfer,I.Wrap,I.UnwrapRequested,I.UnwrapFinalized],Y={DelegatedForUserDecryption:F(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:F(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:L(e.topics[1]),delegate:L(e.topics[2]),contractAddress:B(e.data,0),delegationCounter:V(e.data,1),oldExpirationDate:V(e.data,2),newExpirationDate:V(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:L(e.topics[1]),delegate:L(e.topics[2]),contractAddress:B(e.data,0),delegationCounter:V(e.data,1),oldExpirationDate:V(e.data,2)}}function Q(e){return X(e)??Z(e)}function be(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function xe(e){for(let t of e){let e=X(t);if(e)return e}return null}function Se(e){for(let t of e){let e=Z(t);if(e)return e}return null}const Ce=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${s.f(e)}`}const we=d.z.union([d.z.pipe(s.m,d.z.transform(e=>({unwrapTxHash:e}))),d.z.pipe(d.z.object({version:d.z.literal(1),unwrapTxHash:s.m,unwrapRequestId:d.z.optional(s.m)}),d.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Te(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ee(e,t){return(await De(e,t))?.unwrapTxHash??null}async function De(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=we.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Oe(e,t){await e.delete($(t))}var ke=class extends r.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.R(e,{cause:n})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(t.p(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#o();return this.sdk.provider.readContract(t.h(n,(0,u.getAddress)(e),this.address))}async shield(n,i){let a=await r.s(`shield`,this.sdk.signer,this.sdk.provider),s=await this.isPayable(),c=await this.#o(),l=(0,u.getAddress)(a.address),d;try{d=await this.sdk.provider.readContract(t._(c,l))}catch(t){throw t instanceof e.r?t:new r.g(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:o.h(t)})}if(d<n)throw new r.v(`Insufficient ERC-20 balance: requested ${n}, available ${d} (token: ${c})`,{requested:n,available:d,token:c});return s?this.#i(n,c,l,i):this.#a(n,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,u.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:O(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#c(e,i===`max`,r);let a=r?.to?(0,u.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.I(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let n=await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#o(),a=(0,u.getAddress)(n.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t.h(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.g(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.L(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#s(l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.L(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#s(r.txHash,n,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async getPendingUnshield(){return Ee(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let i=(0,u.getAddress)((await r.s(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i}),[s]=a;if(!s)throw new n.n(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`unwrap`,config:t.P(this.address,i,i,s,o)})}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,u.getAddress)((await r.s(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),i=await this.readConfidentialBalanceOf(e);if(r.i(i))throw new n.t(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:t.F(this.address,e,e,i)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await r.c(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e]),i=n.clearValues[e];return o.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.O(this.address,e,i,n.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.N(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(n,i,a){this.emit({type:r.o.UnshieldPhase1Submitted,txHash:n,operationId:i}),await t.L(`unshield: savePendingUnshield`,()=>Te(this.sdk.storage,this.address,n),this.sdk.logger);let o;try{o=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new r.x(`Failed to get unshield receipt`,{cause:t})}let s=J(o.logs);if(!s)throw new r.x(`No UnwrapRequested event found in unshield receipt`);this.emit({type:r.o.UnshieldPhase2Started,operationId:i}),t.L(`unshield: onFinalizing`,()=>a?.onFinalizing?.(),this.sdk.logger);let c=await this.finalizeUnwrap(s.unwrapRequestId??s.encryptedAmount);return this.emit({type:r.o.UnshieldPhase2Submitted,txHash:c.txHash,operationId:i}),t.L(`unshield: onFinalizeSubmitted`,()=>a?.onFinalizeSubmitted?.(c.txHash),this.sdk.logger),await t.L(`unshield: clearPendingUnshield`,()=>Oe(this.sdk.storage,this.address),this.sdk.logger),c}async#c(e,n,i){this.#r(`approveUnderlying`);let a=await this.#o(),o=(0,u.getAddress)((await r.s(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),s=await this.sdk.provider.readContract(t.h(a,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(a,this.address,0n)});let c=n?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.g(a,this.address,c),onSubmitted:i?.onApprovalSubmitted})}},Ae=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#n=e.onEvent??function(){},this.#r=e.logger,this.#i=new oe(e.storage,this.#r),this.#l=new me({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this),logger:this.#r});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new s.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#t=t,this.#e=e.registryTTL,e.signer&&(this.#c=new s.d({relayer:this.relayer,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage,logger:this.#r}),this.#s=new ue({cache:this.#i,credentialService:this.#c,delegationService:this.#l,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#o=new he({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#a=new ge({signer:e.signer,relayer:this.relayer,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.permits=new j({signer:this.signer,provider:this.provider,cachingService:this.#i,credentialService:this.#c,logger:this.#r}),this.delegations=new A({signer:this.signer,provider:this.provider,delegationService:this.#l}),this.decryption=new k({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#s})}onWalletAccountChange(e){return this.#a.onWalletAccountChange(e)}get logger(){return this.#r}emitEvent(e,t){try{this.#n({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#r.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new s.o({provider:this.provider,registryAddresses:{...this.#t,...e},registryTTL:this.#e})}async encrypt(e){return this.#o.encrypt(e)}createToken(e){return new r.t(this,e)}createWrappedToken(e){return new ke(this,e)}dispose(){this.#a.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}},je=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 je;exports.ACL_TOPICS=Ce,exports.AclPausedError=C,exports.AclTopics=Y,exports.BalanceCheckUnavailableError=r.h,exports.BaseSigner=s.t,exports.ChainMismatchError=r.y,exports.ChromeSessionStorage=je,exports.ConfigurationError=e.t,exports.Decryption=k,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=s.a,exports.DelegationContractIsSelfError=S,exports.DelegationCooldownError=_,exports.DelegationDelegateEqualsContractError=x,exports.DelegationExpirationTooSoonError=w,exports.DelegationExpiredError=y,exports.DelegationExpiryUnchangedError=b,exports.DelegationNotFoundError=v,exports.DelegationNotPropagatedError=T,exports.DelegationSelfNotAllowedError=g,exports.Delegations=A,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=r.g,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=c.n,exports.InsufficientConfidentialBalanceError=r._,exports.InsufficientERC20BalanceError=r.v,exports.InvalidTransportKeyPairError=m,exports.MemoryStorage=s.l,exports.MutableWalletAccountStore=s.n,exports.NoCiphertextError=h,exports.NotEntitledError=i.n,exports.Permits=j,exports.RelayerRequestFailedError=e.n,exports.RpcRateLimitError=r.b,exports.SignerNotConfiguredError=t.R,exports.SignerRequiredError=t.z,exports.SigningFailedError=t.U,exports.SigningRejectedError=t.W,exports.TOKEN_TOPICS=ye,exports.Token=r.t,exports.Topics=I,exports.TransactionRevertedError=r.x,exports.TransportKeyPairExpiredError=p,exports.WalletAccountNotReadyError=t.B,exports.WalletNotConnectedError=t.V,exports.WorkerRecycledError=a.t,exports.WorkerTimeoutError=a.n,exports.WrappedToken=ke,exports.WrappersRegistry=s.o,exports.ZERO_ENCRYPTED_VALUE=r.r,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=Ae,exports.ZamaSDKEvents=r.o,exports.allowanceContract=t.h,exports.anvil=l.t,exports.approveContract=t.g,exports.balanceOfContract=t._,exports.bscTestnet=l.n,exports.chains=l.r,exports.chromeSessionStorage=Me,exports.cleartext=te,exports.confidentialBalanceOfContract=t.S,exports.confidentialTotalSupplyContract=t.C,exports.confidentialTransferContract=t.T,exports.confidentialTransferFromContract=t.D,exports.createConfig=re,exports.createWalletAccountStore=s.r,exports.decimalsContract=t.v,exports.decodeAclEvent=Q,exports.decodeAclEvents=be,exports.decodeConfidentialTransfer=U,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=_e,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=K,exports.decodeUnwrapRequested=G,exports.decodeWrap=W,exports.delegateForUserDecryptionContract=r.u,exports.finalizeUnwrapContract=t.O,exports.findDelegatedForUserDecryption=xe,exports.findRevokedDelegationForUserDecryption=Se,exports.findUnwrapRequested=J,exports.findWrap=ve,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=r.d,exports.getTokenAddressContract=t.n,exports.getTokenPairContract=t.r,exports.getTokenPairsContract=t.i,exports.getTokenPairsLengthContract=t.a,exports.getTokenPairsSliceContract=t.o,exports.hardhat=l.i,exports.hoodi=l.a,exports.indexedDBStorage=c.r,exports.inferredTotalSupplyContract=t.k,exports.ingenTestnet=l.o,exports.isConfidentialTokenContract=t.d,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.f,exports.isEncryptedValueZero=r.i,exports.isHandleDelegatedContract=r.f,exports.isOperatorContract=t.A,exports.mainnet=l.s,exports.matchZamaError=f,exports.memoryStorage=s.u,exports.nameContract=t.b,exports.rateContract=t.j,exports.resolveChainRelayers=s.s,exports.resolveStorage=s.c,exports.revokeDelegationContract=r.p,exports.sepolia=l.c,exports.setOperatorContract=t.M,exports.supportsInterfaceContract=t.m,exports.symbolContract=t.x,exports.transferAndCallContract=O,exports.underlyingContract=t.N,exports.unwrapContract=t.P,exports.unwrapFromBalanceContract=t.F,exports.wrapContract=t.I;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|