@cowprotocol/permit-utils 3.6.0 → 3.7.1

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