@cowprotocol/permit-utils 3.0.0 → 3.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.
Files changed (47) hide show
  1. package/1inchPermitUtils-BDO_CqjL.cjs +1 -0
  2. package/1inchPermitUtils-CXu6m1-9.js +4 -0
  3. package/abi/versionAbis.d.ts +15 -0
  4. package/const.d.ts +24 -0
  5. package/consts/1inchPermitUtils.d.ts +25 -0
  6. package/{src/imports/1inchPermitUtils.ts → imports/1inchPermitUtils.d.ts} +1 -3
  7. package/index.cjs +1 -0
  8. package/{src/index.ts → index.d.ts} +8 -11
  9. package/index.js +547 -0
  10. package/lib/checkIsCallDataAValidPermit.d.ts +3 -0
  11. package/lib/generatePermitHook.d.ts +2 -0
  12. package/lib/getPermitUtilsInstance.d.ts +3 -0
  13. package/lib/getTokenPermitInfo.d.ts +2 -0
  14. package/package.json +19 -7
  15. package/types.d.ts +47 -0
  16. package/utils/PermitProviderConnector.d.ts +13 -0
  17. package/utils/buildPermitCallData.d.ts +3 -0
  18. package/utils/getContract.d.ts +3 -0
  19. package/utils/getEip712Domain.d.ts +13 -0
  20. package/utils/getPermitDeadline.d.ts +1 -0
  21. package/utils/getTokenName.d.ts +2 -0
  22. package/utils/getTokenPermitVersion.d.ts +2 -0
  23. package/utils/isSupportedPermitInfo.d.ts +2 -0
  24. package/CHANGELOG.md +0 -308
  25. package/jest.config.ts +0 -11
  26. package/project.json +0 -42
  27. package/src/abi/erc20.json +0 -59
  28. package/src/abi/versionAbis.ts +0 -37
  29. package/src/const.ts +0 -20
  30. package/src/consts/1inchPermitUtils.ts +0 -68
  31. package/src/lib/checkIsCallDataAValidPermit.ts +0 -64
  32. package/src/lib/generatePermitHook.ts +0 -133
  33. package/src/lib/getPermitUtilsInstance.ts +0 -51
  34. package/src/lib/getTokenPermitInfo.ts +0 -281
  35. package/src/types.ts +0 -61
  36. package/src/utils/PermitProviderConnector.ts +0 -75
  37. package/src/utils/buildPermitCallData.ts +0 -26
  38. package/src/utils/getContract.ts +0 -6
  39. package/src/utils/getEip712Domain.ts +0 -70
  40. package/src/utils/getPermitDeadline.ts +0 -7
  41. package/src/utils/getTokenName.ts +0 -13
  42. package/src/utils/getTokenPermitVersion.ts +0 -35
  43. package/src/utils/isSupportedPermitInfo.ts +0 -5
  44. package/tsconfig.json +0 -22
  45. package/tsconfig.lib.json +0 -10
  46. package/tsconfig.spec.json +0 -9
  47. package/vite.config.mts +0 -51
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@1inch/permit-signed-approvals-utils");Object.defineProperty(exports,"Eip2612PermitUtils",{enumerable:!0,get:()=>e.Eip2612PermitUtils});
@@ -0,0 +1,4 @@
1
+ import { Eip2612PermitUtils as t } from "@1inch/permit-signed-approvals-utils";
2
+ export {
3
+ t as Eip2612PermitUtils
4
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * ABIs for fetching the version of different permit flavours
3
+ */
4
+ export declare const VERSION_ABIS: {
5
+ constant: boolean;
6
+ inputs: never[];
7
+ name: string;
8
+ outputs: {
9
+ name: string;
10
+ type: string;
11
+ }[];
12
+ payable: boolean;
13
+ stateMutability: string;
14
+ type: string;
15
+ }[][];
package/const.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { Wallet } from '@ethersproject/wallet';
2
+ export declare const PERMIT_ACCOUNT: {
3
+ address: import('viem/accounts').Address;
4
+ nonceManager?: import('viem/accounts').NonceManager | undefined;
5
+ sign: (parameters: {
6
+ hash: import('viem').Hash;
7
+ }) => Promise<import('viem').Hex>;
8
+ signAuthorization: (parameters: import('viem').AuthorizationRequest) => Promise<import('viem/accounts').SignAuthorizationReturnType>;
9
+ signMessage: ({ message }: {
10
+ message: import('viem').SignableMessage;
11
+ }) => Promise<import('viem').Hex>;
12
+ signTransaction: <serializer extends import('viem').SerializeTransactionFn<import('viem').TransactionSerializable> = import('viem').SerializeTransactionFn<import('viem').TransactionSerializable>, transaction extends Parameters<serializer>[0] = Parameters<serializer>[0]>(transaction: transaction, options?: {
13
+ serializer?: serializer | undefined;
14
+ } | undefined) => Promise<import('viem').Hex>;
15
+ signTypedData: <const typedData extends import('viem').TypedData | Record<string, unknown>, primaryType extends keyof typedData | "EIP712Domain" = keyof typedData>(parameters: import('viem').TypedDataDefinition<typedData, primaryType>) => Promise<import('viem').Hex>;
16
+ publicKey: import('viem').Hex;
17
+ source: "privateKey";
18
+ type: "local";
19
+ };
20
+ export declare const PERMIT_SIGNER: Wallet;
21
+ export declare const DEFAULT_MIN_GAS_LIMIT = 55000;
22
+ export declare const DEFAULT_PERMIT_GAS_LIMIT = "80000";
23
+ export declare const DEFAULT_PERMIT_VALUE: bigint;
24
+ export declare const DEFAULT_PERMIT_DURATION: number;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @1inch/permit-signed-approvals-utils has a lot of extra variables and increases bundle size.
3
+ *
4
+ * At the same time it's repo is archived.
5
+ *
6
+ * Therefore we just copied needed constants, and when it's not possible, we should use import(...)
7
+ *
8
+ * You also can use `import type ... from '@1inch/permit-signed-approvals-utils'`
9
+ */
10
+ export declare const DAI_EIP_2612_PERMIT_ABI: {
11
+ constant: boolean;
12
+ inputs: {
13
+ internalType: string;
14
+ name: string;
15
+ type: string;
16
+ }[];
17
+ name: string;
18
+ outputs: never[];
19
+ payable: boolean;
20
+ stateMutability: string;
21
+ type: string;
22
+ }[];
23
+ export declare const EIP_2612_PERMIT_SELECTOR = "0xd505accf";
24
+ export declare const DAI_PERMIT_SELECTOR = "0x8fcbaf0c";
25
+ export declare const DAI_LIKE_PERMIT_TYPEHASH = "0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb";
@@ -5,6 +5,4 @@
5
5
  *
6
6
  * You also can use `import type ... from '@1inch/permit-signed-approvals-utils'`
7
7
  */
8
-
9
- // eslint-disable-next-line @typescript-eslint/no-restricted-imports
10
- export { Eip2612PermitUtils } from '@1inch/permit-signed-approvals-utils'
8
+ export { Eip2612PermitUtils } from '@1inch/permit-signed-approvals-utils';
package/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("@ethersproject/constants"),q=require("@ethersproject/wallet"),B=require("viem/accounts"),V=require("@cowprotocol/hook-dapp-lib"),k=require("@ethersproject/abi"),K=require("@ethersproject/bignumber"),j=require("@ethersproject/contracts"),W=require("@cowprotocol/cow-sdk"),S=require("@ethersproject/address"),L="0xa50dc0f7fc051309434deb3b1c71e927dbb711759231d8ecbf630c85d94a42fe",Q=B.privateKeyToAccount(L),I=new q.Wallet(L),$=55e3,b="80000",R=G.MaxUint256.toBigInt(),z=157788e6;async function Y(n,r,e,a,t,i,{version:o,type:d,name:u}){const s=u||t;if(d==="unsupported")return!1;if(!s)throw new Error(`No token name for ${a}`);const l={chainId:r,tokenName:s,tokenAddress:a,callData:i,version:o};let m;if(i.startsWith(h)?m=e.recoverPermitOwnerFromCallData({...l,callData:i.replace(h,"0x")}):i.startsWith(P)&&(m=e.recoverDaiLikePermitOwnerFromCallData({...l,callData:i.replace(P,"0x")})),!!m)try{return(await m).toLowerCase()===n.toLowerCase()}catch(p){return console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${n} with callData ${i}`,p),!1}}async function M({eip2612Utils:n,callDataParams:r}){const[e,a,t,...i]=r;return(await n.buildPermitCallData(e,a,t,...i)).replace("0x",h)}async function N({eip2612Utils:n,callDataParams:r}){return(await n.buildDaiLikePermitCallData(...r)).replace("0x",P)}function E(){return Math.ceil((Date.now()+z)/1e3)}function U(n){return!!n&&n.type!=="unsupported"}const w={};async function J(n){const r=ee(n),e=w[r];if(e)return await e;const a=X(n).catch(t=>{console.debug("[generatePermitHook] cached request failed",t)}).finally(()=>{delete w[r]});return w[r]=a,a}async function X(n){const{inputToken:r,spender:e,chainId:a,permitInfo:t,provider:i,account:o,eip2612Utils:d,nonce:u}=n,s=r.address,l=t.name||r.name;if(!U(t))throw new Error(`Trying to generate permit hook for unsupported token: ${s}`);if(!l)throw new Error(`No token name for token: ${s}`);const m=o||I.address,p=u===void 0?await d.getTokenNonce(s,m):u,y=E(),c=n.amount||R,f=t.type==="eip-2612"?await M({eip2612Utils:d,callDataParams:[{owner:m,spender:e,value:c.toString(),nonce:p,deadline:y},a,l,s,t.version]}):await N({eip2612Utils:d,callDataParams:[{holder:m,spender:e,allowed:!0,value:c.toString(),nonce:p,expiry:y},a,l,s,t.version]}),x=await Z(f,m,s,i,!!o);return{target:s,callData:f,gasLimit:x,dappId:V.PERMIT_HOOK_DAPP_ID}}async function Z(n,r,e,a,t){try{const i=await a.estimateGas({data:n,from:r,to:e}),o=t?i:i.add(i.div(10));return o.gt(b)?o.toString():b}catch(i){return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default",i),b}}function ee(n){const{inputToken:r,chainId:e,account:a,amount:t}=n;return`${r.address.toLowerCase()}-${e}${a?`-${a.toLowerCase()}`:""}${t?`-${t.toString()}`:""}`}function T(n,r,e){return new j.Contract(n,r,e)}class te{constructor(r,e){this.provider=r,this.walletSigner=e}contractEncodeABI(r,e,a,t){return T(e||"",r,this.provider).interface.encodeFunctionData(a,t)}signTypedData(r,e,a){const t=Object.keys(e.types).reduce((o,d)=>(d!=="EIP712Domain"&&(o[d]=e.types[d]),o),{});return(this.walletSigner||this.provider.getSigner())._signTypedData(e.domain,t,e.message)}ethCall(r,e){return this.provider.call({to:r,data:e})}decodeABIParameter(r,e){return k.defaultAbiCoder.decode([r],e)[0]}decodeABIParameters(r,e){const a=k.defaultAbiCoder.decode(r,e);if(a&&typeof a=="object"){const t={};return Object.keys(a).forEach(i=>{const o=a[i];K.BigNumber.isBigNumber(o)?t[i]=o.toHexString():t[i]=o}),t}return a}}const v=new Map,_=new Map;async function H(n,r,e){const a=v.get(n);if(!e&&a)return a;const t=`${n}-${e}`,i=_.get(t);if(i)return i;const o=new te(r,e?void 0:I),d=await Promise.resolve().then(()=>require("./1inchPermitUtils-BDO_CqjL.cjs")).then(s=>s.Eip2612PermitUtils),u=new d(o,{enabledCheckSalt:!0});return e?(console.log(`[getPermitUtilsInstance] Set cached provider utils for chain ${n}-${e}`,u),_.set(t,u)):(console.log(`[getPermitUtilsInstance] Set cached chain utils for chain ${n}`,u),v.set(n,u)),u}const O=[{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 ne(n,r,e){const a=S.getAddress(n),i=await T(a,O,e).callStatic.eip712Domain();return re(i,r,n)}async function re(n,r,e){const{extensions:a,...t}=n;if(a.length>0)throw Error("Extensions not implemented");if(t.chainId&&r!==parseInt(t.chainId,16))throw Error(`ChainId mismatch. Received: '${t.chainId}', expected: '${r}'`);if(t.verifyingContract&&e.toLowerCase()!==t.verifyingContract.toLowerCase())throw Error(`Address mismatch. Received: '${t.verifyingContract}', expected: '${e}'`);return ie(t)}const ae=["name","version","chainId","verifyingContract","salt"];function ie(n){const r=parseInt(n.fields,16);return ae.reduce((e,a,t)=>(r&1<<t&&(e[a]=n[a]),e),{})}async function oe(n,r,e){const a=S.getAddress(n);return T(a,O,e).callStatic.name()}const se=[[{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 F(n,r,e=0){const a=se[e];if(!a)return"1";try{const i=T(n,a,r).interface.encodeFunctionData(a[0].name),o=await r.call({to:n,data:i});return o==="0x"||Number.isNaN(Number(o))?"1":o.startsWith("0x")?k.defaultAbiCoder.decode(["string"],o).toString():o}catch{return F(n,r,e+1)}}const ce={nonce:0,deadline:E()},le={allowed:!0,nonce:0,expiry:E()},D={},g={type:"unsupported"};async function de(n){const{tokenAddress:r,chainId:e}=n,a=W.getTokenId({address:r,chainId:e}),t=D[a];if(t)return t;const i=ue(n);return D[a]=i,i}async function ue(n){const{spender:r,tokenAddress:e,chainId:a,provider:t,minGasLimit:i,amount:o}=n,d=await H(a,t),u=I.address;let s;try{s=await ne(e,a,t)}catch{console.debug(`[checkTokenIsPermittable] Couldn't fetch eip712domain for token ${e}`)}let l=s?.name;try{l||(l=await oe(e,a,t))}catch(c){if(/ETIMEDOUT/.test(c)&&!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}'`,c)}if(!l)return{error:`Token name could not be determined for ${e}`};let m;try{m=await d.getTokenNonce(e,u)}catch(c){return c==="nonce not supported"||c.message==="nonce is NaN"?(console.debug(`[checkTokenIsPermittable] Not a permittable token ${e} - ${l}`,c?.message||c),{...g,name:l}):(console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${e} - ${l}`,c),{error:c.message||c.toString()})}let p=s?.version;if(p===void 0)try{p=await F(e,t)}catch(c){console.debug(`[checkTokenIsPermittable] Failed to get version for ${e} - ${l}`,c)}const y={chainId:a,eip2612PermitUtils:d,nonce:m,spender:r,tokenAddress:e,tokenName:l,walletAddress:u,version:p,minGasLimit:i,amount:o};try{return await A({...y,type:"eip-2612",provider:t})}catch(c){try{return await pe(e,d)?await A({...y,type:"dai-like",provider:t}):/invalid signature/.test(c)||c?.code==="UNPREDICTABLE_GAS_LIMIT"?(console.debug(`[checkTokenIsPermittable] Token ${e} - ${l} might be permittable, but it's not supported for now. Reason:`,c?.reason),{...g,name:l}):(console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${e} - ${l}`,c),{error:c.message||c.toString()})}catch(f){return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${e} - ${l}`,f),{error:f.message||f.toString()}}}}async function A(n){const{provider:r,walletAddress:e,tokenAddress:a,tokenName:t,type:i,version:o,minGasLimit:d=$}=n,s=await(i==="eip-2612"?me:fe)(n);return s?(await r.estimateGas({data:s,from:e,to:a})).toNumber()>d?{type:i,version:o,name:t}:{...g,name:t}:{...g,name:t}}async function me(n){const{eip2612PermitUtils:r,walletAddress:e,spender:a,nonce:t,chainId:i,tokenName:o,tokenAddress:d,version:u,amount:s}=n;return M({eip2612Utils:r,callDataParams:[{...ce,owner:e,spender:a,nonce:t,value:s?s.toString():R.toString()},+i,o,d,u]})}async function pe(n,r){return await r.getPermitTypeHash(n)===C}async function fe(n){const{eip2612PermitUtils:r,tokenAddress:e,walletAddress:a,spender:t,nonce:i,chainId:o,tokenName:d,version:u}=n;return await r.getPermitTypeHash(e)===C?N({eip2612Utils:r,callDataParams:[{...le,holder:a,spender:t,nonce:i},o,d,e,u]}):!1}const ye=[{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"}],h="0xd505accf",P="0x8fcbaf0c",C="0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb",ge=Object.freeze(Object.defineProperty({__proto__:null,DAI_EIP_2612_PERMIT_ABI:ye,DAI_LIKE_PERMIT_TYPEHASH:C,DAI_PERMIT_SELECTOR:P,EIP_2612_PERMIT_SELECTOR:h},Symbol.toStringTag,{value:"Module"}));exports.DEFAULT_MIN_GAS_LIMIT=$;exports.PERMIT_ACCOUNT=Q;exports.PERMIT_SIGNER=I;exports.checkIsCallDataAValidPermit=Y;exports.generatePermitHook=J;exports.getPermitUtilsInstance=H;exports.getTokenPermitInfo=de;exports.isSupportedPermitInfo=U;exports.oneInchPermitUtilsConsts=ge;
@@ -1,11 +1,8 @@
1
- export { DEFAULT_MIN_GAS_LIMIT, PERMIT_ACCOUNT, PERMIT_SIGNER } from './const'
2
-
3
- export { checkIsCallDataAValidPermit } from './lib/checkIsCallDataAValidPermit'
4
- export { generatePermitHook } from './lib/generatePermitHook'
5
- export { getPermitUtilsInstance } from './lib/getPermitUtilsInstance'
6
- export { getTokenPermitInfo } from './lib/getTokenPermitInfo'
7
- export { isSupportedPermitInfo } from './utils/isSupportedPermitInfo'
8
-
9
- export * as oneInchPermitUtilsConsts from './consts/1inchPermitUtils'
10
-
11
- export type { GetTokenPermitIntoResult, PermitHookData, PermitHookParams, PermitInfo, PermitType } from './types'
1
+ export { DEFAULT_MIN_GAS_LIMIT, PERMIT_ACCOUNT, PERMIT_SIGNER } from './const';
2
+ export { checkIsCallDataAValidPermit } from './lib/checkIsCallDataAValidPermit';
3
+ export { generatePermitHook } from './lib/generatePermitHook';
4
+ export { getPermitUtilsInstance } from './lib/getPermitUtilsInstance';
5
+ export { getTokenPermitInfo } from './lib/getTokenPermitInfo';
6
+ export { isSupportedPermitInfo } from './utils/isSupportedPermitInfo';
7
+ export * as oneInchPermitUtilsConsts from './consts/1inchPermitUtils';
8
+ export type { GetTokenPermitIntoResult, PermitHookData, PermitHookParams, PermitInfo, PermitType } from './types';
package/index.js ADDED
@@ -0,0 +1,547 @@
1
+ import { MaxUint256 as x } from "@ethersproject/constants";
2
+ import { Wallet as O } from "@ethersproject/wallet";
3
+ import { privateKeyToAccount as F } from "viem/accounts";
4
+ import { PERMIT_HOOK_DAPP_ID as G } from "@cowprotocol/hook-dapp-lib";
5
+ import { defaultAbiCoder as w } from "@ethersproject/abi";
6
+ import { BigNumber as B } from "@ethersproject/bignumber";
7
+ import { Contract as K } from "@ethersproject/contracts";
8
+ import { getTokenId as V } from "@cowprotocol/cow-sdk";
9
+ import { getAddress as S } from "@ethersproject/address";
10
+ const L = "0xa50dc0f7fc051309434deb3b1c71e927dbb711759231d8ecbf630c85d94a42fe", be = F(L), k = new O(L), j = 55e3, I = "80000", $ = x.toBigInt(), q = 157788e6;
11
+ async function we(n, r, e, a, t, o, {
12
+ version: i,
13
+ type: d,
14
+ name: m
15
+ }) {
16
+ const s = m || t;
17
+ if (d === "unsupported")
18
+ return !1;
19
+ if (!s)
20
+ throw new Error(`No token name for ${a}`);
21
+ const l = {
22
+ chainId: r,
23
+ tokenName: s,
24
+ tokenAddress: a,
25
+ callData: o,
26
+ version: i
27
+ };
28
+ let u;
29
+ if (o.startsWith(h) ? u = e.recoverPermitOwnerFromCallData({
30
+ ...l,
31
+ // I don't know why this was removed, ok?
32
+ // We added it back on buildPermitCallData.ts
33
+ // But it looks like this is needed 🤷
34
+ // 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: o.replace(h, "0x")
36
+ }) : o.startsWith(P) && (u = e.recoverDaiLikePermitOwnerFromCallData({
37
+ ...l,
38
+ callData: o.replace(P, "0x")
39
+ })), !!u)
40
+ try {
41
+ return (await u).toLowerCase() === n.toLowerCase();
42
+ } catch (p) {
43
+ return console.debug(`[checkHasValidPendingPermit] Failed to check permit validity for owner ${n} with callData ${o}`, p), !1;
44
+ }
45
+ }
46
+ async function R({
47
+ eip2612Utils: n,
48
+ callDataParams: r
49
+ }) {
50
+ const [e, a, t, ...o] = r;
51
+ return (await n.buildPermitCallData(e, a, t, ...o)).replace("0x", h);
52
+ }
53
+ async function N({
54
+ eip2612Utils: n,
55
+ callDataParams: r
56
+ }) {
57
+ return (await n.buildDaiLikePermitCallData(...r)).replace("0x", P);
58
+ }
59
+ function E() {
60
+ return Math.ceil((Date.now() + q) / 1e3);
61
+ }
62
+ function W(n) {
63
+ return !!n && n.type !== "unsupported";
64
+ }
65
+ const b = {};
66
+ async function ke(n) {
67
+ const r = Y(n), e = b[r];
68
+ if (e)
69
+ return await e;
70
+ const a = Q(n).catch((t) => {
71
+ console.debug("[generatePermitHook] cached request failed", t);
72
+ }).finally(() => {
73
+ delete b[r];
74
+ });
75
+ return b[r] = a, a;
76
+ }
77
+ async function Q(n) {
78
+ const {
79
+ inputToken: r,
80
+ spender: e,
81
+ chainId: a,
82
+ permitInfo: t,
83
+ provider: o,
84
+ account: i,
85
+ eip2612Utils: d,
86
+ nonce: m
87
+ } = n, s = r.address, l = t.name || r.name;
88
+ if (!W(t))
89
+ throw new Error(`Trying to generate permit hook for unsupported token: ${s}`);
90
+ if (!l)
91
+ throw new Error(`No token name for token: ${s}`);
92
+ const u = i || k.address, p = m === void 0 ? await d.getTokenNonce(s, u) : m, y = E(), c = n.amount || $, f = t.type === "eip-2612" ? await R({
93
+ eip2612Utils: d,
94
+ callDataParams: [{
95
+ owner: u,
96
+ spender: e,
97
+ value: c.toString(),
98
+ nonce: p,
99
+ deadline: y
100
+ }, a, l, s, t.version]
101
+ }) : await N({
102
+ eip2612Utils: d,
103
+ callDataParams: [{
104
+ holder: u,
105
+ spender: e,
106
+ allowed: !0,
107
+ value: c.toString(),
108
+ nonce: p,
109
+ expiry: y
110
+ }, a, l, s, t.version]
111
+ }), H = await z(f, u, s, o, !!i);
112
+ return {
113
+ target: s,
114
+ callData: f,
115
+ gasLimit: H,
116
+ dappId: G
117
+ };
118
+ }
119
+ async function z(n, r, e, a, t) {
120
+ try {
121
+ const o = await a.estimateGas({
122
+ data: n,
123
+ from: r,
124
+ to: e
125
+ }), i = t ? o : o.add(o.div(10));
126
+ return i.gt(I) ? i.toString() : I;
127
+ } catch (o) {
128
+ return console.debug("[calculatePermitGasLimit] Failed to estimateGas, using default", o), I;
129
+ }
130
+ }
131
+ function Y(n) {
132
+ const {
133
+ inputToken: r,
134
+ chainId: e,
135
+ account: a,
136
+ amount: t
137
+ } = n;
138
+ return `${r.address.toLowerCase()}-${e}${a ? `-${a.toLowerCase()}` : ""}${t ? `-${t.toString()}` : ""}`;
139
+ }
140
+ function T(n, r, e) {
141
+ return new K(n, r, e);
142
+ }
143
+ class J {
144
+ constructor(r, e) {
145
+ this.provider = r, this.walletSigner = e;
146
+ }
147
+ contractEncodeABI(r, e, a, t) {
148
+ return T(e || "", r, this.provider).interface.encodeFunctionData(a, t);
149
+ }
150
+ signTypedData(r, e, a) {
151
+ const t = Object.keys(e.types).reduce((i, d) => (d !== "EIP712Domain" && (i[d] = e.types[d]), i), {});
152
+ return (this.walletSigner || this.provider.getSigner())._signTypedData(e.domain, t, e.message);
153
+ }
154
+ ethCall(r, e) {
155
+ return this.provider.call({
156
+ to: r,
157
+ data: e
158
+ });
159
+ }
160
+ decodeABIParameter(r, e) {
161
+ return w.decode([r], e)[0];
162
+ }
163
+ decodeABIParameters(r, e) {
164
+ const a = w.decode(r, e);
165
+ if (a && typeof a == "object") {
166
+ const t = {};
167
+ return Object.keys(a).forEach((o) => {
168
+ const i = a[o];
169
+ B.isBigNumber(i) ? t[o] = i.toHexString() : t[o] = i;
170
+ }), t;
171
+ }
172
+ return a;
173
+ }
174
+ }
175
+ const v = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map();
176
+ async function X(n, r, e) {
177
+ const a = v.get(n);
178
+ if (!e && a)
179
+ return a;
180
+ const t = `${n}-${e}`, o = _.get(t);
181
+ if (o)
182
+ return o;
183
+ const i = new J(r, e ? void 0 : k), d = await import("./1inchPermitUtils-CXu6m1-9.js").then((s) => s.Eip2612PermitUtils), m = new d(i, {
184
+ enabledCheckSalt: !0
185
+ });
186
+ return e ? (console.log(`[getPermitUtilsInstance] Set cached provider utils for chain ${n}-${e}`, m), _.set(t, m)) : (console.log(`[getPermitUtilsInstance] Set cached chain utils for chain ${n}`, m), v.set(n, m)), m;
187
+ }
188
+ const M = [
189
+ {
190
+ constant: !0,
191
+ inputs: [],
192
+ name: "name",
193
+ outputs: [
194
+ {
195
+ name: "",
196
+ type: "string"
197
+ }
198
+ ],
199
+ payable: !1,
200
+ stateMutability: "view",
201
+ type: "function"
202
+ },
203
+ {
204
+ inputs: [],
205
+ name: "eip712Domain",
206
+ outputs: [
207
+ {
208
+ internalType: "bytes1",
209
+ name: "fields",
210
+ type: "bytes1"
211
+ },
212
+ {
213
+ internalType: "string",
214
+ name: "name",
215
+ type: "string"
216
+ },
217
+ {
218
+ internalType: "string",
219
+ name: "version",
220
+ type: "string"
221
+ },
222
+ {
223
+ internalType: "uint256",
224
+ name: "chainId",
225
+ type: "uint256"
226
+ },
227
+ {
228
+ internalType: "address",
229
+ name: "verifyingContract",
230
+ type: "address"
231
+ },
232
+ {
233
+ internalType: "bytes32",
234
+ name: "salt",
235
+ type: "bytes32"
236
+ },
237
+ {
238
+ internalType: "uint256[]",
239
+ name: "extensions",
240
+ type: "uint256[]"
241
+ }
242
+ ],
243
+ stateMutability: "view",
244
+ type: "function"
245
+ }
246
+ ];
247
+ async function Z(n, r, e) {
248
+ const a = S(n), o = await T(a, M, e).callStatic.eip712Domain();
249
+ return ee(o, r, n);
250
+ }
251
+ async function ee(n, r, e) {
252
+ const {
253
+ extensions: a,
254
+ ...t
255
+ } = n;
256
+ if (a.length > 0)
257
+ throw Error("Extensions not implemented");
258
+ if (t.chainId && r !== parseInt(t.chainId, 16))
259
+ throw Error(`ChainId mismatch. Received: '${t.chainId}', expected: '${r}'`);
260
+ if (t.verifyingContract && e.toLowerCase() !== t.verifyingContract.toLowerCase())
261
+ throw Error(`Address mismatch. Received: '${t.verifyingContract}', expected: '${e}'`);
262
+ return ne(t);
263
+ }
264
+ const te = ["name", "version", "chainId", "verifyingContract", "salt"];
265
+ function ne(n) {
266
+ const r = parseInt(n.fields, 16);
267
+ return te.reduce((e, a, t) => (r & 1 << t && (e[a] = n[a]), e), {});
268
+ }
269
+ async function re(n, r, e) {
270
+ const a = S(n);
271
+ return T(a, M, e).callStatic.name();
272
+ }
273
+ const ae = [[{
274
+ constant: !0,
275
+ inputs: [],
276
+ name: "version",
277
+ outputs: [{
278
+ name: "",
279
+ type: "string"
280
+ }],
281
+ payable: !1,
282
+ stateMutability: "view",
283
+ type: "function"
284
+ }], [{
285
+ constant: !0,
286
+ inputs: [],
287
+ name: "ERC712_VERSION",
288
+ outputs: [{
289
+ name: "",
290
+ type: "string"
291
+ }],
292
+ payable: !1,
293
+ stateMutability: "view",
294
+ type: "function"
295
+ }]];
296
+ async function U(n, r, e = 0) {
297
+ const a = ae[e];
298
+ if (!a)
299
+ return "1";
300
+ try {
301
+ const o = T(n, a, r).interface.encodeFunctionData(a[0].name), i = await r.call({
302
+ to: n,
303
+ data: o
304
+ });
305
+ return i === "0x" || Number.isNaN(Number(i)) ? "1" : i.startsWith("0x") ? w.decode(["string"], i).toString() : i;
306
+ } catch {
307
+ return U(n, r, e + 1);
308
+ }
309
+ }
310
+ const oe = {
311
+ nonce: 0,
312
+ deadline: E()
313
+ }, ie = {
314
+ allowed: !0,
315
+ nonce: 0,
316
+ expiry: E()
317
+ }, D = {}, g = {
318
+ type: "unsupported"
319
+ };
320
+ async function Ee(n) {
321
+ const {
322
+ tokenAddress: r,
323
+ chainId: e
324
+ } = n, a = V({
325
+ address: r,
326
+ chainId: e
327
+ }), t = D[a];
328
+ if (t)
329
+ return t;
330
+ const o = se(n);
331
+ return D[a] = o, o;
332
+ }
333
+ async function se(n) {
334
+ const {
335
+ spender: r,
336
+ tokenAddress: e,
337
+ chainId: a,
338
+ provider: t,
339
+ minGasLimit: o,
340
+ amount: i
341
+ } = n, d = await X(a, t), m = k.address;
342
+ let s;
343
+ try {
344
+ s = await Z(e, a, t);
345
+ } catch {
346
+ console.debug(`[checkTokenIsPermittable] Couldn't fetch eip712domain for token ${e}`);
347
+ }
348
+ let l = s?.name;
349
+ try {
350
+ l || (l = await re(e, a, t));
351
+ } catch (c) {
352
+ if (/ETIMEDOUT/.test(c) && !l)
353
+ return {
354
+ error: "Failed to fetch token name from contract. RPC connection error"
355
+ };
356
+ console.debug(`[checkTokenIsPermittable] Couldn't fetch token name from the contract for token ${e}, using provided '${l}'`, c);
357
+ }
358
+ if (!l)
359
+ return {
360
+ error: `Token name could not be determined for ${e}`
361
+ };
362
+ let u;
363
+ try {
364
+ u = await d.getTokenNonce(e, m);
365
+ } catch (c) {
366
+ return c === "nonce not supported" || c.message === "nonce is NaN" ? (console.debug(`[checkTokenIsPermittable] Not a permittable token ${e} - ${l}`, c?.message || c), {
367
+ ...g,
368
+ name: l
369
+ }) : (console.debug(`[checkTokenIsPermittable] Failed to get nonce for ${e} - ${l}`, c), {
370
+ error: c.message || c.toString()
371
+ });
372
+ }
373
+ let p = s?.version;
374
+ if (p === void 0)
375
+ try {
376
+ p = await U(e, t);
377
+ } catch (c) {
378
+ console.debug(`[checkTokenIsPermittable] Failed to get version for ${e} - ${l}`, c);
379
+ }
380
+ const y = {
381
+ chainId: a,
382
+ eip2612PermitUtils: d,
383
+ nonce: u,
384
+ spender: r,
385
+ tokenAddress: e,
386
+ tokenName: l,
387
+ walletAddress: m,
388
+ version: p,
389
+ minGasLimit: o,
390
+ amount: i
391
+ };
392
+ try {
393
+ return await A({
394
+ ...y,
395
+ type: "eip-2612",
396
+ provider: t
397
+ });
398
+ } catch (c) {
399
+ try {
400
+ return await le(e, d) ? await A({
401
+ ...y,
402
+ type: "dai-like",
403
+ provider: t
404
+ }) : /invalid signature/.test(c) || c?.code === "UNPREDICTABLE_GAS_LIMIT" ? (console.debug(`[checkTokenIsPermittable] Token ${e} - ${l} might be permittable, but it's not supported for now. Reason:`, c?.reason), {
405
+ ...g,
406
+ name: l
407
+ }) : (console.debug(`[checkTokenIsPermittable] Failed to estimate eip-2612 permit for ${e} - ${l}`, c), {
408
+ error: c.message || c.toString()
409
+ });
410
+ } catch (f) {
411
+ return console.debug(`[checkTokenIsPermittable] Failed to estimate dai-like permit for ${e} - ${l}`, f), {
412
+ error: f.message || f.toString()
413
+ };
414
+ }
415
+ }
416
+ }
417
+ async function A(n) {
418
+ const {
419
+ provider: r,
420
+ walletAddress: e,
421
+ tokenAddress: a,
422
+ tokenName: t,
423
+ type: o,
424
+ version: i,
425
+ minGasLimit: d = j
426
+ } = n, s = await (o === "eip-2612" ? ce : de)(n);
427
+ return s ? (await r.estimateGas({
428
+ data: s,
429
+ from: e,
430
+ to: a
431
+ })).toNumber() > d ? {
432
+ type: o,
433
+ version: i,
434
+ name: t
435
+ } : {
436
+ ...g,
437
+ name: t
438
+ } : {
439
+ ...g,
440
+ name: t
441
+ };
442
+ }
443
+ async function ce(n) {
444
+ const {
445
+ eip2612PermitUtils: r,
446
+ walletAddress: e,
447
+ spender: a,
448
+ nonce: t,
449
+ chainId: o,
450
+ tokenName: i,
451
+ tokenAddress: d,
452
+ version: m,
453
+ amount: s
454
+ } = n;
455
+ return R({
456
+ eip2612Utils: r,
457
+ callDataParams: [{
458
+ ...oe,
459
+ owner: e,
460
+ spender: a,
461
+ nonce: t,
462
+ value: s ? s.toString() : $.toString()
463
+ }, +o, i, d, m]
464
+ });
465
+ }
466
+ async function le(n, r) {
467
+ return await r.getPermitTypeHash(n) === C;
468
+ }
469
+ async function de(n) {
470
+ const {
471
+ eip2612PermitUtils: r,
472
+ tokenAddress: e,
473
+ walletAddress: a,
474
+ spender: t,
475
+ nonce: o,
476
+ chainId: i,
477
+ tokenName: d,
478
+ version: m
479
+ } = n;
480
+ return await r.getPermitTypeHash(e) === C ? N({
481
+ eip2612Utils: r,
482
+ callDataParams: [{
483
+ ...ie,
484
+ holder: a,
485
+ spender: t,
486
+ nonce: o
487
+ }, i, d, e, m]
488
+ }) : !1;
489
+ }
490
+ const me = [{
491
+ constant: !1,
492
+ inputs: [{
493
+ internalType: "address",
494
+ name: "holder",
495
+ type: "address"
496
+ }, {
497
+ internalType: "address",
498
+ name: "spender",
499
+ type: "address"
500
+ }, {
501
+ internalType: "uint256",
502
+ name: "nonce",
503
+ type: "uint256"
504
+ }, {
505
+ internalType: "uint256",
506
+ name: "expiry",
507
+ type: "uint256"
508
+ }, {
509
+ internalType: "bool",
510
+ name: "allowed",
511
+ type: "bool"
512
+ }, {
513
+ internalType: "uint8",
514
+ name: "v",
515
+ type: "uint8"
516
+ }, {
517
+ internalType: "bytes32",
518
+ name: "r",
519
+ type: "bytes32"
520
+ }, {
521
+ internalType: "bytes32",
522
+ name: "s",
523
+ type: "bytes32"
524
+ }],
525
+ name: "permit",
526
+ outputs: [],
527
+ payable: !1,
528
+ stateMutability: "nonpayable",
529
+ type: "function"
530
+ }], h = "0xd505accf", P = "0x8fcbaf0c", C = "0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb", Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
531
+ __proto__: null,
532
+ DAI_EIP_2612_PERMIT_ABI: me,
533
+ DAI_LIKE_PERMIT_TYPEHASH: C,
534
+ DAI_PERMIT_SELECTOR: P,
535
+ EIP_2612_PERMIT_SELECTOR: h
536
+ }, Symbol.toStringTag, { value: "Module" }));
537
+ export {
538
+ j as DEFAULT_MIN_GAS_LIMIT,
539
+ be as PERMIT_ACCOUNT,
540
+ k as PERMIT_SIGNER,
541
+ we as checkIsCallDataAValidPermit,
542
+ ke as generatePermitHook,
543
+ X as getPermitUtilsInstance,
544
+ Ee as getTokenPermitInfo,
545
+ W as isSupportedPermitInfo,
546
+ Ce as oneInchPermitUtilsConsts
547
+ };
@@ -0,0 +1,3 @@
1
+ import { PermitInfo } from '../types';
2
+ import { Eip2612PermitUtils } from '@1inch/permit-signed-approvals-utils';
3
+ export declare function checkIsCallDataAValidPermit(owner: string, chainId: number, eip2612Utils: Eip2612PermitUtils, tokenAddress: string, _tokenName: string | undefined, callData: string, { version, type, name }: PermitInfo): Promise<boolean | undefined>;
@@ -0,0 +1,2 @@
1
+ import { PermitHookData, PermitHookParams } from '../types';
2
+ export declare function generatePermitHook(params: PermitHookParams): Promise<PermitHookData | undefined>;
@@ -0,0 +1,3 @@
1
+ import { JsonRpcProvider } from '@ethersproject/providers';
2
+ import { Eip2612PermitUtils } from '@1inch/permit-signed-approvals-utils';
3
+ export declare function getPermitUtilsInstance(chainId: number, provider: JsonRpcProvider, account?: string | undefined): Promise<Eip2612PermitUtils>;