@cowprotocol/permit-utils 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/const.d.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import { SupportedChainId } from '@cowprotocol/cow-sdk';
1
2
  import { Wallet } from '@ethersproject/wallet';
2
3
  export declare const PERMIT_SIGNER: Wallet;
3
- export declare const PERMIT_GAS_LIMIT_MIN: Record<number, number>;
4
+ export declare const PERMIT_GAS_LIMIT_MIN: Record<SupportedChainId, number>;
4
5
  export declare const DEFAULT_PERMIT_GAS_LIMIT = "80000";
5
6
  export declare const DEFAULT_PERMIT_VALUE: string;
6
7
  export declare const DEFAULT_PERMIT_DURATION: number;
package/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@1inch/permit-signed-approvals-utils"),M=require("@ethersproject/constants"),U=require("@ethersproject/wallet"),w=require("@ethersproject/abi"),H=require("@ethersproject/bignumber"),O=require("@ethersproject/contracts"),F=require("@ethersproject/address");function A(t){return t==="USD//C"?"USD Coin":t}async function q(t,n,e,a,o,r,{version:i,type:c,name:l}){const d=l||o;if(c==="unsupported")return!1;if(!d)throw new Error(`No token name for ${a}`);const m={chainId:n,tokenName:A(d),tokenAddress:a,callData:r,version:i};let u;if(r.startsWith(p.EIP_2612_PERMIT_SELECTOR)?u=e.recoverPermitOwnerFromCallData({...m,callData:r.replace(p.EIP_2612_PERMIT_SELECTOR,"0x")}):r.startsWith(p.DAI_PERMIT_SELECTOR)&&(u=e.recoverDaiLikePermitOwnerFromCallData({...m,callData:r.replace(p.DAI_PERMIT_SELECTOR,"0x")})),!!u)try{return(await u).toLowerCase()===t.toLowerCase()}catch(s){return console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${t} with callData ${r}`,s),!1}}const x="0xec10458cfaafb32533a4a27e18d9da345758094dde7052521b939a41c55dd1b0",h=new U.Wallet(x),G={1:55e3,100:55e3,5:36e3},I="80000",D=M.MaxUint256.toString(),K=157788e6,V=new Set(["0x6b175474e89094c44da98b954eedeac495271d0f"]);async function S({eip2162Utils:t,callDataParams:n}){const[e,a,o,...r]=n;return(await t.buildPermitCallData(e,a,A(o),...r)).replace("0x",p.EIP_2612_PERMIT_SELECTOR)}async function v({eip2162Utils:t,callDataParams:n}){return(await t.buildDaiLikePermitCallData(...n)).replace("0x",p.DAI_PERMIT_SELECTOR)}function T(){return Math.ceil((Date.now()+K)/1e3)}function L(t){return!!t&&t.type!=="unsupported"}const f={};async function B(t){const n=Q(t),e=f[n];if(e)try{return await e}catch(o){console.debug("[generatePermitHookWith] cached request failed",o),delete f[n]}const a=j(t).then(o=>(delete f[n],o));return f[n]=a,a}async function j(t){const{inputToken:n,spender:e,chainId:a,permitInfo:o,provider:r,account:i,eip2162Utils:c,nonce:l}=t,d=n.address,m=o.name||n.name;if(!L(o))throw new Error(`Trying to generate permit hook for unsupported token: ${d}`);if(!m)throw new Error(`No token name for token: ${d}`);const u=i||h.address,s=l===void 0?await c.getTokenNonce(d,u):l,P=T(),k=D,E=o.type==="eip-2612"?await S({eip2162Utils:c,callDataParams:[{owner:u,spender:e,value:k,nonce:s,deadline:P},a,m,d,o.version]}):await v({eip2162Utils:c,callDataParams:[{holder:u,spender:e,allowed:!0,value:k,nonce:s,expiry:P},a,m,d,o.version]}),N=await W(E,u,d,r,!!i);return{target:d,callData:E,gasLimit:N}}async function W(t,n,e,a,o){try{const r=await a.estimateGas({data:t,from:n,to:e}),i=o?r:r.add(r.div(10));return i.gt(I)?i.toString():I}catch(r){return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default",r),I}}function Q(t){const{inputToken:n,chainId:e,account:a}=t;return`${n.address.toLowerCase()}-${e}${a?`-${a.toLowerCase()}`:""}`}function R(t,n,e){return new O.Contract(t,n,e)}class Y{constructor(n,e){this.provider=n,this.walletSigner=e}contractEncodeABI(n,e,a,o){return R(e||"",n,this.provider).interface.encodeFunctionData(a,o)}signTypedData(n,e,a){const o=Object.keys(e.types).reduce((i,c)=>(c!=="EIP712Domain"&&(i[c]=e.types[c]),i),{});return(this.walletSigner||this.provider.getSigner())._signTypedData(e.domain,o,e.message)}ethCall(n,e){return this.provider.call({to:n,data:e})}decodeABIParameter(n,e){return w.defaultAbiCoder.decode([n],e)[0]}decodeABIParameters(n,e){const a=w.defaultAbiCoder.decode(n,e);if(a&&typeof a=="object"){const o={};return Object.keys(a).forEach(r=>{const i=a[r];H.BigNumber.isBigNumber(i)?o[r]=i.toHexString():o[r]=i}),o}return a}}const _=new Map,y=new Map;function $(t,n,e){const a=_.get(t);if(!e&&a)return a;const o=`${t}-${e}`,r=y.get(o);if(r)return r;const i=new Y(n,e?void 0:h),c=new p.Eip2612PermitUtils(i);return e?(console.log(`[getPermitUtilsInstance] Set cached provider utils for chain ${t}-${e}`,c),y.set(o,c)):(console.log(`[getPermitUtilsInstance] Set cached chain utils for chain ${t}`,c),_.set(t,c)),c}const z=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"}];async function J(t,n,e){const a=F.getAddress(t);return R(a,z,e).callStatic.name()}const X={value:D,nonce:0,deadline:T()},Z={allowed:!0,nonce:0,expiry:T()},C={},g={type:"unsupported"};async function ee(t){const{tokenAddress:n,chainId:e}=t,a=`${e}-${n.toLowerCase()}`,o=C[a];if(o)return o;const r=te(t);return C[a]=r,r}async function te(t){const{spender:n,tokenAddress:e,tokenName:a,chainId:o,provider:r}=t,i=$(o,r),c=h.address;let l=a;try{l=await J(e,o,r)}catch(s){if(/ETIMEDOUT/.test(s)&&!l)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 ${e}, using provided '${l}'`,s)}if(!l)return{error:`Token name could not be determined for ${e}`};let d;try{d=await i.getTokenNonce(e,c)}catch(s){return s==="nonce not supported"||s.message==="nonce is NaN"?(console.debug(`[checkTokenIsPermittable] Not a permittable token ${e} - ${l}`,s?.message||s),{...g,name:l}):(console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${e} - ${l}`,s),{error:s.message||s.toString()})}let m;if(!V.has(e))try{m=await i.getTokenVersion(e)}catch(s){console.debug(`[checkTokenIsPermittable] Failed to get version for ${e} - ${l}`,s)}const u={chainId:o,eip2612PermitUtils:i,nonce:d,spender:n,tokenAddress:e,tokenName:l,walletAddress:c,version:m};try{return await b({...u,type:"eip-2612",provider:r})}catch(s){try{return await re(e,i)?await b({...u,type:"dai-like",provider:r}):/invalid signature/.test(s)||s?.code==="UNPREDICTABLE_GAS_LIMIT"?(console.debug(`[checkTokenIsPermittable] Token ${e} - ${l} might be permittable, but it's not supported for now. Reason:`,s?.reason),{...g,name:l}):(console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${e} - ${l}`,s),{error:s.message||s.toString()})}catch(P){return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${e} - ${l}`,P),{error:P.message||P.toString()}}}}async function b(t){const{provider:n,chainId:e,walletAddress:a,tokenAddress:o,tokenName:r,type:i,version:c}=t,d=await(i==="eip-2612"?ne:ae)(t);return d?(await n.estimateGas({data:d,from:a,to:o})).toNumber()>G[e]?{type:i,version:c,name:r}:{...g,name:r}:{...g,name:r}}async function ne(t){const{eip2612PermitUtils:n,walletAddress:e,spender:a,nonce:o,chainId:r,tokenName:i,tokenAddress:c,version:l}=t;return S({eip2162Utils:n,callDataParams:[{...X,owner:e,spender:a,nonce:o},+r,i,c,l]})}async function re(t,n){return await n.getPermitTypeHash(t)===p.DAI_LIKE_PERMIT_TYPEHASH}async function ae(t){const{eip2612PermitUtils:n,tokenAddress:e,walletAddress:a,spender:o,nonce:r,chainId:i,tokenName:c,version:l}=t;return await n.getPermitTypeHash(e)===p.DAI_LIKE_PERMIT_TYPEHASH?v({eip2162Utils:n,callDataParams:[{...Z,holder:a,spender:o,nonce:r},i,c,e,l]}):!1}exports.checkIsCallDataAValidPermit=q;exports.generatePermitHook=B;exports.getPermitUtilsInstance=$;exports.getTokenPermitInfo=ee;exports.isSupportedPermitInfo=L;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@cowprotocol/cow-sdk"),U=require("@ethersproject/constants"),H=require("@ethersproject/wallet"),p=require("@1inch/permit-signed-approvals-utils"),C=require("@ethersproject/abi"),O=require("@ethersproject/bignumber"),F=require("@ethersproject/contracts"),G=require("@ethersproject/address"),q="0x4dae303b820e9878cafeb0f84edcc015e8a81b1bff510e824e4fc27544e458dd",h=new H.Wallet(q),x={[f.SupportedChainId.MAINNET]:55e3,[f.SupportedChainId.GNOSIS_CHAIN]:55e3,[f.SupportedChainId.SEPOLIA]:55e3,[f.SupportedChainId.GOERLI]:36e3},T="80000",A=U.MaxUint256.toString(),K=157788e6,V=new Set(["0x6b175474e89094c44da98b954eedeac495271d0f"]);function D(t){return t==="USD//C"?"USD Coin":t}async function B(t,n,e,o,a,r,{version:i,type:c,name:d}){const l=d||a;if(c==="unsupported")return!1;if(!l)throw new Error(`No token name for ${o}`);const m={chainId:n,tokenName:D(l),tokenAddress:o,callData:r,version:i};let u;if(r.startsWith(p.EIP_2612_PERMIT_SELECTOR)?u=e.recoverPermitOwnerFromCallData({...m,callData:r.replace(p.EIP_2612_PERMIT_SELECTOR,"0x")}):r.startsWith(p.DAI_PERMIT_SELECTOR)&&(u=e.recoverDaiLikePermitOwnerFromCallData({...m,callData:r.replace(p.DAI_PERMIT_SELECTOR,"0x")})),!!u)try{return(await u).toLowerCase()===t.toLowerCase()}catch(s){return console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${t} with callData ${r}`,s),!1}}async function R({eip2162Utils:t,callDataParams:n}){const[e,o,a,...r]=n;return(await t.buildPermitCallData(e,o,D(a),...r)).replace("0x",p.EIP_2612_PERMIT_SELECTOR)}async function v({eip2162Utils:t,callDataParams:n}){return(await t.buildDaiLikePermitCallData(...n)).replace("0x",p.DAI_PERMIT_SELECTOR)}function E(){return Math.ceil((Date.now()+K)/1e3)}function L(t){return!!t&&t.type!=="unsupported"}const I={};async function j(t){const n=Y(t),e=I[n];if(e)try{return await e}catch(a){console.debug("[generatePermitHookWith] cached request failed",a),delete I[n]}const o=W(t).then(a=>(delete I[n],a));return I[n]=o,o}async function W(t){const{inputToken:n,spender:e,chainId:o,permitInfo:a,provider:r,account:i,eip2162Utils:c,nonce:d}=t,l=n.address,m=a.name||n.name;if(!L(a))throw new Error(`Trying to generate permit hook for unsupported token: ${l}`);if(!m)throw new Error(`No token name for token: ${l}`);const u=i||h.address,s=d===void 0?await c.getTokenNonce(l,u):d,P=E(),k=A,w=a.type==="eip-2612"?await R({eip2162Utils:c,callDataParams:[{owner:u,spender:e,value:k,nonce:s,deadline:P},o,m,l,a.version]}):await v({eip2162Utils:c,callDataParams:[{holder:u,spender:e,allowed:!0,value:k,nonce:s,expiry:P},o,m,l,a.version]}),M=await Q(w,u,l,r,!!i);return{target:l,callData:w,gasLimit:M}}async function Q(t,n,e,o,a){try{const r=await o.estimateGas({data:t,from:n,to:e}),i=a?r:r.add(r.div(10));return i.gt(T)?i.toString():T}catch(r){return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default",r),T}}function Y(t){const{inputToken:n,chainId:e,account:o}=t;return`${n.address.toLowerCase()}-${e}${o?`-${o.toLowerCase()}`:""}`}function N(t,n,e){return new F.Contract(t,n,e)}class z{constructor(n,e){this.provider=n,this.walletSigner=e}contractEncodeABI(n,e,o,a){return N(e||"",n,this.provider).interface.encodeFunctionData(o,a)}signTypedData(n,e,o){const a=Object.keys(e.types).reduce((i,c)=>(c!=="EIP712Domain"&&(i[c]=e.types[c]),i),{});return(this.walletSigner||this.provider.getSigner())._signTypedData(e.domain,a,e.message)}ethCall(n,e){return this.provider.call({to:n,data:e})}decodeABIParameter(n,e){return C.defaultAbiCoder.decode([n],e)[0]}decodeABIParameters(n,e){const o=C.defaultAbiCoder.decode(n,e);if(o&&typeof o=="object"){const a={};return Object.keys(o).forEach(r=>{const i=o[r];O.BigNumber.isBigNumber(i)?a[r]=i.toHexString():a[r]=i}),a}return o}}const _=new Map,S=new Map;function $(t,n,e){const o=_.get(t);if(!e&&o)return o;const a=`${t}-${e}`,r=S.get(a);if(r)return r;const i=new z(n,e?void 0:h),c=new p.Eip2612PermitUtils(i);return e?(console.log(`[getPermitUtilsInstance] Set cached provider utils for chain ${t}-${e}`,c),S.set(a,c)):(console.log(`[getPermitUtilsInstance] Set cached chain utils for chain ${t}`,c),_.set(t,c)),c}const J=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"}];async function X(t,n,e){const o=G.getAddress(t);return N(o,J,e).callStatic.name()}const Z={value:A,nonce:0,deadline:E()},ee={allowed:!0,nonce:0,expiry:E()},y={},g={type:"unsupported"};async function te(t){const{tokenAddress:n,chainId:e}=t,o=`${e}-${n.toLowerCase()}`,a=y[o];if(a)return a;const r=ne(t);return y[o]=r,r}async function ne(t){const{spender:n,tokenAddress:e,tokenName:o,chainId:a,provider:r}=t,i=$(a,r),c=h.address;let d=o;try{d=await X(e,a,r)}catch(s){if(/ETIMEDOUT/.test(s)&&!d)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 ${e}, using provided '${d}'`,s)}if(!d)return{error:`Token name could not be determined for ${e}`};let l;try{l=await i.getTokenNonce(e,c)}catch(s){return s==="nonce not supported"||s.message==="nonce is NaN"?(console.debug(`[checkTokenIsPermittable] Not a permittable token ${e} - ${d}`,s?.message||s),{...g,name:d}):(console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${e} - ${d}`,s),{error:s.message||s.toString()})}let m;if(!V.has(e))try{m=await i.getTokenVersion(e)}catch(s){console.debug(`[checkTokenIsPermittable] Failed to get version for ${e} - ${d}`,s)}const u={chainId:a,eip2612PermitUtils:i,nonce:l,spender:n,tokenAddress:e,tokenName:d,walletAddress:c,version:m};try{return await b({...u,type:"eip-2612",provider:r})}catch(s){try{return await oe(e,i)?await b({...u,type:"dai-like",provider:r}):/invalid signature/.test(s)||s?.code==="UNPREDICTABLE_GAS_LIMIT"?(console.debug(`[checkTokenIsPermittable] Token ${e} - ${d} might be permittable, but it's not supported for now. Reason:`,s?.reason),{...g,name:d}):(console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${e} - ${d}`,s),{error:s.message||s.toString()})}catch(P){return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${e} - ${d}`,P),{error:P.message||P.toString()}}}}async function b(t){const{provider:n,chainId:e,walletAddress:o,tokenAddress:a,tokenName:r,type:i,version:c}=t,l=await(i==="eip-2612"?re:ae)(t);return l?(await n.estimateGas({data:l,from:o,to:a})).toNumber()>x[e]?{type:i,version:c,name:r}:{...g,name:r}:{...g,name:r}}async function re(t){const{eip2612PermitUtils:n,walletAddress:e,spender:o,nonce:a,chainId:r,tokenName:i,tokenAddress:c,version:d}=t;return R({eip2162Utils:n,callDataParams:[{...Z,owner:e,spender:o,nonce:a},+r,i,c,d]})}async function oe(t,n){return await n.getPermitTypeHash(t)===p.DAI_LIKE_PERMIT_TYPEHASH}async function ae(t){const{eip2612PermitUtils:n,tokenAddress:e,walletAddress:o,spender:a,nonce:r,chainId:i,tokenName:c,version:d}=t;return await n.getPermitTypeHash(e)===p.DAI_LIKE_PERMIT_TYPEHASH?v({eip2162Utils:n,callDataParams:[{...ee,holder:o,spender:a,nonce:r},i,c,e,d]}):!1}exports.PERMIT_SIGNER=h;exports.checkIsCallDataAValidPermit=B;exports.generatePermitHook=j;exports.getPermitUtilsInstance=$;exports.getTokenPermitInfo=te;exports.isSupportedPermitInfo=L;
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { PERMIT_SIGNER } from './const';
1
2
  export { checkIsCallDataAValidPermit } from './lib/checkIsCallDataAValidPermit';
