@cowprotocol/permit-utils 3.8.0 → 3.10.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/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("viem"),B=require("viem/accounts"),b=require("wagmi/actions"),V=require("@cowprotocol/hook-dapp-lib"),K=require("@cowprotocol/cow-sdk"),z="0xa50dc0f7fc051309434deb3b1c71e927dbb711759231d8ecbf630c85d94a42fe",v=B.privateKeyToAccount(z),$=55000n,k=80000n,x=f.maxUint256,W=157788e6;async function J(e,n,t,r,a,o,{version:s,type:i,name:u}){const c=u||a;if(i==="unsupported")return!1;if(!c)throw new Error(`No token name for ${r}`);const l={chainId:n,tokenName:c,tokenAddress:r,callData:o,version:s};let m;if(o.startsWith(I)?m=t.recoverPermitOwnerFromCallData({...l,callData:o.replace(I,"0x")}):o.startsWith(w)&&(m=t.recoverDaiLikePermitOwnerFromCallData({...l,callData:o.replace(w,"0x")})),!!m)try{return(await m).toLowerCase()===e.toLowerCase()}catch(y){console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${e} with callData ${o}`,y);return}}async function O({eip2612Utils:e,callDataParams:n}){return(await e.buildDaiLikePermitCallData(...n)).replace("0x",w)}async function H({eip2612Utils:e,callDataParams:n}){const[t,r,a,...o]=n;return(await e.buildPermitCallData(t,r,a,...o)).replace("0x",I)}function _(){return Math.ceil((Date.now()+W)/1e3)}function F(e){return!!e&&e.type!=="unsupported"}const C={},Q=[4001,-32e3],Y=["user denied","user rejected","rejected transaction","transaction was rejected"];async function X(e){const n=te(e),t=C[n];if(t)return await t;const r=ee(e).catch(a=>{const o=G(a);if(ae(o)||o instanceof f.ExecutionRevertedError)throw o;console.debug("[generatePermitHook] cached request failed",o)}).finally(()=>{delete C[n]});return C[n]=r,r}async function Z({data:e,from:n,to:t,config:r,isUserAccount:a}){try{const o=await b.estimateGas(r,{account:n,to:t,data:e}),s=a?o:o+o/10n;return s>k?s:k}catch(o){const s=G(o),i=a?ne(s):void 0;if(i)throw i;return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default",s),k}}async function ee(e){const{inputToken:n,spender:t,chainId:r,permitInfo:a,config:o,account:s,eip2612Utils:i,nonce:u}=e,c=n.address,l=a.name||n.name;if(!F(a))throw new Error(`Trying to generate permit hook for unsupported token: ${c}`);if(!l)throw new Error(`No token name for token: ${c}`);const m=s||v.address,y=u===void 0?await i.getTokenNonce(c,m):u,g=_(),P=e.amount||x,h=a.type==="eip-2612"?await H({eip2612Utils:i,callDataParams:[{owner:m,spender:t,value:P.toString(),nonce:y,deadline:g},r,l,c,a.version]}):await O({eip2612Utils:i,callDataParams:[{holder:m,spender:t,allowed:!0,value:P.toString(),nonce:y,expiry:g},r,l,c,a.version]}),p=await Z({data:h,from:m,to:c,config:o,isUserAccount:!!s});return{target:c,callData:h,gasLimit:p.toString(),dappId:V.PERMIT_HOOK_DAPP_ID}}function te(e){const{inputToken:n,chainId:t,account:r,amount:a}=e;return`${n.address.toLowerCase()}-${t}${r?`-${r.toLowerCase()}`:""}${a?`-${a.toString()}`:""}`}function ne(e){if(!(e instanceof f.BaseError))return;const n=e.walk(t=>t instanceof f.ExecutionRevertedError);return n instanceof f.ExecutionRevertedError?n:void 0}function ae(e){if(e.code!==void 0&&Q.includes(e.code))return!0;const n=e.message.toLowerCase();return Y.some(t=>n.includes(t))}function G(e){if(e instanceof Error)return e;const n=typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:String(e),t=new Error(n);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"&&(t.code=e.code),t}class re{constructor(n,t){this.publicClient=n,this.walletClient=t}contractEncodeABI(n,t,r,a){const o=a.map(s=>s instanceof Uint8Array?f.bytesToHex(s):s);return f.encodeFunctionData({abi:n,functionName:r,args:o})}signTypedData(n,t,r){const a=Object.fromEntries(Object.entries(t.types).filter(([s])=>s!=="EIP712Domain")),o=this.walletClient.account??n;return this.walletClient.signTypedData({account:o,domain:t.domain,types:a,primaryType:t.primaryType,message:t.message})}ethCall(n,t){return this.publicClient.call({to:n,data:t}).then(({data:r})=>r||"0x")}decodeABIParameter(n,t){const[r]=f.decodeAbiParameters([{type:n}],t);return r}decodeABIParameters(n,t){const r=f.decodeAbiParameters(n,t),a={};return n.forEach((o,s)=>{const i=r[s],u=typeof i=="bigint"?f.toHex(i):i;a[s]=u,o.name&&(a[o.name]=u)}),a}}const L=new Map,N=new Map;async function j({chainId:e,publicClient:n,account:t,walletClient:r}){const a=L.get(e);if(!t&&a)return a;const o=`${e}-${t}`,s=N.get(o);if(s)return s;let i;if(!t)i=f.createWalletClient({account:v,chain:n.chain,transport:f.http()});else if(r)i=r;else throw new Error("Permit signing needs an active wallet client. Reconnect your wallet or use an injected extension.");const u=new re(n,i),c=await Promise.resolve().then(()=>require("./1inchPermitUtils-BDO_CqjL.cjs")).then(m=>m.Eip2612PermitUtils),l=new c(u,{enabledCheckSalt:!0});return t?N.set(o,l):L.set(e,l),l}const oe=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];async function ie(e,n,t){const[r,a,o,s,i,u,c]=await b.readContract(t,{abi:oe,address:e,functionName:"eip712Domain"}),l={fields:r,name:a,version:o,chainId:s.toString(),verifyingContract:i,salt:u,extensions:c.map(m=>String(m))};return se(l,n,e)}async function se(e,n,t){const{extensions:r,...a}=e;if(r.length>0)throw Error("Extensions not implemented");if(a.chainId&&n!==parseInt(a.chainId,16))throw Error(`ChainId mismatch. Received: '${a.chainId}', expected: '${n}'`);if(a.verifyingContract&&t.toLowerCase()!==a.verifyingContract.toLowerCase())throw Error(`Address mismatch. Received: '${a.verifyingContract}', expected: '${t}'`);return le(a)}const ce=["name","version","chainId","verifyingContract","salt"];function le(e){const n=parseInt(e.fields,16);return ce.reduce((t,r,a)=>(n&1<<a&&(t[r]=e[r]),t),{})}async function ue(e,n,t){return b.readContract(t,{abi:f.erc20Abi,address:e,functionName:"name"})}const de=[[{constant:!0,inputs:[],name:"version",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"}],[{constant:!0,inputs:[],name:"ERC712_VERSION",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"}]];async function q(e,n,t=0){const r=de[t];if(!r)return"1";try{const a=await b.readContract(n,{abi:r,address:e,functionName:r[0].name});if(a==="0x"||Number.isNaN(Number(a)))return"1";if(!a.startsWith("0x"))return a;const[o]=f.decodeAbiParameters([{type:"string"}],a);return o}catch{return q(e,n,t+1)}}const me={nonce:0,deadline:_()},pe={allowed:!0,nonce:0,expiry:_()},M={},T={type:"unsupported"};async function fe(e){const{tokenAddress:n,chainId:t}=e,r=K.getTokenId({address:n,chainId:t}),a=M[r];if(a)return a;const o=ye(e);return M[r]=o,o}async function ye(e){const{amount:n,chainId:t,config:r,minGasLimit:a,publicClient:o,spender:s,tokenAddress:i}=e,u=await j({chainId:t,publicClient:o}),c=v.address;let l;try{l=await ie(i,t,r)}catch{console.debug(`[checkTokenIsPermittable] Couldn't fetch eip712domain for token ${i}`)}const m=!l?.name,y=l?.version===void 0,[g,P,h]=await Promise.allSettled([m?ue(i,t,r):Promise.resolve(l?.name),u.getTokenNonce(i,c),y?q(i,r):Promise.resolve(l?.version)]);let p=l?.name;if(g.status==="fulfilled")p=g.value;else if(m){const d=g.reason;if(/ETIMEDOUT/.test(d)&&!p)return{error:"Failed to fetch token name from contract. RPC connection error"};console.debug(`[checkTokenIsPermittable] Couldn't fetch token name from the contract for token ${i}, using provided '${p}'`,d)}if(!p)return{error:`Token name could not be determined for ${i}`};let A;if(P.status==="fulfilled")A=P.value;else{const d=P.reason;return d==="nonce not supported"||d.message==="nonce is NaN"?(console.debug(`[checkTokenIsPermittable] Not a permittable token ${i} - ${p}`,d?.message||d),{...T,name:p}):(console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${i} - ${p}`,d),{error:d.message||d.toString()})}let R=l?.version;h.status==="fulfilled"?R=h.value:y&&console.debug(`[checkTokenIsPermittable] Failed to get version for ${i} - ${p}`,h.reason);const S={chainId:t,eip2612PermitUtils:u,nonce:A,spender:s,tokenAddress:i,tokenName:p,walletAddress:c,version:R,minGasLimit:a,amount:n};try{return await U({...S,type:"eip-2612",config:r})}catch(d){try{return await he(i,u)?await U({...S,type:"dai-like",config:r}):/invalid signature/.test(d)||d?.code==="UNPREDICTABLE_GAS_LIMIT"?(console.debug(`[checkTokenIsPermittable] Token ${i} - ${p} might be permittable, but it's not supported for now. Reason:`,d?.reason),{...T,name:p}):(console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${i} - ${p}`,d),{error:d.message||d.toString()})}catch(E){return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${i} - ${p}`,E),{error:E.message||E.toString()}}}}async function U(e){const{config:n,walletAddress:t,tokenAddress:r,tokenName:a,type:o,version:s,minGasLimit:i=$}=e,c=await(o==="eip-2612"?Pe:ge)(e);return c?await b.estimateGas(n,{to:r,account:t,data:c})>i?{type:o,version:s,name:a}:{...T,name:a}:{...T,name:a}}async function ge(e){const{eip2612PermitUtils:n,tokenAddress:t,walletAddress:r,spender:a,nonce:o,chainId:s,tokenName:i,version:u}=e;return await n.getPermitTypeHash(t)===D?O({eip2612Utils:n,callDataParams:[{...pe,holder:r,spender:a,nonce:o},s,i,t,u]}):!1}async function Pe(e){const{eip2612PermitUtils:n,walletAddress:t,spender:r,nonce:a,chainId:o,tokenName:s,tokenAddress:i,version:u,amount:c}=e;return H({eip2612Utils:n,callDataParams:[{...me,owner:t,spender:r,nonce:a,value:c?c.toString():x.toString()},+o,s,i,u]})}async function he(e,n){return await n.getPermitTypeHash(e)===D}const be=[{constant:!1,inputs:[{internalType:"address",name:"holder",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"nonce",type:"uint256"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"bool",name:"allowed",type:"bool"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"}],Ee=[{type:"function",name:"permit",stateMutability:"nonpayable",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"deadline",type:"uint256"},{name:"v",type:"uint8"},{name:"r",type:"bytes32"},{name:"s",type:"bytes32"}],outputs:[]}],I="0xd505accf",w="0x8fcbaf0c",D="0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb",Te=Object.freeze(Object.defineProperty({__proto__:null,DAI_EIP_2612_PERMIT_ABI:be,DAI_LIKE_PERMIT_TYPEHASH:D,DAI_PERMIT_SELECTOR:w,EIP_2612_PERMIT_ABI:Ee,EIP_2612_PERMIT_SELECTOR:I},Symbol.toStringTag,{value:"Module"}));exports.DEFAULT_MIN_GAS_LIMIT=$;exports.PERMIT_ACCOUNT=v;exports.checkIsCallDataAValidPermit=J;exports.generatePermitHook=X;exports.getPermitUtilsInstance=j;exports.getTokenPermitInfo=fe;exports.isSupportedPermitInfo=F;exports.oneInchPermitUtilsConsts=Te;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("viem"),V=require("viem/accounts"),T=require("wagmi/actions"),E=require("@cowprotocol/cow-sdk"),B=require("@cowprotocol/hook-dapp-lib"),W="0xa50dc0f7fc051309434deb3b1c71e927dbb711759231d8ecbf630c85d94a42fe",b=V.privateKeyToAccount(W),O=55000n,A=80000n,_=f.maxUint256,z=157788e6;async function J(e,n,t,a,r,i,{version:s,type:o,name:l}){const c=l||r;if(o==="unsupported")return!1;if(!c)throw new Error(`No token name for ${a}`);const d={chainId:n,tokenName:c,tokenAddress:a,callData:i,version:s};let m;if(i.startsWith(v)?m=t.recoverPermitOwnerFromCallData({...d,callData:i.replace(v,"0x")}):i.startsWith(C)&&(m=t.recoverDaiLikePermitOwnerFromCallData({...d,callData:i.replace(C,"0x")})),!!m)try{return(await m).toLowerCase()===e.toLowerCase()}catch(y){console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${e} with callData ${i}`,y);return}}async function H({eip2612Utils:e,callDataParams:n}){return(await e.buildDaiLikePermitCallData(...n)).replace("0x",C)}async function F({eip2612Utils:e,callDataParams:n}){const[t,a,r,...i]=n;return(await e.buildPermitCallData(t,a,r,...i)).replace("0x",v)}function D(){return Math.ceil((Date.now()+z)/1e3)}function G(e){return!!e&&e.type!=="unsupported"}const M=new WeakMap,Q=[4001,-32e3],Y=["user denied","user rejected","rejected transaction","transaction was rejected"];async function X(e){const n=te(e),t=M.get(e.config)??new Map,a=t.get(n);if(a)return await a;const r=ee(e).catch(i=>{const s=j(i);if(re(s)||s instanceof f.ExecutionRevertedError)throw s;console.debug("[generatePermitHook] cached request failed",s)}).finally(()=>{t.delete(n)});return t.set(n,r),M.set(e.config,t),r}async function Z({data:e,from:n,to:t,config:a,isUserAccount:r}){try{const i=await T.estimateGas(a,{account:n,to:t,data:e}),s=r?i:i+i/10n;return s>A?s:A}catch(i){const s=j(i),o=r?ne(s):void 0;if(o)throw o;return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default",s),A}}async function ee(e){const{inputToken:n,spender:t,chainId:a,permitInfo:r,config:i,account:s,eip2612Utils:o,nonce:l}=e,c=n.address,d=r.name||n.name;if(!G(r))throw new Error(`Trying to generate permit hook for unsupported token: ${c}`);if(!d)throw new Error(`No token name for token: ${c}`);const m=s||b.address,y=l===void 0?await o.getTokenNonce(c,m):l,g=D(),P=e.amount??_,h=r.type==="eip-2612"?await F({eip2612Utils:o,callDataParams:[{owner:m,spender:t,value:P.toString(),nonce:y,deadline:g},a,d,c,r.version]}):await H({eip2612Utils:o,callDataParams:[{holder:m,spender:t,allowed:!0,value:P.toString(),nonce:y,expiry:g},a,d,c,r.version]}),p=await Z({data:h,from:m,to:c,config:i,isUserAccount:!!s});return{target:c,callData:h,gasLimit:p.toString(),dappId:B.PERMIT_HOOK_DAPP_ID}}function te(e){const{inputToken:n,chainId:t,account:a,amount:r,nonce:i,permitInfo:s,spender:o}=e,l=a??b.address,c=s.name||n.name;return JSON.stringify({tokenAddress:E.getAddressKey(n.address),chainId:t,owner:E.getAddressKey(l),spender:E.getAddressKey(o),amount:(r??_).toString(),nonce:i??null,permitType:s.type,tokenName:c??null,permitVersion:s.version??null})}function ne(e){if(!(e instanceof f.BaseError))return;const n=e.walk(t=>t instanceof f.ExecutionRevertedError);return n instanceof f.ExecutionRevertedError?n:void 0}function re(e){if(e.code!==void 0&&Q.includes(e.code))return!0;const n=e.message.toLowerCase();return Y.some(t=>n.includes(t))}function j(e){if(e instanceof Error)return e;const n=typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:String(e),t=new Error(n);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"&&(t.code=e.code),t}class ae{constructor(n,t){this.publicClient=n,this.walletClient=t}contractEncodeABI(n,t,a,r){const i=r.map(s=>s instanceof Uint8Array?f.bytesToHex(s):s);return f.encodeFunctionData({abi:n,functionName:a,args:i})}signTypedData(n,t,a){const r=Object.fromEntries(Object.entries(t.types).filter(([s])=>s!=="EIP712Domain")),i=this.walletClient.account??n;return this.walletClient.signTypedData({account:i,domain:t.domain,types:r,primaryType:t.primaryType,message:t.message})}ethCall(n,t){return this.publicClient.call({to:n,data:t}).then(({data:a})=>a||"0x")}decodeABIParameter(n,t){const[a]=f.decodeAbiParameters([{type:n}],t);return a}decodeABIParameters(n,t){const a=f.decodeAbiParameters(n,t),r={};return n.forEach((i,s)=>{const o=a[s],l=typeof o=="bigint"?f.toHex(o):o;r[s]=l,i.name&&(r[i.name]=l)}),r}}const U=new Map,$=new Map;async function K({chainId:e,publicClient:n,account:t,walletClient:a}){const r=U.get(e);if(!t&&r)return r;const i=`${e}-${t}`,s=$.get(i);if(s)return s;let o;if(!t)o=f.createWalletClient({account:b,chain:n.chain,transport:f.http()});else if(a)o=a;else throw new Error("Permit signing needs an active wallet client. Reconnect your wallet or use an injected extension.");const l=new ae(n,o),c=await Promise.resolve().then(()=>require("./1inchPermitUtils-BDO_CqjL.cjs")).then(m=>m.Eip2612PermitUtils),d=new c(l,{enabledCheckSalt:!0});return t?$.set(i,d):U.set(e,d),d}const oe=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];async function ie(e,n,t){const[a,r,i,s,o,l,c]=await T.readContract(t,{abi:oe,address:e,functionName:"eip712Domain"}),d={fields:a,name:r,version:i,chainId:s.toString(),verifyingContract:o,salt:l,extensions:c.map(m=>String(m))};return se(d,n,e)}async function se(e,n,t){const{extensions:a,...r}=e;if(a.length>0)throw Error("Extensions not implemented");if(r.chainId&&n!==parseInt(r.chainId,16))throw Error(`ChainId mismatch. Received: '${r.chainId}', expected: '${n}'`);if(r.verifyingContract&&t.toLowerCase()!==r.verifyingContract.toLowerCase())throw Error(`Address mismatch. Received: '${r.verifyingContract}', expected: '${t}'`);return le(r)}const ce=["name","version","chainId","verifyingContract","salt"];function le(e){const n=parseInt(e.fields,16);return ce.reduce((t,a,r)=>(n&1<<r&&(t[a]=e[a]),t),{})}async function de(e,n,t){return T.readContract(t,{abi:f.erc20Abi,address:e,functionName:"name"})}const ue=[[{constant:!0,inputs:[],name:"version",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"}],[{constant:!0,inputs:[],name:"ERC712_VERSION",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"}]];async function q(e,n,t=0){const a=ue[t];if(!a)return"1";try{const r=await T.readContract(n,{abi:a,address:e,functionName:a[0].name});if(r==="0x"||Number.isNaN(Number(r)))return"1";if(!r.startsWith("0x"))return r;const[i]=f.decodeAbiParameters([{type:"string"}],r);return i}catch{return q(e,n,t+1)}}const me={nonce:0,deadline:D()},pe={allowed:!0,nonce:0,expiry:D()},w={},k={type:"unsupported"};async function fe(e){const{tokenAddress:n,chainId:t,spender:a}=e,r=`${E.getTokenId({address:n,chainId:t})}-${E.getAddressKey(a)}`,i=w[r];if(i)return i;const s=ye(e).then(o=>("error"in o&&delete w[r],o)).catch(o=>{throw delete w[r],o});return w[r]=s,s}async function ye(e){const{amount:n,chainId:t,config:a,minGasLimit:r,publicClient:i,spender:s,tokenAddress:o}=e,l=await K({chainId:t,publicClient:i}),c=b.address;let d;try{d=await ie(o,t,a)}catch{console.debug(`[checkTokenIsPermittable] Couldn't fetch eip712domain for token ${o}`)}const m=!d?.name,y=d?.version===void 0,[g,P,h]=await Promise.allSettled([m?de(o,t,a):Promise.resolve(d?.name),l.getTokenNonce(o,c),y?q(o,a):Promise.resolve(d?.version)]);let p=d?.name;if(g.status==="fulfilled")p=g.value;else if(m){const u=g.reason;if(/ETIMEDOUT/.test(u)&&!p)return{error:"Failed to fetch token name from contract. RPC connection error"};console.debug(`[checkTokenIsPermittable] Couldn't fetch token name from the contract for token ${o}, using provided '${p}'`,u)}if(!p)return{error:`Token name could not be determined for ${o}`};let S;if(P.status==="fulfilled")S=P.value;else{const u=P.reason;return u==="nonce not supported"||u.message==="nonce is NaN"?(console.debug(`[checkTokenIsPermittable] Not a permittable token ${o} - ${p}`,u?.message||u),{...k,name:p}):(console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${o} - ${p}`,u),{error:u.message||u.toString()})}let N=d?.version;h.status==="fulfilled"?N=h.value:y&&console.debug(`[checkTokenIsPermittable] Failed to get version for ${o} - ${p}`,h.reason);const L={chainId:t,eip2612PermitUtils:l,nonce:S,spender:s,tokenAddress:o,tokenName:p,walletAddress:c,version:N,minGasLimit:r,amount:n};try{return await x({...L,type:"eip-2612",config:a})}catch(u){try{return await he(o,l)?await x({...L,type:"dai-like",config:a}):/invalid signature/.test(u)||u?.code==="UNPREDICTABLE_GAS_LIMIT"?(console.debug(`[checkTokenIsPermittable] Token ${o} - ${p} might be permittable, but it's not supported for now. Reason:`,u?.reason),{...k,name:p}):(console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${o} - ${p}`,u),{error:u.message||u.toString()})}catch(I){return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${o} - ${p}`,I),{error:I.message||I.toString()}}}}async function x(e){const{config:n,walletAddress:t,tokenAddress:a,tokenName:r,type:i,version:s,minGasLimit:o=O}=e,c=await(i==="eip-2612"?Pe:ge)(e);return c?await T.estimateGas(n,{to:a,account:t,data:c})>o?{type:i,version:s,name:r}:{...k,name:r}:{...k,name:r}}async function ge(e){const{eip2612PermitUtils:n,tokenAddress:t,walletAddress:a,spender:r,nonce:i,chainId:s,tokenName:o,version:l}=e;return await n.getPermitTypeHash(t)===R?H({eip2612Utils:n,callDataParams:[{...pe,holder:a,spender:r,nonce:i},s,o,t,l]}):!1}async function Pe(e){const{eip2612PermitUtils:n,walletAddress:t,spender:a,nonce:r,chainId:i,tokenName:s,tokenAddress:o,version:l,amount:c}=e;return F({eip2612Utils:n,callDataParams:[{...me,owner:t,spender:a,nonce:r,value:c?c.toString():_.toString()},+i,s,o,l]})}async function he(e,n){return await n.getPermitTypeHash(e)===R}const Ee=[{constant:!1,inputs:[{internalType:"address",name:"holder",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"nonce",type:"uint256"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"bool",name:"allowed",type:"bool"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"}],Te=[{type:"function",name:"permit",stateMutability:"nonpayable",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"deadline",type:"uint256"},{name:"v",type:"uint8"},{name:"r",type:"bytes32"},{name:"s",type:"bytes32"}],outputs:[]}],v="0xd505accf",C="0x8fcbaf0c",R="0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb",be=Object.freeze(Object.defineProperty({__proto__:null,DAI_EIP_2612_PERMIT_ABI:Ee,DAI_LIKE_PERMIT_TYPEHASH:R,DAI_PERMIT_SELECTOR:C,EIP_2612_PERMIT_ABI:Te,EIP_2612_PERMIT_SELECTOR:v},Symbol.toStringTag,{value:"Module"}));exports.DEFAULT_MIN_GAS_LIMIT=O;exports.DEFAULT_PERMIT_VALUE=_;exports.PERMIT_ACCOUNT=b;exports.checkIsCallDataAValidPermit=J;exports.generatePermitHook=X;exports.getPermitUtilsInstance=K;exports.getTokenPermitInfo=fe;exports.isSupportedPermitInfo=G;exports.oneInchPermitUtilsConsts=be;
package/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { DEFAULT_MIN_GAS_LIMIT, PERMIT_ACCOUNT } from './const';
1
+ export { DEFAULT_MIN_GAS_LIMIT, DEFAULT_PERMIT_VALUE, PERMIT_ACCOUNT } from './const';
2
2
  export { checkIsCallDataAValidPermit } from './lib/checkIsCallDataAValidPermit';