2
3
  export { generatePermitHook } from './lib/generatePermitHook';
3
4
  export { getPermitUtilsInstance } from './lib/getPermitUtilsInstance';
package/index.js CHANGED
@@ -1,14 +1,21 @@
1
- import { EIP_2612_PERMIT_SELECTOR as h, DAI_PERMIT_SELECTOR as k, Eip2612PermitUtils as U, DAI_LIKE_PERMIT_TYPEHASH as A } from "@1inch/permit-signed-approvals-utils";
1
+ import { SupportedChainId as f } from "@cowprotocol/cow-sdk";
2
2
  import { MaxUint256 as M } from "@ethersproject/constants";
3
3
  import { Wallet as H } from "@ethersproject/wallet";
4
- import { defaultAbiCoder as y } from "@ethersproject/abi";
4
+ import { EIP_2612_PERMIT_SELECTOR as k, DAI_PERMIT_SELECTOR as I, Eip2612PermitUtils as O, DAI_LIKE_PERMIT_TYPEHASH as S } from "@1inch/permit-signed-approvals-utils";
5
+ import { defaultAbiCoder as C } from "@ethersproject/abi";
5
6
  import { BigNumber as F } from "@ethersproject/bignumber";
6
- import { Contract as O } from "@ethersproject/contracts";
7
+ import { Contract as G } from "@ethersproject/contracts";
7
8
  import { getAddress as x } from "@ethersproject/address";
8
- function v(t) {
9
+ const K = "0x4dae303b820e9878cafeb0f84edcc015e8a81b1bff510e824e4fc27544e458dd", T = new H(K), V = {
10
+ [f.MAINNET]: 55e3,
11
+ [f.GNOSIS_CHAIN]: 55e3,
12
+ [f.SEPOLIA]: 55e3,
13
+ [f.GOERLI]: 36e3
14
+ }, h = "80000", v = M.toString(), B = 157788e6, q = /* @__PURE__ */ new Set(["0x6b175474e89094c44da98b954eedeac495271d0f"]);
15
+ function L(t) {
9
16
  return t === "USD//C" ? "USD Coin" : t;
10
17
  }
11
- async function ue(t, n, e, o, a, r, {
18
+ async function fe(t, n, e, o, a, r, {
12
19
  version: i,
13
20
  type: c,
14
21
  name: l
@@ -20,22 +27,22 @@ async function ue(t, n, e, o, a, r, {
20
27
  throw new Error(`No token name for ${o}`);
21
28
  const u = {
22
29
  chainId: n,
23
- tokenName: v(d),
30
+ tokenName: L(d),
24
31
  tokenAddress: o,
25
32
  callData: r,
26
33
  version: i
27
34
  };
28
35
  let m;
29
- if (r.startsWith(h) ? m = e.recoverPermitOwnerFromCallData({
36
+ if (r.startsWith(k) ? m = e.recoverPermitOwnerFromCallData({
30
37
  ...u,
31
38
  // I don't know why this was removed, ok?
32
39
  // We added it back on buildPermitCallData.ts
33
40
  // But it looks like this is needed 🤷
34
41
  // Check the test for this method https://github.com/1inch/permit-signed-approvals-utils/blob/master/src/eip-2612-permit.test.ts#L85-L106
35
- callData: r.replace(h, "0x")
36
- }) : r.startsWith(k) && (m = e.recoverDaiLikePermitOwnerFromCallData({
37
- ...u,
38
42
  callData: r.replace(k, "0x")
43
+ }) : r.startsWith(I) && (m = e.recoverDaiLikePermitOwnerFromCallData({
44
+ ...u,
45
+ callData: r.replace(I, "0x")
39
46
  })), !!m)
40
47
  try {
41
48
  return (await m).toLowerCase() === t.toLowerCase();
@@ -43,43 +50,38 @@ async function ue(t, n, e, o, a, r, {
43
50
  return console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${t} with callData ${r}`, s), !1;
44
51
  }
45
52
  }
46
- const G = "0xec10458cfaafb32533a4a27e18d9da345758094dde7052521b939a41c55dd1b0", w = new H(G), K = {
47
- 1: 55e3,
48
- 100: 55e3,
49
- 5: 36e3
50
- }, P = "80000", S = M.toString(), V = 157788e6, B = /* @__PURE__ */ new Set(["0x6b175474e89094c44da98b954eedeac495271d0f"]);
51
- async function L({
53
+ async function N({
52
54
  eip2162Utils: t,
53
55
  callDataParams: n
54
56
  }) {
55
57
  const [e, o, a, ...r] = n;
56
- return (await t.buildPermitCallData(e, o, v(a), ...r)).replace("0x", h);
58
+ return (await t.buildPermitCallData(e, o, L(a), ...r)).replace("0x", k);
57
59
  }
58
60
  async function $({
59
61
  eip2162Utils: t,
60
62
  callDataParams: n
61
63
  }) {
62
- return (await t.buildDaiLikePermitCallData(...n)).replace("0x", k);
64
+ return (await t.buildDaiLikePermitCallData(...n)).replace("0x", I);
63
65
  }
64
- function T() {
65
- return Math.ceil((Date.now() + V) / 1e3);
66
+ function w() {
67
+ return Math.ceil((Date.now() + B) / 1e3);
66
68
  }
67
- function q(t) {
69
+ function W(t) {
68
70
  return !!t && t.type !== "unsupported";
69
71
  }
70
- const f = {};
71
- async function pe(t) {
72
- const n = Q(t), e = f[n];
72
+ const g = {};
73
+ async function ge(t) {
74
+ const n = Y(t), e = g[n];
73
75
  if (e)
74
76
  try {
75
77
  return await e;
76
78
  } catch (a) {
77
- console.debug("[generatePermitHookWith] cached request failed", a), delete f[n];
79
+ console.debug("[generatePermitHookWith] cached request failed", a), delete g[n];
78
80
  }
79
- const o = W(t).then((a) => (delete f[n], a));
80
- return f[n] = o, o;
81
+ const o = j(t).then((a) => (delete g[n], a));
82
+ return g[n] = o, o;
81
83
  }
82
- async function W(t) {
84
+ async function j(t) {
83
85
  const {
84
86
  inputToken: n,
85
87
  spender: e,
@@ -90,16 +92,16 @@ async function W(t) {
90
92
  eip2162Utils: c,
91
93
  nonce: l
92
94
  } = t, d = n.address, u = a.name || n.name;
93
- if (!q(a))
95
+ if (!W(a))
94
96
  throw new Error(`Trying to generate permit hook for unsupported token: ${d}`);
95
97
  if (!u)
96
98
  throw new Error(`No token name for token: ${d}`);
97
- const m = i || w.address, s = l === void 0 ? await c.getTokenNonce(d, m) : l, p = T(), I = S, E = a.type === "eip-2612" ? await L({
99
+ const m = i || T.address, s = l === void 0 ? await c.getTokenNonce(d, m) : l, p = w(), E = v, y = a.type === "eip-2612" ? await N({
98
100
  eip2162Utils: c,
99
101
  callDataParams: [{
100
102
  owner: m,
101
103
  spender: e,
102
- value: I,
104
+ value: E,
103
105
  nonce: s,
104
106
  deadline: p
105
107
  }, o, u, d, a.version]
@@ -109,30 +111,30 @@ async function W(t) {
109
111
  holder: m,
110
112
  spender: e,
111
113
  allowed: !0,
112
- value: I,
114
+ value: E,
113
115
  nonce: s,
114
116
  expiry: p
115
117
  }, o, u, d, a.version]
116
- }), R = await j(E, m, d, r, !!i);
118
+ }), U = await Q(y, m, d, r, !!i);
117
119
  return {
118
120
  target: d,
119
- callData: E,
120
- gasLimit: R
121
+ callData: y,
122
+ gasLimit: U
121
123
  };
122
124
  }
123
- async function j(t, n, e, o, a) {
125
+ async function Q(t, n, e, o, a) {
124
126
  try {
125
127
  const r = await o.estimateGas({
126
128
  data: t,
127
129
  from: n,
128
130
  to: e
129
131
  }), i = a ? r : r.add(r.div(10));
130
- return i.gt(P) ? i.toString() : P;
132
+ return i.gt(h) ? i.toString() : h;
131
133
  } catch (r) {
132
- return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default", r), P;
134
+ return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default", r), h;
133
135
  }
134
136
  }
135
- function Q(t) {
137
+ function Y(t) {
136
138
  const {
137
139
  inputToken: n,
138
140
  chainId: e,
@@ -140,15 +142,15 @@ function Q(t) {
140
142
  } = t;
141
143
  return `${n.address.toLowerCase()}-${e}${o ? `-${o.toLowerCase()}` : ""}`;
142
144
  }
143
- function N(t, n, e) {
144
- return new O(t, n, e);
145
+ function R(t, n, e) {
146
+ return new G(t, n, e);
145
147
  }
146
- class Y {
148
+ class z {
147
149
  constructor(n, e) {
148
150
  this.provider = n, this.walletSigner = e;
149
151
  }
150
152
  contractEncodeABI(n, e, o, a) {
151
- return N(e || "", n, this.provider).interface.encodeFunctionData(o, a);
153
+ return R(e || "", n, this.provider).interface.encodeFunctionData(o, a);
152
154
  }
153
155
  signTypedData(n, e, o) {
154
156
  const a = Object.keys(e.types).reduce((i, c) => (c !== "EIP712Domain" && (i[c] = e.types[c]), i), {});
@@ -161,10 +163,10 @@ class Y {
161
163
  });
162
164
  }
163
165
  decodeABIParameter(n, e) {
164
- return y.decode([n], e)[0];
166
+ return C.decode([n], e)[0];
165
167
  }
166
168
  decodeABIParameters(n, e) {
167
- const o = y.decode(n, e);
169
+ const o = C.decode(n, e);
168
170
  if (o && typeof o == "object") {
169
171
  const a = {};
170
172
  return Object.keys(o).forEach((r) => {
@@ -175,18 +177,18 @@ class Y {
175
177
  return o;
176
178
  }
177
179
  }
178
- const C = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Map();
179
- function z(t, n, e) {
180
- const o = C.get(t);
180
+ const b = /* @__PURE__ */ new Map(), A = /* @__PURE__ */ new Map();
181
+ function J(t, n, e) {
182
+ const o = b.get(t);
181
183
  if (!e && o)
182
184
  return o;
183
- const a = `${t}-${e}`, r = b.get(a);
185
+ const a = `${t}-${e}`, r = A.get(a);
184
186
  if (r)
185
187
  return r;
186
- const i = new Y(n, e ? void 0 : w), c = new U(i);
187
- return e ? (console.log(`[getPermitUtilsInstance] Set cached provider utils for chain ${t}-${e}`, c), b.set(a, c)) : (console.log(`[getPermitUtilsInstance] Set cached chain utils for chain ${t}`, c), C.set(t, c)), c;
188
+ const i = new z(n, e ? void 0 : T), c = new O(i);
189
+ return e ? (console.log(`[getPermitUtilsInstance] Set cached provider utils for chain ${t}-${e}`, c), A.set(a, c)) : (console.log(`[getPermitUtilsInstance] Set cached chain utils for chain ${t}`, c), b.set(t, c)), c;
188
190
  }
189
- const J = [
191
+ const X = [
190
192
  {
191
193
  constant: !0,
192
194
  inputs: [],
@@ -202,42 +204,42 @@ const J = [
202
204
  type: "function"
203
205
  }
204
206
  ];
205
- async function X(t, n, e) {
207
+ async function Z(t, n, e) {
206
208
  const o = x(t);
207
- return N(o, J, e).callStatic.name();
209
+ return R(o, X, e).callStatic.name();
208
210
  }
209
- const Z = {
210
- value: S,
211
+ const ee = {
212
+ value: v,
211
213
  nonce: 0,
212
- deadline: T()
213
- }, ee = {
214
+ deadline: w()
215
+ }, te = {
214
216
  allowed: !0,
215
217
  nonce: 0,
216
- expiry: T()
217
- }, D = {}, g = {
218
+ expiry: w()
219
+ }, D = {}, P = {
218
220
  type: "unsupported"
219
221
  };
220
- async function fe(t) {
222
+ async function Pe(t) {
221
223
  const {
222
224
  tokenAddress: n,
223
225
  chainId: e
224
226
  } = t, o = `${e}-${n.toLowerCase()}`, a = D[o];
225
227
  if (a)
226
228
  return a;
227
- const r = te(t);
229
+ const r = ne(t);
228
230
  return D[o] = r, r;
229
231
  }
230
- async function te(t) {
232
+ async function ne(t) {
231
233
  const {
232
234
  spender: n,
233
235
  tokenAddress: e,
234
236
  tokenName: o,
235
237
  chainId: a,
236
238
  provider: r
237
- } = t, i = z(a, r), c = w.address;
239
+ } = t, i = J(a, r), c = T.address;
238
240
  let l = o;
239
241
  try {
240
- l = await X(e, a, r);
242
+ l = await Z(e, a, r);
241
243
  } catch (s) {
242
244
  if (/ETIMEDOUT/.test(s) && !l)
243
245
  return {
@@ -254,14 +256,14 @@ async function te(t) {
254
256
  d = await i.getTokenNonce(e, c);
255
257
  } catch (s) {
256
258
  return s === "nonce not supported" || s.message === "nonce is NaN" ? (console.debug(`[checkTokenIsPermittable] Not a permittable token ${e} - ${l}`, s?.message || s), {
257
- ...g,
259
+ ...P,
258
260
  name: l
259
261
  }) : (console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${e} - ${l}`, s), {
260
262
  error: s.message || s.toString()
261
263
  });
262
264
  }
263
265
  let u;
264
- if (!B.has(e))
266
+ if (!q.has(e))
265
267
  try {
266
268
  u = await i.getTokenVersion(e);
267
269
  } catch (s) {
@@ -285,12 +287,12 @@ async function te(t) {
285
287
  });
286
288
  } catch (s) {
287
289
  try {
288
- return await re(e, i) ? await _({
290
+ return await oe(e, i) ? await _({
289
291
  ...m,
290
292
  type: "dai-like",
291
293
  provider: r
292
294
  }) : /invalid signature/.test(s) || s?.code === "UNPREDICTABLE_GAS_LIMIT" ? (console.debug(`[checkTokenIsPermittable] Token ${e} - ${l} might be permittable, but it's not supported for now. Reason:`, s?.reason), {
293
- ...g,
295
+ ...P,
294
296
  name: l
295
297
  }) : (console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${e} - ${l}`, s), {
296
298
  error: s.message || s.toString()
@@ -311,24 +313,24 @@ async function _(t) {
311
313
  tokenName: r,
312
314
  type: i,
313
315
  version: c
314
- } = t, d = await (i === "eip-2612" ? ne : oe)(t);
316
+ } = t, d = await (i === "eip-2612" ? re : ae)(t);
315
317
  return d ? (await n.estimateGas({
316
318
  data: d,
317
319
  from: o,
318
320
  to: a
319
- })).toNumber() > K[e] ? {
321
+ })).toNumber() > V[e] ? {
320
322
  type: i,
321
323
  version: c,
322
324
  name: r
323
325
  } : {
324
- ...g,
326
+ ...P,
325
327
  name: r
326
328
  } : {
327
- ...g,
329
+ ...P,
328
330
  name: r
329
331
  };
330
332
  }
331
- async function ne(t) {
333
+ async function re(t) {
332
334
  const {
333
335
  eip2612PermitUtils: n,
334
336
  walletAddress: e,
@@ -339,20 +341,20 @@ async function ne(t) {
339
341
  tokenAddress: c,
340
342
  version: l
341
343
  } = t;
342
- return L({
344
+ return N({
343
345
  eip2162Utils: n,
344
346
  callDataParams: [{
345
- ...Z,
347
+ ...ee,
346
348
  owner: e,
347
349
  spender: o,
348
350
  nonce: a
349
351
  }, +r, i, c, l]
350
352
  });
351
353
  }
352
- async function re(t, n) {
353
- return await n.getPermitTypeHash(t) === A;
354
+ async function oe(t, n) {
355
+ return await n.getPermitTypeHash(t) === S;
354
356
  }
355
- async function oe(t) {
357
+ async function ae(t) {
356
358
  const {
357
359
  eip2612PermitUtils: n,
358
360
  tokenAddress: e,
@@ -363,10 +365,10 @@ async function oe(t) {
363
365
  tokenName: c,
364
366
  version: l
365
367
  } = t;
366
- return await n.getPermitTypeHash(e) === A ? $({
368
+ return await n.getPermitTypeHash(e) === S ? $({
367
369
  eip2162Utils: n,
368
370
  callDataParams: [{
369
- ...ee,
371
+ ...te,
370
372
  holder: o,
371
373
  spender: a,
372
374
  nonce: r
@@ -374,9 +376,10 @@ async function oe(t) {
374
376
  }) : !1;
375
377
  }
376
378
  export {
377
- ue as checkIsCallDataAValidPermit,
378
- pe as generatePermitHook,
379
- z as getPermitUtilsInstance,
380
- fe as getTokenPermitInfo,
381
- q as isSupportedPermitInfo
379
+ T as PERMIT_SIGNER,
380
+ fe as checkIsCallDataAValidPermit,
381
+ ge as generatePermitHook,
382
+ J as getPermitUtilsInstance,
383
+ Pe as getTokenPermitInfo,
384
+ W as isSupportedPermitInfo
382
385
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/permit-utils",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "type": "module",
5
5
  "dependencies": {
6
6
  "ethers": "^5.7.2",