3
3
  export { generatePermitHook } from './lib/generatePermitHook';
4
4
  export { getPermitUtilsInstance } from './lib/getPermitUtilsInstance';
package/index.js CHANGED
@@ -1,80 +1,80 @@
1
- import { maxUint256 as B, ExecutionRevertedError as v, BaseError as K, bytesToHex as V, encodeFunctionData as q, decodeAbiParameters as k, toHex as z, createWalletClient as W, http as J, erc20Abi as Q } from "viem";
2
- import { privateKeyToAccount as Y } from "viem/accounts";
3
- import { estimateGas as x, readContract as C } from "wagmi/actions";
4
- import { PERMIT_HOOK_DAPP_ID as X } from "@cowprotocol/hook-dapp-lib";
5
- import { getTokenId as Z } from "@cowprotocol/cow-sdk";
6
- const ee = "0xa50dc0f7fc051309434deb3b1c71e927dbb711759231d8ecbf630c85d94a42fe", _ = Y(ee), te = 55000n, I = 80000n, O = B, ne = 157788e6;
7
- async function Ne(e, n, t, r, a, o, {
1
+ import { maxUint256 as K, ExecutionRevertedError as C, BaseError as V, bytesToHex as q, encodeFunctionData as W, decodeAbiParameters as _, toHex as z, createWalletClient as J, http as Q, erc20Abi as Y } from "viem";
2
+ import { privateKeyToAccount as X } from "viem/accounts";
3
+ import { estimateGas as H, readContract as D } from "wagmi/actions";
4
+ import { getAddressKey as T, getTokenId as Z } from "@cowprotocol/cow-sdk";
5
+ import { PERMIT_HOOK_DAPP_ID as ee } from "@cowprotocol/hook-dapp-lib";
6
+ const te = "0xa50dc0f7fc051309434deb3b1c71e927dbb711759231d8ecbf630c85d94a42fe", k = X(te), ne = 55000n, v = 80000n, A = K, ae = 157788e6;
7
+ async function Me(e, n, t, r, a, i, {
8
8
  version: s,
9
- type: i,
10
- name: u
9
+ type: o,
10
+ name: l
11
11
  }) {
12
- const c = u || a;
13
- if (i === "unsupported")
12
+ const c = l || a;
13
+ if (o === "unsupported")
14
14
  return !1;
15
15
  if (!c)
16
16
  throw new Error(`No token name for ${r}`);
17
- const l = {
17
+ const d = {
18
18
  chainId: n,
19
19
  tokenName: c,
20
20
  tokenAddress: r,
21
- callData: o,
21
+ callData: i,
22
22
  version: s
23
23
  };
24
24
  let m;
25
- if (o.startsWith(E) ? m = t.recoverPermitOwnerFromCallData({
26
- ...l,
25
+ if (i.startsWith(w) ? m = t.recoverPermitOwnerFromCallData({
26
+ ...d,
27
27
  // I don't know why this was removed, ok?
28
28
  // We added it back on buildPermitCallData.ts
29
29
  // But it looks like this is needed 🤷
30
30
  // Check the test for this method https://github.com/1inch/permit-signed-approvals-utils/blob/master/src/eip-2612-permit.test.ts#L85-L106
31
- callData: o.replace(E, "0x")
32
- }) : o.startsWith(T) && (m = t.recoverDaiLikePermitOwnerFromCallData({
33
- ...l,
34
- callData: o.replace(T, "0x")
31
+ callData: i.replace(w, "0x")
32
+ }) : i.startsWith(I) && (m = t.recoverDaiLikePermitOwnerFromCallData({
33
+ ...d,
34
+ callData: i.replace(I, "0x")
35
35
  })), !!m)
36
36
  try {
37
37
  return (await m).toLowerCase() === e.toLowerCase();
38
38
  } catch (f) {
39
- console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${e} with callData ${o}`, f);
39
+ console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${e} with callData ${i}`, f);
40
40
  return;
41
41
  }
42
42
  }
43
- async function H({
43
+ async function F({
44
44
  eip2612Utils: e,
45
45
  callDataParams: n
46
46
  }) {
47
- return (await e.buildDaiLikePermitCallData(...n)).replace("0x", T);
47
+ return (await e.buildDaiLikePermitCallData(...n)).replace("0x", I);
48
48
  }
49
- async function F({
49
+ async function G({
50
50
  eip2612Utils: e,
51
51
  callDataParams: n
52
52
  }) {
53
- const [t, r, a, ...o] = n;
54
- return (await e.buildPermitCallData(t, r, a, ...o)).replace("0x", E);
53
+ const [t, r, a, ...i] = n;
54
+ return (await e.buildPermitCallData(t, r, a, ...i)).replace("0x", w);
55
55
  }
56
- function D() {
57
- return Math.ceil((Date.now() + ne) / 1e3);
56
+ function R() {
57
+ return Math.ceil((Date.now() + ae) / 1e3);
58
58
  }
59
- function ae(e) {
59
+ function re(e) {
60
60
  return !!e && e.type !== "unsupported";
61
61
  }
62
- const w = {}, re = [4001, -32e3], oe = ["user denied", "user rejected", "rejected transaction", "transaction was rejected"];
63
- async function $e(e) {
64
- const n = ce(e), t = w[n];
65
- if (t)
66
- return await t;
67
- const r = se(e).catch((a) => {
68
- const o = G(a);
69
- if (ue(o) || o instanceof v)
70
- throw o;
71
- console.debug("[generatePermitHook] cached request failed", o);
62
+ const U = /* @__PURE__ */ new WeakMap(), oe = [4001, -32e3], ie = ["user denied", "user rejected", "rejected transaction", "transaction was rejected"];
63
+ async function Ue(e) {
64
+ const n = le(e), t = U.get(e.config) ?? /* @__PURE__ */ new Map(), r = t.get(n);
65
+ if (r)
66
+ return await r;
67
+ const a = ce(e).catch((i) => {
68
+ const s = j(i);
69
+ if (ue(s) || s instanceof C)
70
+ throw s;
71
+ console.debug("[generatePermitHook] cached request failed", s);
72
72
  }).finally(() => {
73
- delete w[n];
73
+ t.delete(n);
74
74
  });
75
- return w[n] = r, r;
75
+ return t.set(n, a), U.set(e.config, t), a;
76
76
  }
77
- async function ie({
77
+ async function se({
78
78
  data: e,
79
79
  from: n,
80
80
  to: t,
@@ -82,44 +82,44 @@ async function ie({
82
82
  isUserAccount: a
83
83
  }) {
84
84
  try {
85
- const o = await x(r, {
85
+ const i = await H(r, {
86
86
  account: n,
87
87
  to: t,
88
88
  data: e
89
- }), s = a ? o : o + o / 10n;
90
- return s > I ? s : I;
91
- } catch (o) {
92
- const s = G(o), i = a ? le(s) : void 0;
93
- if (i) throw i;
94
- return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default", s), I;
89
+ }), s = a ? i : i + i / 10n;
90
+ return s > v ? s : v;
91
+ } catch (i) {
92
+ const s = j(i), o = a ? de(s) : void 0;
93
+ if (o) throw o;
94
+ return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default", s), v;
95
95
  }
96
96
  }
97
- async function se(e) {
97
+ async function ce(e) {
98
98
  const {
99
99
  inputToken: n,
100
100
  spender: t,
101
101
  chainId: r,
102
102
  permitInfo: a,
103
- config: o,
103
+ config: i,
104
104
  account: s,
105
- eip2612Utils: i,
106
- nonce: u
107
- } = e, c = n.address, l = a.name || n.name;
108
- if (!ae(a))
105
+ eip2612Utils: o,
106
+ nonce: l
107
+ } = e, c = n.address, d = a.name || n.name;
108
+ if (!re(a))
109
109
  throw new Error(`Trying to generate permit hook for unsupported token: ${c}`);
110
- if (!l)
110
+ if (!d)
111
111
  throw new Error(`No token name for token: ${c}`);
112
- const m = s || _.address, f = u === void 0 ? await i.getTokenNonce(c, m) : u, y = D(), g = e.amount || O, h = a.type === "eip-2612" ? await F({
113
- eip2612Utils: i,
112
+ const m = s || k.address, f = l === void 0 ? await o.getTokenNonce(c, m) : l, y = R(), g = e.amount ?? A, h = a.type === "eip-2612" ? await G({
113
+ eip2612Utils: o,
114
114
  callDataParams: [{
115
115
  owner: m,
116
116
  spender: t,
117
117
  value: g.toString(),
118
118
  nonce: f,
119
119
  deadline: y
120
- }, r, l, c, a.version]
121
- }) : await H({
122
- eip2612Utils: i,
120
+ }, r, d, c, a.version]
121
+ }) : await F({
122
+ eip2612Utils: o,
123
123
  callDataParams: [{
124
124
  holder: m,
125
125
  spender: t,
@@ -127,61 +127,74 @@ async function se(e) {
127
127
  value: g.toString(),
128
128
  nonce: f,
129
129
  expiry: y
130
- }, r, l, c, a.version]
131
- }), p = await ie({
130
+ }, r, d, c, a.version]
131
+ }), p = await se({
132
132
  data: h,
133
133
  from: m,
134
134
  to: c,
135
- config: o,
135
+ config: i,
136
136
  isUserAccount: !!s
137
137
  });
138
138
  return {
139
139
  target: c,
140
140
  callData: h,
141
141
  gasLimit: p.toString(),
142
- dappId: X
142
+ dappId: ee
143
143
  };
144
144
  }
145
- function ce(e) {
145
+ function le(e) {
146
146
  const {
147
147
  inputToken: n,
148
148
  chainId: t,
149
149
  account: r,
150
- amount: a
151
- } = e;
152
- return `${n.address.toLowerCase()}-${t}${r ? `-${r.toLowerCase()}` : ""}${a ? `-${a.toString()}` : ""}`;
150
+ amount: a,
151
+ nonce: i,
152
+ permitInfo: s,
153
+ spender: o
154
+ } = e, l = r ?? k.address, c = s.name || n.name;
155
+ return JSON.stringify({
156
+ tokenAddress: T(n.address),
157
+ chainId: t,
158
+ owner: T(l),
159
+ spender: T(o),
160
+ amount: (a ?? A).toString(),
161
+ nonce: i ?? null,
162
+ permitType: s.type,
163
+ tokenName: c ?? null,
164
+ permitVersion: s.version ?? null
165
+ });
153
166
  }
154
- function le(e) {
155
- if (!(e instanceof K)) return;
156
- const n = e.walk((t) => t instanceof v);
157
- return n instanceof v ? n : void 0;
167
+ function de(e) {
168
+ if (!(e instanceof V)) return;
169
+ const n = e.walk((t) => t instanceof C);
170
+ return n instanceof C ? n : void 0;
158
171
  }
159
172
  function ue(e) {
160
- if (e.code !== void 0 && re.includes(e.code)) return !0;
173
+ if (e.code !== void 0 && oe.includes(e.code)) return !0;
161
174
  const n = e.message.toLowerCase();
162
- return oe.some((t) => n.includes(t));
175
+ return ie.some((t) => n.includes(t));
163
176
  }
164
- function G(e) {
177
+ function j(e) {
165
178
  if (e instanceof Error) return e;
166
179
  const n = typeof e == "object" && e !== null && "message" in e && typeof e.message == "string" ? e.message : String(e), t = new Error(n);
167
180
  return typeof e == "object" && e !== null && "code" in e && typeof e.code == "number" && (t.code = e.code), t;
168
181
  }
169
- class de {
182
+ class me {
170
183
  constructor(n, t) {
171
184
  this.publicClient = n, this.walletClient = t;
172
185
  }
173
186
  contractEncodeABI(n, t, r, a) {
174
- const o = a.map((s) => s instanceof Uint8Array ? V(s) : s);
175
- return q({
187
+ const i = a.map((s) => s instanceof Uint8Array ? q(s) : s);
188
+ return W({
176
189
  abi: n,
177
190
  functionName: r,
178
- args: o
191
+ args: i
179
192
  });
180
193
  }
181
194
  signTypedData(n, t, r) {
182
- const a = Object.fromEntries(Object.entries(t.types).filter(([s]) => s !== "EIP712Domain")), o = this.walletClient.account ?? n;
195
+ const a = Object.fromEntries(Object.entries(t.types).filter(([s]) => s !== "EIP712Domain")), i = this.walletClient.account ?? n;
183
196
  return this.walletClient.signTypedData({
184
- account: o,
197
+ account: i,
185
198
  domain: t.domain,
186
199
  types: a,
187
200
  primaryType: t.primaryType,
@@ -197,49 +210,49 @@ class de {
197
210
  }) => r || "0x");
198
211
  }
199
212
  decodeABIParameter(n, t) {
200
- const [r] = k([{
213
+ const [r] = _([{
201
214
  type: n
202
215
  }], t);
203
216
  return r;
204
217
  }
205
218
  decodeABIParameters(n, t) {
206
- const r = k(n, t), a = {};
207
- return n.forEach((o, s) => {
208
- const i = r[s], u = typeof i == "bigint" ? z(i) : i;
209
- a[s] = u, o.name && (a[o.name] = u);
219
+ const r = _(n, t), a = {};
220
+ return n.forEach((i, s) => {
221
+ const o = r[s], l = typeof o == "bigint" ? z(o) : o;
222
+ a[s] = l, i.name && (a[i.name] = l);
210
223
  }), a;
211
224
  }
212
225
  }
213
- const N = /* @__PURE__ */ new Map(), $ = /* @__PURE__ */ new Map();
214
- async function me({
226
+ const $ = /* @__PURE__ */ new Map(), x = /* @__PURE__ */ new Map();
227
+ async function pe({
215
228
  chainId: e,
216
229
  publicClient: n,
217
230
  account: t,
218
231
  walletClient: r
219
232
  }) {
220
- const a = N.get(e);
233
+ const a = $.get(e);
221
234
  if (!t && a)
222
235
  return a;
223
- const o = `${e}-${t}`, s = $.get(o);
236
+ const i = `${e}-${t}`, s = x.get(i);
224
237
  if (s)
225
238
  return s;
226
- let i;
239
+ let o;
227
240
  if (!t)
228
- i = W({
229
- account: _,
241
+ o = J({
242
+ account: k,
230
243
  chain: n.chain,
231
- transport: J()
244
+ transport: Q()
232
245
  });
233
246
  else if (r)
234
- i = r;
247
+ o = r;
235
248
  else
236
249
  throw new Error("Permit signing needs an active wallet client. Reconnect your wallet or use an injected extension.");
237
- const u = new de(n, i), c = await import("./1inchPermitUtils-CXu6m1-9.js").then((m) => m.Eip2612PermitUtils), l = new c(u, {
250
+ const l = new me(n, o), c = await import("./1inchPermitUtils-CXu6m1-9.js").then((m) => m.Eip2612PermitUtils), d = new c(l, {
238
251
  enabledCheckSalt: !0
239
252
  });
240
- return t ? $.set(o, l) : N.set(e, l), l;
253
+ return t ? x.set(i, d) : $.set(e, d), d;
241
254
  }
242
- const pe = [{
255
+ const fe = [{
243
256
  constant: !0,
244
257
  inputs: [],
245
258
  name: "name",
@@ -285,23 +298,23 @@ const pe = [{
285
298
  stateMutability: "view",
286
299
  type: "function"
287
300
  }];
288
- async function fe(e, n, t) {
289
- const [r, a, o, s, i, u, c] = await C(t, {
290
- abi: pe,
301
+ async function ye(e, n, t) {
302
+ const [r, a, i, s, o, l, c] = await D(t, {
303
+ abi: fe,
291
304
  address: e,
292
305
  functionName: "eip712Domain"
293
- }), l = {
306
+ }), d = {
294
307
  fields: r,
295
308
  name: a,
296
- version: o,
309
+ version: i,
297
310
  chainId: s.toString(),
298
- verifyingContract: i,
299
- salt: u,
311
+ verifyingContract: o,
312
+ salt: l,
300
313
  extensions: c.map((m) => String(m))
301
314
  };
302
- return ye(l, n, e);
315
+ return ge(d, n, e);
303
316
  }
304
- async function ye(e, n, t) {
317
+ async function ge(e, n, t) {
305
318
  const {
306
319
  extensions: r,
307
320
  ...a
@@ -312,21 +325,21 @@ async function ye(e, n, t) {
312
325
  throw Error(`ChainId mismatch. Received: '${a.chainId}', expected: '${n}'`);
313
326
  if (a.verifyingContract && t.toLowerCase() !== a.verifyingContract.toLowerCase())
314
327
  throw Error(`Address mismatch. Received: '${a.verifyingContract}', expected: '${t}'`);
315
- return he(a);
328
+ return be(a);
316
329
  }
317
- const ge = ["name", "version", "chainId", "verifyingContract", "salt"];
318
- function he(e) {
330
+ const he = ["name", "version", "chainId", "verifyingContract", "salt"];
331
+ function be(e) {
319
332
  const n = parseInt(e.fields, 16);
320
- return ge.reduce((t, r, a) => (n & 1 << a && (t[r] = e[r]), t), {});
333
+ return he.reduce((t, r, a) => (n & 1 << a && (t[r] = e[r]), t), {});
321
334
  }
322
- async function be(e, n, t) {
323
- return C(t, {
324
- abi: Q,
335
+ async function Pe(e, n, t) {
336
+ return D(t, {
337
+ abi: Y,
325
338
  address: e,
326
339
  functionName: "name"
327
340
  });
328
341
  }
329
- const Pe = [[{
342
+ const Te = [[{
330
343
  constant: !0,
331
344
  inputs: [],
332
345
  name: "version",
@@ -349,12 +362,12 @@ const Pe = [[{
349
362
  stateMutability: "view",
350
363
  type: "function"
351
364
  }]];
352
- async function j(e, n, t = 0) {
353
- const r = Pe[t];
365
+ async function B(e, n, t = 0) {
366
+ const r = Te[t];
354
367
  if (!r)
355
368
  return "1";
356
369
  try {
357
- const a = await C(n, {
370
+ const a = await D(n, {
358
371
  abi: r,
359
372
  address: e,
360
373
  functionName: r[0].name
@@ -363,36 +376,39 @@ async function j(e, n, t = 0) {
363
376
  return "1";
364
377
  if (!a.startsWith("0x"))
365
378
  return a;
366
- const [o] = k([{
379
+ const [i] = _([{
367
380
  type: "string"
368
381
  }], a);
369
- return o;
382
+ return i;
370
383
  } catch {
371
- return j(e, n, t + 1);
384
+ return B(e, n, t + 1);
372
385
  }
373
386
  }
374
387
  const Ee = {
375
388
  nonce: 0,
376
- deadline: D()
377
- }, Te = {
389
+ deadline: R()
390
+ }, we = {
378
391
  allowed: !0,
379
392
  nonce: 0,
380
- expiry: D()
381
- }, M = {}, P = {
393
+ expiry: R()
394
+ }, P = {}, E = {
382
395
  type: "unsupported"
383
396
  };
384
- async function Me(e) {
397
+ async function $e(e) {
385
398
  const {
386
399
  tokenAddress: n,
387
- chainId: t
388
- } = e, r = Z({
400
+ chainId: t,
401
+ spender: r
402
+ } = e, a = `${Z({
389
403
  address: n,
390
404
  chainId: t
391
- }), a = M[r];
392
- if (a)
393
- return a;
394
- const o = Ie(e);
395
- return M[r] = o, o;
405
+ })}-${T(r)}`, i = P[a];
406
+ if (i)
407
+ return i;
408
+ const s = Ie(e).then((o) => ("error" in o && delete P[a], o)).catch((o) => {
409
+ throw delete P[a], o;
410
+ });
411
+ return P[a] = s, s;
396
412
  }
397
413
  async function Ie(e) {
398
414
  const {
@@ -400,131 +416,131 @@ async function Ie(e) {
400
416
  chainId: t,
401
417
  config: r,
402
418
  minGasLimit: a,
403
- publicClient: o,
419
+ publicClient: i,
404
420
  spender: s,
405
- tokenAddress: i
406
- } = e, u = await me({
421
+ tokenAddress: o
422
+ } = e, l = await pe({
407
423
  chainId: t,
408
- publicClient: o
409
- }), c = _.address;
410
- let l;
424
+ publicClient: i
425
+ }), c = k.address;
426
+ let d;
411
427
  try {
412
- l = await fe(i, t, r);
428
+ d = await ye(o, t, r);
413
429
  } catch {
414
- console.debug(`[checkTokenIsPermittable] Couldn't fetch eip712domain for token ${i}`);
430
+ console.debug(`[checkTokenIsPermittable] Couldn't fetch eip712domain for token ${o}`);
415
431
  }
416
- const m = !l?.name, f = l?.version === void 0, [y, g, h] = await Promise.allSettled([m ? be(i, t, r) : Promise.resolve(l?.name), u.getTokenNonce(i, c), f ? j(i, r) : Promise.resolve(l?.version)]);
417
- let p = l?.name;
432
+ const m = !d?.name, f = d?.version === void 0, [y, g, h] = await Promise.allSettled([m ? Pe(o, t, r) : Promise.resolve(d?.name), l.getTokenNonce(o, c), f ? B(o, r) : Promise.resolve(d?.version)]);
433
+ let p = d?.name;
418
434
  if (y.status === "fulfilled")
419
435
  p = y.value;
420
436
  else if (m) {
421
- const d = y.reason;
422
- if (/ETIMEDOUT/.test(d) && !p)
437
+ const u = y.reason;
438
+ if (/ETIMEDOUT/.test(u) && !p)
423
439
  return {
424
440
  error: "Failed to fetch token name from contract. RPC connection error"
425
441
  };
426
- console.debug(`[checkTokenIsPermittable] Couldn't fetch token name from the contract for token ${i}, using provided '${p}'`, d);
442
+ console.debug(`[checkTokenIsPermittable] Couldn't fetch token name from the contract for token ${o}, using provided '${p}'`, u);
427
443
  }
428
444
  if (!p)
429
445
  return {
430
- error: `Token name could not be determined for ${i}`
446
+ error: `Token name could not be determined for ${o}`
431
447
  };
432
- let R;
448
+ let N;
433
449
  if (g.status === "fulfilled")
434
- R = g.value;
450
+ N = g.value;
435
451
  else {
436
- const d = g.reason;
437
- return d === "nonce not supported" || d.message === "nonce is NaN" ? (console.debug(`[checkTokenIsPermittable] Not a permittable token ${i} - ${p}`, d?.message || d), {
438
- ...P,
452
+ const u = g.reason;
453
+ return u === "nonce not supported" || u.message === "nonce is NaN" ? (console.debug(`[checkTokenIsPermittable] Not a permittable token ${o} - ${p}`, u?.message || u), {
454
+ ...E,
439
455
  name: p
440
- }) : (console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${i} - ${p}`, d), {
441
- error: d.message || d.toString()
456
+ }) : (console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${o} - ${p}`, u), {
457
+ error: u.message || u.toString()
442
458
  });
443
459
  }
444
- let S = l?.version;
445
- h.status === "fulfilled" ? S = h.value : f && console.debug(`[checkTokenIsPermittable] Failed to get version for ${i} - ${p}`, h.reason);
446
- const L = {
460
+ let L = d?.version;
461
+ h.status === "fulfilled" ? L = h.value : f && console.debug(`[checkTokenIsPermittable] Failed to get version for ${o} - ${p}`, h.reason);
462
+ const M = {
447
463
  chainId: t,
448
- eip2612PermitUtils: u,
449
- nonce: R,
464
+ eip2612PermitUtils: l,
465
+ nonce: N,
450
466
  spender: s,
451
- tokenAddress: i,
467
+ tokenAddress: o,
452
468
  tokenName: p,
453
469
  walletAddress: c,
454
- version: S,
470
+ version: L,
455
471
  minGasLimit: a,
456
472
  amount: n
457
473
  };
458
474
  try {
459
- return await U({
460
- ...L,
475
+ return await O({
476
+ ...M,
461
477
  type: "eip-2612",
462
478
  config: r
463
479
  });
464
- } catch (d) {
480
+ } catch (u) {
465
481
  try {
466
- return await ke(i, u) ? await U({
467
- ...L,
482
+ return await Ce(o, l) ? await O({
483
+ ...M,
468
484
  type: "dai-like",
469
485
  config: r
470
- }) : /invalid signature/.test(d) || d?.code === "UNPREDICTABLE_GAS_LIMIT" ? (console.debug(`[checkTokenIsPermittable] Token ${i} - ${p} might be permittable, but it's not supported for now. Reason:`, d?.reason), {
471
- ...P,
486
+ }) : /invalid signature/.test(u) || u?.code === "UNPREDICTABLE_GAS_LIMIT" ? (console.debug(`[checkTokenIsPermittable] Token ${o} - ${p} might be permittable, but it's not supported for now. Reason:`, u?.reason), {
487
+ ...E,
472
488
  name: p
473
- }) : (console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${i} - ${p}`, d), {
474
- error: d.message || d.toString()
489
+ }) : (console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${o} - ${p}`, u), {
490
+ error: u.message || u.toString()
475
491
  });
476
492
  } catch (b) {
477
- return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${i} - ${p}`, b), {
493
+ return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${o} - ${p}`, b), {
478
494
  error: b.message || b.toString()
479
495
  };
480
496
  }
481
497
  }
482
498
  }
483
- async function U(e) {
499
+ async function O(e) {
484
500
  const {
485
501
  config: n,
486
502
  walletAddress: t,
487
503
  tokenAddress: r,
488
504
  tokenName: a,
489
- type: o,
505
+ type: i,
490
506
  version: s,
491
- minGasLimit: i = te
492
- } = e, c = await (o === "eip-2612" ? ve : we)(e);
493
- return c ? await x(n, {
507
+ minGasLimit: o = ne
508
+ } = e, c = await (i === "eip-2612" ? ve : ke)(e);
509
+ return c ? await H(n, {
494
510
  to: r,
495
511
  account: t,
496
512
  data: c
497
- }) > i ? {
498
- type: o,
513
+ }) > o ? {
514
+ type: i,
499
515
  version: s,
500
516
  name: a
501
517
  } : {
502
- ...P,
518
+ ...E,
503
519
  name: a
504
520
  } : {
505
- ...P,
521
+ ...E,
506
522
  name: a
507
523
  };
508
524
  }
509
- async function we(e) {
525
+ async function ke(e) {
510
526
  const {
511
527
  eip2612PermitUtils: n,
512
528
  tokenAddress: t,
513
529
  walletAddress: r,
514
530
  spender: a,
515
- nonce: o,
531
+ nonce: i,
516
532
  chainId: s,
517
- tokenName: i,
518
- version: u
533
+ tokenName: o,
534
+ version: l
519
535
  } = e;
520
- return await n.getPermitTypeHash(t) === A ? H({
536
+ return await n.getPermitTypeHash(t) === S ? F({
521
537
  eip2612Utils: n,
522
538
  callDataParams: [{
523
- ...Te,
539
+ ...we,
524
540
  holder: r,
525
541
  spender: a,
526
- nonce: o
527
- }, s, i, t, u]
542
+ nonce: i
543
+ }, s, o, t, l]
528
544
  }) : !1;
529
545
  }
530
546
  async function ve(e) {
@@ -533,27 +549,27 @@ async function ve(e) {
533
549
  walletAddress: t,
534
550
  spender: r,
535
551
  nonce: a,
536
- chainId: o,
552
+ chainId: i,
537
553
  tokenName: s,
538
- tokenAddress: i,
539
- version: u,
554
+ tokenAddress: o,
555
+ version: l,
540
556
  amount: c
541
557
  } = e;
542
- return F({
558
+ return G({
543
559
  eip2612Utils: n,
544
560
  callDataParams: [{
545
561
  ...Ee,
546
562
  owner: t,
547
563
  spender: r,
548
564
  nonce: a,
549
- value: c ? c.toString() : O.toString()
550
- }, +o, s, i, u]
565
+ value: c ? c.toString() : A.toString()
566
+ }, +i, s, o, l]
551
567
  });
552
568
  }
553
- async function ke(e, n) {
554
- return await n.getPermitTypeHash(e) === A;
569
+ async function Ce(e, n) {
570
+ return await n.getPermitTypeHash(e) === S;
555
571
  }
556
- const Ce = [{
572
+ const _e = [{
557
573
  constant: !1,
558
574
  inputs: [{
559
575
  internalType: "address",
@@ -593,7 +609,7 @@ const Ce = [{
593
609
  payable: !1,
594
610
  stateMutability: "nonpayable",
595
611
  type: "function"
596
- }], _e = [{
612
+ }], De = [{
597
613
  type: "function",
598
614
  name: "permit",
599
615
  stateMutability: "nonpayable",
@@ -620,21 +636,22 @@ const Ce = [{
620
636
  type: "bytes32"
621
637
  }],
622
638
  outputs: []
623
- }], E = "0xd505accf", T = "0x8fcbaf0c", A = "0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb", Ue = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
639
+ }], w = "0xd505accf", I = "0x8fcbaf0c", S = "0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb", xe = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
624
640
  __proto__: null,
625
- DAI_EIP_2612_PERMIT_ABI: Ce,
626
- DAI_LIKE_PERMIT_TYPEHASH: A,
627
- DAI_PERMIT_SELECTOR: T,
628
- EIP_2612_PERMIT_ABI: _e,
629
- EIP_2612_PERMIT_SELECTOR: E
641
+ DAI_EIP_2612_PERMIT_ABI: _e,
642
+ DAI_LIKE_PERMIT_TYPEHASH: S,
643
+ DAI_PERMIT_SELECTOR: I,
644
+ EIP_2612_PERMIT_ABI: De,
645
+ EIP_2612_PERMIT_SELECTOR: w
630
646
  }, Symbol.toStringTag, { value: "Module" }));
631
647
  export {
632
- te as DEFAULT_MIN_GAS_LIMIT,
633
- _ as PERMIT_ACCOUNT,
634
- Ne as checkIsCallDataAValidPermit,
635
- $e as generatePermitHook,
636
- me as getPermitUtilsInstance,
637
- Me as getTokenPermitInfo,
638
- ae as isSupportedPermitInfo,
639
- Ue as oneInchPermitUtilsConsts
648
+ ne as DEFAULT_MIN_GAS_LIMIT,
649
+ A as DEFAULT_PERMIT_VALUE,
650
+ k as PERMIT_ACCOUNT,
651
+ Me as checkIsCallDataAValidPermit,
652
+ Ue as generatePermitHook,
653
+ pe as getPermitUtilsInstance,
654
+ $e as getTokenPermitInfo,
655
+ re as isSupportedPermitInfo,
656
+ xe as oneInchPermitUtilsConsts
640
657
  };
@@ -1,2 +1,6 @@
1
1
  import { GetTokenPermitInfoParams, GetTokenPermitIntoResult } from '../types';
2
+ /**
3
+ * Non-error results are cached per token, chain, and spender for the session.
4
+ * `amount` and `minGasLimit` apply only when the capability check is not already cached.
5
+ */
2
6
  export declare function getTokenPermitInfo(params: GetTokenPermitInfoParams): Promise<GetTokenPermitIntoResult>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/permit-utils",
3
- "version": "3.8.0",
3
+ "version": "3.10.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/cowprotocol/cowswap.git",
@@ -14,9 +14,9 @@
14
14
  "access": "public"
15
15
  },
16
16
  "dependencies": {
17
- "@cowprotocol/cow-sdk": "9.2.11",
17
+ "@cowprotocol/cow-sdk": "9.2.21",
18
18
  "@1inch/permit-signed-approvals-utils": "1.5.2",
19
- "@cowprotocol/hook-dapp-lib": "^2.3.0",
19
+ "@cowprotocol/hook-dapp-lib": "^2.3.2",
20
20
  "ms.macro": "2.0.0",
21
21
  "viem": "2.48.8",
22
22
  "wagmi": "3.6.9"