@orderly.network/hooks 1.5.2 → 1.5.3-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"signatureMiddleware.d.ts","sourceRoot":"","sources":["../../src/middleware/signatureMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,UAAU,EAAE,MAAM,KAAK,CAAC;AAI1C,eAAO,MAAM,mBAAmB,EAAE,UAiCjC,CAAC"}
1
+ {"version":3,"file":"signatureMiddleware.d.ts","sourceRoot":"","sources":["../../src/middleware/signatureMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,UAAU,EAAE,MAAM,KAAK,CAAC;AAK1C,eAAO,MAAM,mBAAmB,EAAE,UAiCjC,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { SimpleDI } from "@orderly.network/core";
2
2
  import { useConfig } from "../useConfig";
3
+ import { getTimestamp } from "@orderly.network/utils";
3
4
  export const signatureMiddleware = (useSWRNext)=>{
4
5
  const apiBaseUrl = useConfig("apiBaseUrl");
5
6
  return (key, fetcher, config)=>{
@@ -13,7 +14,7 @@ export const signatureMiddleware = (useSWRNext)=>{
13
14
  method: "GET",
14
15
  url
15
16
  };
16
- const signature = await signer.sign(payload);
17
+ const signature = await signer.sign(payload, getTimestamp());
17
18
  // @ts-ignore
18
19
  return fetcher(fullUrl, {
19
20
  headers: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/signatureMiddleware.ts"],"sourcesContent":["import { SWRHook, Middleware } from \"swr\";\nimport { SimpleDI, Account, MessageFactor } from \"@orderly.network/core\";\nimport { useConfig } from \"../useConfig\";\n\nexport const signatureMiddleware: Middleware = (useSWRNext: SWRHook) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n return (key, fetcher, config) => {\n try {\n const extendedFetcher = async (args: any) => {\n let url = Array.isArray(args) ? args[0] : args;\n\n let account = SimpleDI.get<Account>(\"account\");\n let fullUrl = `${apiBaseUrl}${url}`;\n\n const signer = account.signer;\n\n const payload: MessageFactor = {\n method: \"GET\",\n url,\n };\n\n const signature = await signer.sign(payload);\n\n // @ts-ignore\n return fetcher(fullUrl, {\n headers: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n });\n };\n return useSWRNext(key, extendedFetcher, config);\n } catch (e) {\n console.error(\"signature error:\", e);\n throw e;\n }\n };\n};\n"],"names":["SimpleDI","useConfig","signatureMiddleware","useSWRNext","apiBaseUrl","key","fetcher","config","extendedFetcher","args","url","Array","isArray","account","get","fullUrl","signer","payload","method","signature","sign","headers","accountId","e","console","error"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AACA,SAASA,QAAQ,QAAgC,wBAAwB;AACzE,SAASC,SAAS,QAAQ,eAAe;AAEzC,OAAO,MAAMC,sBAAkC,CAACC;IAC9C,MAAMC,aAAaH,UAAU;IAC7B,OAAO,CAACI,KAAKC,SAASC;QACpB,IAAI;YACF,MAAMC,kBAAkB,OAAOC;gBAC7B,IAAIC,MAAMC,MAAMC,OAAO,CAACH,QAAQA,IAAI,CAAC,EAAE,GAAGA;gBAE1C,IAAII,UAAUb,SAASc,GAAG,CAAU;gBACpC,IAAIC,UAAU,CAAC,EAAEX,WAAW,EAAEM,IAAI,CAAC;gBAEnC,MAAMM,SAASH,QAAQG,MAAM;gBAE7B,MAAMC,UAAyB;oBAC7BC,QAAQ;oBACRR;gBACF;gBAEA,MAAMS,YAAY,MAAMH,OAAOI,IAAI,CAACH;gBAEpC,aAAa;gBACb,OAAOX,QAAQS,SAAS;oBACtBM,SAAS;wBACP,GAAGF,SAAS;wBACZ,sBAAsBN,QAAQS,SAAS;oBACzC;gBACF;YACF;YACA,OAAOnB,WAAWE,KAAKG,iBAAiBD;QAC1C,EAAE,OAAOgB,GAAG;YACVC,QAAQC,KAAK,CAAC,oBAAoBF;YAClC,MAAMA;QACR;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/middleware/signatureMiddleware.ts"],"sourcesContent":["import { SWRHook, Middleware } from \"swr\";\nimport { SimpleDI, Account, MessageFactor } from \"@orderly.network/core\";\nimport { useConfig } from \"../useConfig\";\nimport { getTimestamp } from \"@orderly.network/utils\";\n\nexport const signatureMiddleware: Middleware = (useSWRNext: SWRHook) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n return (key, fetcher, config) => {\n try {\n const extendedFetcher = async (args: any) => {\n let url = Array.isArray(args) ? args[0] : args;\n\n let account = SimpleDI.get<Account>(\"account\");\n let fullUrl = `${apiBaseUrl}${url}`;\n\n const signer = account.signer;\n\n const payload: MessageFactor = {\n method: \"GET\",\n url,\n };\n\n const signature = await signer.sign(payload, getTimestamp());\n\n // @ts-ignore\n return fetcher(fullUrl, {\n headers: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n });\n };\n return useSWRNext(key, extendedFetcher, config);\n } catch (e) {\n console.error(\"signature error:\", e);\n throw e;\n }\n };\n};\n"],"names":["SimpleDI","useConfig","getTimestamp","signatureMiddleware","useSWRNext","apiBaseUrl","key","fetcher","config","extendedFetcher","args","url","Array","isArray","account","get","fullUrl","signer","payload","method","signature","sign","headers","accountId","e","console","error"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AACA,SAASA,QAAQ,QAAgC,wBAAwB;AACzE,SAASC,SAAS,QAAQ,eAAe;AACzC,SAASC,YAAY,QAAQ,yBAAyB;AAEtD,OAAO,MAAMC,sBAAkC,CAACC;IAC9C,MAAMC,aAAaJ,UAAU;IAC7B,OAAO,CAACK,KAAKC,SAASC;QACpB,IAAI;YACF,MAAMC,kBAAkB,OAAOC;gBAC7B,IAAIC,MAAMC,MAAMC,OAAO,CAACH,QAAQA,IAAI,CAAC,EAAE,GAAGA;gBAE1C,IAAII,UAAUd,SAASe,GAAG,CAAU;gBACpC,IAAIC,UAAU,CAAC,EAAEX,WAAW,EAAEM,IAAI,CAAC;gBAEnC,MAAMM,SAASH,QAAQG,MAAM;gBAE7B,MAAMC,UAAyB;oBAC7BC,QAAQ;oBACRR;gBACF;gBAEA,MAAMS,YAAY,MAAMH,OAAOI,IAAI,CAACH,SAAShB;gBAE7C,aAAa;gBACb,OAAOK,QAAQS,SAAS;oBACtBM,SAAS;wBACP,GAAGF,SAAS;wBACZ,sBAAsBN,QAAQS,SAAS;oBACzC;gBACF;YACF;YACA,OAAOnB,WAAWE,KAAKG,iBAAiBD;QAC1C,EAAE,OAAOgB,GAAG;YACVC,QAAQC,KAAK,CAAC,oBAAoBF;YAClC,MAAMA;QACR;IACF;AACF,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.d.ts","sourceRoot":"","sources":["../src/useMutation.ts"],"names":[],"mappings":"AAAA,OAAuB,EAErB,KAAK,wBAAwB,EAE9B,MAAM,cAAc,CAAC;AAStB,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAmC7C;;GAEG;AACH,eAAO,MAAM,WAAW,cAKjB,MAAM,WAIH,WAAW,4EA6BX,OAAO,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,WAIvB,OAAO,MAAM,EAAE,GAAG,CAAC,2DAE3B,QAAQ,GAAG,CAAC;;;;;EAsChB,CAAC"}
1
+ {"version":3,"file":"useMutation.d.ts","sourceRoot":"","sources":["../src/useMutation.ts"],"names":[],"mappings":"AAAA,OAAuB,EAErB,KAAK,wBAAwB,EAE9B,MAAM,cAAc,CAAC;AAUtB,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAmC7C;;GAEG;AACH,eAAO,MAAM,WAAW,cAKjB,MAAM,WAIH,WAAW,4EA6BX,OAAO,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,WAIvB,OAAO,MAAM,EAAE,GAAG,CAAC,2DAE3B,QAAQ,GAAG,CAAC;;;;;EAsChB,CAAC"}
@@ -2,6 +2,7 @@ import useSWRMutation from "swr/mutation";
2
2
  import { mutate } from "@orderly.network/net";
3
3
  import { useAccountInstance } from "./useAccountInstance";
4
4
  import { useConfig } from "./useConfig";
5
+ import { getTimestamp } from "@orderly.network/utils";
5
6
  const fetcher = (url, options)=>{
6
7
  const init = {
7
8
  method: options.arg.method,
@@ -55,7 +56,7 @@ const fetcher = (url, options)=>{
55
56
  url: newUrl,
56
57
  data
57
58
  };
58
- const signature = await signer.sign(payload);
59
+ const signature = await signer.sign(payload, getTimestamp());
59
60
  return trigger({
60
61
  data,
61
62
  params,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/useMutation.ts"],"sourcesContent":["import useSWRMutation, {\n TriggerWithOptionsArgs,\n type SWRMutationConfiguration,\n TriggerWithoutArgs,\n} from \"swr/mutation\";\nimport { mutate } from \"@orderly.network/net\";\nimport {\n type MessageFactor,\n type SignedMessagePayload,\n} from \"@orderly.network/core\";\nimport { useAccountInstance } from \"./useAccountInstance\";\nimport { useConfig } from \"./useConfig\";\n\ntype HTTP_METHOD = \"POST\" | \"PUT\" | \"DELETE\";\n\nconst fetcher = (\n url: string,\n options: {\n arg: {\n data?: any;\n params?: any;\n method: HTTP_METHOD;\n signature: SignedMessagePayload;\n };\n }\n) => {\n const init: RequestInit = {\n method: options.arg.method,\n headers: {\n ...options.arg.signature,\n },\n };\n\n if (options.arg.data) {\n init.body = JSON.stringify(options.arg.data);\n }\n\n if (\n typeof options.arg.params === \"object\" &&\n Object.keys(options.arg.params).length\n ) {\n let search = new URLSearchParams(options.arg.params);\n url = `${url}?${search.toString()}`;\n }\n\n return mutate(url, init);\n};\n\n/**\n * This hook is used to execute API requests for data mutation, such as POST, DELETE, PUT, etc.\n */\nexport const useMutation = <T, E>(\n /**\n * The URL to send the request to. If the URL does not start with \"http\",\n * it will be prefixed with the API base URL.\n */\n url: string,\n /**\n * The HTTP method to use for the request. Defaults to \"POST\".\n */\n method: HTTP_METHOD = \"POST\",\n /**\n * The configuration object for the mutation.\n * @see [useSWRMutation](https://swr.vercel.app/docs/mutation#api)\n *\n * @link https://swr.vercel.app/docs/mutation#api\n */\n options?: SWRMutationConfiguration<T, E>\n) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n\n let fullUrl = url;\n if (!url.startsWith(\"http\")) {\n fullUrl = `${apiBaseUrl}${url}`;\n }\n\n const account = useAccountInstance();\n const signer = account.signer;\n const { trigger, data, error, reset, isMutating } = useSWRMutation(\n fullUrl,\n // method === \"POST\" ? fetcher : deleteFetcher,\n fetcher,\n options\n );\n\n const mutation = async (\n /**\n * The data to send with the request.\n */\n data: Record<string, any> | null,\n /**\n * The query parameters to send with the request.\n */\n params?: Record<string, any>,\n options?: SWRMutationConfiguration<T, E>\n ): Promise<any> => {\n let newUrl = url;\n if (typeof params === \"object\" && Object.keys(params).length) {\n let search = new URLSearchParams(params);\n newUrl = `${url}?${search.toString()}`;\n }\n\n const payload: MessageFactor = {\n method,\n url: newUrl,\n data,\n };\n\n const signature = await signer.sign(payload);\n\n return trigger(\n {\n data,\n params,\n method,\n signature: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n },\n options\n );\n };\n\n return [\n mutation,\n {\n data,\n error,\n reset,\n isMutating,\n },\n ] as const;\n};\n"],"names":["useSWRMutation","mutate","useAccountInstance","useConfig","fetcher","url","options","init","method","arg","headers","signature","data","body","JSON","stringify","params","Object","keys","length","search","URLSearchParams","toString","useMutation","apiBaseUrl","fullUrl","startsWith","account","signer","trigger","error","reset","isMutating","mutation","newUrl","payload","sign","accountId"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,oBAIA,eAAe;AACtB,SAASC,MAAM,QAAQ,uBAAuB;AAK9C,SAASC,kBAAkB,QAAQ,uBAAuB;AAC1D,SAASC,SAAS,QAAQ,cAAc;AAIxC,MAAMC,UAAU,CACdC,KACAC;IASA,MAAMC,OAAoB;QACxBC,QAAQF,QAAQG,GA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;QAEA,MAAMa,UAAyB;YAC7B3B;YACAH,KAAK6B;YACLtB;QACF;QAEA,MAAMD,YAAY,MAAMiB,OAAOQ,IAAI,CAACD;QAEpC,OAAON,QACL;YACEjB;YACAI;YACAR;YACAG,WAAW;gBACT,GAAGA,SAAS;gBACZ,sBAAsBgB,QAAQU,SAAS;YACzC;QACF,GACA/B;IAEJ;IAEA,OAAO;QACL2B;QACA;YACErB;YACAkB;YACAC;YACAC;QACF;KACD;AACH,EAAE"}
1
+ {"version":3,"sources":["../src/useMutation.ts"],"sourcesContent":["import useSWRMutation, {\n TriggerWithOptionsArgs,\n type SWRMutationConfiguration,\n TriggerWithoutArgs,\n} from \"swr/mutation\";\nimport { mutate } from \"@orderly.network/net\";\nimport {\n type MessageFactor,\n type SignedMessagePayload,\n} from \"@orderly.network/core\";\nimport { useAccountInstance } from \"./useAccountInstance\";\nimport { useConfig } from \"./useConfig\";\nimport { getTimestamp } from \"@orderly.network/utils\";\n\ntype HTTP_METHOD = \"POST\" | \"PUT\" | \"DELETE\";\n\nconst fetcher = (\n url: string,\n options: {\n arg: {\n data?: any;\n params?: any;\n method: HTTP_METHOD;\n signature: SignedMessagePayload;\n };\n }\n) => {\n const init: RequestInit = {\n method: options.arg.method,\n headers: {\n ...options.arg.signature,\n },\n };\n\n if (options.arg.data) {\n init.body = JSON.stringify(options.arg.data);\n }\n\n if (\n typeof options.arg.params === \"object\" &&\n Object.keys(options.arg.params).length\n ) {\n let search = new URLSearchParams(options.arg.params);\n url = `${url}?${search.toString()}`;\n }\n\n return mutate(url, init);\n};\n\n/**\n * This hook is used to execute API requests for data mutation, such as POST, DELETE, PUT, etc.\n */\nexport const useMutation = <T, E>(\n /**\n * The URL to send the request to. If the URL does not start with \"http\",\n * it will be prefixed with the API base URL.\n */\n url: string,\n /**\n * The HTTP method to use for the request. Defaults to \"POST\".\n */\n method: HTTP_METHOD = \"POST\",\n /**\n * The configuration object for the mutation.\n * @see [useSWRMutation](https://swr.vercel.app/docs/mutation#api)\n *\n * @link https://swr.vercel.app/docs/mutation#api\n */\n options?: SWRMutationConfiguration<T, E>\n) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n\n let fullUrl = url;\n if (!url.startsWith(\"http\")) {\n fullUrl = `${apiBaseUrl}${url}`;\n }\n\n const account = useAccountInstance();\n const signer = account.signer;\n const { trigger, data, error, reset, isMutating } = useSWRMutation(\n fullUrl,\n // method === \"POST\" ? fetcher : deleteFetcher,\n fetcher,\n options\n );\n\n const mutation = async (\n /**\n * The data to send with the request.\n */\n data: Record<string, any> | null,\n /**\n * The query parameters to send with the request.\n */\n params?: Record<string, any>,\n options?: SWRMutationConfiguration<T, E>\n ): Promise<any> => {\n let newUrl = url;\n if (typeof params === \"object\" && Object.keys(params).length) {\n let search = new URLSearchParams(params);\n newUrl = `${url}?${search.toString()}`;\n }\n\n const payload: MessageFactor = {\n method,\n url: newUrl,\n data,\n };\n\n const signature = await signer.sign(payload, getTimestamp());\n\n return trigger(\n {\n data,\n params,\n method,\n signature: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n },\n options\n );\n };\n\n return [\n mutation,\n {\n data,\n error,\n reset,\n isMutating,\n },\n ] as const;\n};\n"],"names":["useSWRMutation","mutate","useAccountInstance","useConfig","getTimestamp","fetcher","url","options","init","method","arg","headers","signature","data","body","JSON","stringify","params","Object","keys","length","search","URLSearchParams","toString","useMutation","apiBaseUrl","fullUrl","startsWith","account","signer","trigger","error","reset","isMutating","mutation","newUrl","payload","sign","accountId"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,oBAIA,eAAe;AACtB,SAASC,MAAM,QAAQ,uBAAuB;AAK9C,SAASC,kBAAkB,QAAQ,uBAAuB;AAC1D,SAASC,SAAS,QAAQ,cAAc;AACxC,SAASC,YAAY,QAAQ,yBAAyB;AAItD,MAAMC,UAAU,CACd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,IAAI,CAAC,EAAEe,OAAOE,QAAQ,GAAG,CAAC;QACxC;QAEA,MAAMa,UAAyB;YAC7B3B;YACAH,KAAK6B;YACLtB;QACF;QAEA,MAAMD,YAAY,MAAMiB,OAAOQ,IAAI,CAACD,SAAShC;QAE7C,OAAO0B,QACL;YACEjB;YACAI;YACAR;YACAG,WAAW;gBACT,GAAGA,SAAS;gBACZ,sBAAsBgB,QAAQU,SAAS;YACzC;QACF,GACA/B;IAEJ;IAEA,OAAO;QACL2B;QACA;YACErB;YACAkB;YACAC;YACAC;QACF;KACD;AACH,EAAE"}
@@ -4,12 +4,13 @@ import { type DrawOptions } from "./services/painter/basePaint";
4
4
  * @example
5
5
  * ```tsx
6
6
  * const { ref, toDataURL, toBlob, download, copy } = usePoster({
7
- * backgroundColor: "#0b8c70",
8
- * backgroundImg: "/images/poster_bg.png",
9
- * color: "rgba(255, 255, 255, 0.98)",
10
- * profitColor: "rgb(0,181,159)",
11
- * ...
7
+ * backgroundColor: "#0b8c70",
8
+ * backgroundImg: "/images/poster_bg.png",
9
+ * color: "rgba(255, 255, 255, 0.98)",
10
+ * profitColor: "rgb(0,181,159)",
11
+ * // ...
12
12
  * });
13
+ * ```
13
14
  */
14
15
  export declare const usePoster: (data: DrawOptions, options?: {
15
16
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"usePoster.d.ts","sourceRoot":"","sources":["../src/usePoster.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIhE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,SAAS,SAId,WAAW,YACP;IACR;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;IAiHC;;OAEG;wBAnDa,iBAAiB,GAAG,IAAI;IAqDxC;;OAEG;gCA9EqB,MAAM,mBAAmB,MAAM;IAgFvD;;OAEG;6BAvEK,MAAM,mBAAmB,MAAM,KAAG,QAAQ,IAAI,GAAG,IAAI,CAAC;IAyE9D;;OAEG;kCApDQ,MAAM,SAAQ,MAAM,mBAAiC,MAAM;IAsDtE;;OAEG;;;CAIN,CAAC"}
1
+ {"version":3,"file":"usePoster.d.ts","sourceRoot":"","sources":["../src/usePoster.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIhE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,SAId,WAAW,YACP;IACR;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;IAiHC;;OAEG;wBAnDa,iBAAiB,GAAG,IAAI;IAqDxC;;OAEG;gCA9EqB,MAAM,mBAAmB,MAAM;IAgFvD;;OAEG;6BAvEK,MAAM,mBAAmB,MAAM,KAAG,QAAQ,IAAI,GAAG,IAAI,CAAC;IAyE9D;;OAEG;kCApDQ,MAAM,SAAQ,MAAM,mBAAiC,MAAM;IAsDtE;;OAEG;;;CAIN,CAAC"}
package/esm/usePoster.js CHANGED
@@ -8,12 +8,13 @@ import { SDKError } from "@orderly.network/types";
8
8
  * @example
9
9
  * ```tsx
10
10
  * const { ref, toDataURL, toBlob, download, copy } = usePoster({
11
- * backgroundColor: "#0b8c70",
12
- * backgroundImg: "/images/poster_bg.png",
13
- * color: "rgba(255, 255, 255, 0.98)",
14
- * profitColor: "rgb(0,181,159)",
15
- * ...
11
+ * backgroundColor: "#0b8c70",
12
+ * backgroundImg: "/images/poster_bg.png",
13
+ * color: "rgba(255, 255, 255, 0.98)",
14
+ * profitColor: "rgb(0,181,159)",
15
+ * // ...
16
16
  * });
17
+ * ```
17
18
  */ export const usePoster = (/**
18
19
  * The options to draw the poster
19
20
  */ data, options)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/usePoster.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { mergeDeepRight } from \"ramda\";\nimport { PosterPainter } from \"./services/painter/painter\";\nimport { type DrawOptions } from \"./services/painter/basePaint\";\nimport { DefaultLayoutConfig } from \"./services/painter/layout.config\";\nimport { SDKError } from \"@orderly.network/types\";\n\n/**\n * Generates a poster image based on position information. You can set the size, background color, font color, font size, and content position of the poster.\n * @example\n * ```tsx\n * const { ref, toDataURL, toBlob, download, copy } = usePoster({\n * backgroundColor: \"#0b8c70\",\n * backgroundImg: \"/images/poster_bg.png\",\n * color: \"rgba(255, 255, 255, 0.98)\",\n * profitColor: \"rgb(0,181,159)\",\n * ...\n * });\n */\nexport const usePoster = (\n /**\n * The options to draw the poster\n */\n data: DrawOptions,\n options?: {\n /**\n * The ratio of the poster\n */\n ratio?: number;\n }\n) => {\n const [error, setError] = useState<Error | null>(null);\n const [canCopy, setCanCopy] = useState<boolean>(\n () => typeof navigator.clipboard !== \"undefined\"\n );\n\n const painterRef = useRef<PosterPainter | null>(null);\n\n const [target, setTarget] = useState<HTMLCanvasElement | null>(null);\n\n useEffect(() => {\n // Create the painter instance\n if (target) {\n if (!painterRef.current) {\n painterRef.current = new PosterPainter(target, {\n ratio: options?.ratio || 1,\n ...options,\n });\n }\n\n painterRef.current.draw(\n mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n data\n )\n );\n }\n }, [target, data]);\n\n // useEffect(() => {\n // if (painterRef.current) {\n // painterRef.current.draw(\n // mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n // { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n // data\n // )\n // );\n // }\n // }, [data]);\n\n const toDataURL = (type?: string, encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n return target.toDataURL(type, encoderOptions);\n };\n\n /**\n * Converts the poster to a blob\n */\n const toBlob = useCallback(\n (type?: string, encoderOptions?: number): Promise<Blob | null> => {\n return new Promise<Blob | null>((resolve) => {\n if (!target) {\n resolve(null);\n return;\n }\n target.toBlob(resolve, type, encoderOptions);\n });\n },\n [target]\n );\n\n const ref = (ref: HTMLCanvasElement | null) => {\n if (!ref) return;\n if (ref.tagName.toUpperCase() !== \"CANVAS\") {\n // throw new Error(\"The ref must be a canvas element\");\n setError(new SDKError(\"The ref must be a canvas element\"));\n return;\n }\n setTarget(ref);\n };\n\n const download = useCallback(\n (filename: string, type: string = \"image/png\", encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n const img = new Image();\n img.src = target.toDataURL(type, encoderOptions);\n const link = document.createElement(\"a\");\n link.href = img.src;\n link.download = filename;\n link.click();\n },\n [target]\n );\n\n const copy = useCallback(() => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n // copy image to clipboard\n return new Promise<void>((resolve, reject) => {\n if (!navigator.clipboard) {\n reject(new SDKError(\"Clipboard API is not supported\"));\n return;\n }\n target.toBlob((blob) => {\n if (!blob) {\n reject(new SDKError(\"Failed to create blob\"));\n return;\n }\n return navigator.clipboard\n .write([new ClipboardItem({ [blob.type]: blob })])\n .then(resolve, reject);\n });\n });\n }, [target]);\n\n return {\n error,\n /**\n * The ref to the canvas element, you should pass this ref to the canvas element\n */\n ref,\n /**\n * Converts the poster to a data URL\n */\n toDataURL,\n /**\n * Converts the poster to a blob\n */\n toBlob,\n /**\n * Downloads the poster as an image\n */\n download,\n /**\n * Browser if supports copy image to clipboard\n */\n canCopy,\n copy,\n } as const;\n};\n"],"names":["useCallback","useEffect","useRef","useState","mergeDeepRight","PosterPainter","DefaultLayoutConfig","SDKError","usePoster","data","options","error","setError","canCopy","setCanCopy","navigator","clipboard","painterRef","target","setTarget","current","ratio","draw","layout","fontFamily","toDataURL","type","encoderOptions","toBlob","Promise","resolve","ref","tagName","toUpperCase","download","filename","img","Image","src","link","document","createElement","href","click","copy","reject","blob","write","ClipboardItem","then"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACA+B;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../src/usePoster.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { mergeDeepRight } from \"ramda\";\nimport { PosterPainter } from \"./services/painter/painter\";\nimport { type DrawOptions } from \"./services/painter/basePaint\";\nimport { DefaultLayoutConfig } from \"./services/painter/layout.config\";\nimport { SDKError } from \"@orderly.network/types\";\n\n/**\n * Generates a poster image based on position information. You can set the size, background color, font color, font size, and content position of the poster.\n * @example\n * ```tsx\n * const { ref, toDataURL, toBlob, download, copy } = usePoster({\n * backgroundColor: \"#0b8c70\",\n * backgroundImg: \"/images/poster_bg.png\",\n * color: \"rgba(255, 255, 255, 0.98)\",\n * profitColor: \"rgb(0,181,159)\",\n * // ...\n * });\n * ```\n */\nexport const usePoster = (\n /**\n * The options to draw the poster\n */\n data: DrawOptions,\n options?: {\n /**\n * The ratio of the poster\n */\n ratio?: number;\n }\n) => {\n const [error, setError] = useState<Error | null>(null);\n const [canCopy, setCanCopy] = useState<boolean>(\n () => typeof navigator.clipboard !== \"undefined\"\n );\n\n const painterRef = useRef<PosterPainter | null>(null);\n\n const [target, setTarget] = useState<HTMLCanvasElement | null>(null);\n\n useEffect(() => {\n // Create the painter instance\n if (target) {\n if (!painterRef.current) {\n painterRef.current = new PosterPainter(target, {\n ratio: options?.ratio || 1,\n ...options,\n });\n }\n\n painterRef.current.draw(\n mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n data\n )\n );\n }\n }, [target, data]);\n\n // useEffect(() => {\n // if (painterRef.current) {\n // painterRef.current.draw(\n // mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n // { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n // data\n // )\n // );\n // }\n // }, [data]);\n\n const toDataURL = (type?: string, encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n return target.toDataURL(type, encoderOptions);\n };\n\n /**\n * Converts the poster to a blob\n */\n const toBlob = useCallback(\n (type?: string, encoderOptions?: number): Promise<Blob | null> => {\n return new Promise<Blob | null>((resolve) => {\n if (!target) {\n resolve(null);\n return;\n }\n target.toBlob(resolve, type, encoderOptions);\n });\n },\n [target]\n );\n\n const ref = (ref: HTMLCanvasElement | null) => {\n if (!ref) return;\n if (ref.tagName.toUpperCase() !== \"CANVAS\") {\n // throw new Error(\"The ref must be a canvas element\");\n setError(new SDKError(\"The ref must be a canvas element\"));\n return;\n }\n setTarget(ref);\n };\n\n const download = useCallback(\n (filename: string, type: string = \"image/png\", encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n const img = new Image();\n img.src = target.toDataURL(type, encoderOptions);\n const link = document.createElement(\"a\");\n link.href = img.src;\n link.download = filename;\n link.click();\n },\n [target]\n );\n\n const copy = useCallback(() => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n // copy image to clipboard\n return new Promise<void>((resolve, reject) => {\n if (!navigator.clipboard) {\n reject(new SDKError(\"Clipboard API is not supported\"));\n return;\n }\n target.toBlob((blob) => {\n if (!blob) {\n reject(new SDKError(\"Failed to create blob\"));\n return;\n }\n return navigator.clipboard\n .write([new ClipboardItem({ [blob.type]: blob })])\n .then(resolve, reject);\n });\n });\n }, [target]);\n\n return {\n error,\n /**\n * The ref to the canvas element, you should pass this ref to the canvas element\n */\n ref,\n /**\n * Converts the poster to a data URL\n */\n toDataURL,\n /**\n * Converts the poster to a blob\n */\n toBlob,\n /**\n * Downloads the poster as an image\n */\n download,\n /**\n * Browser if supports copy image to clipboard\n */\n canCopy,\n copy,\n } as const;\n};\n"],"names":["useCallback","useEffect","useRef","useState","mergeDeepRight","PosterPainter","DefaultLayoutConfig","SDKError","usePoster","data","options","error","setError","canCopy","setCanCopy","navigator","clipboard","painterRef","target","setTarget","current","ratio","draw","layout","fontFamily","toDataURL","type","encoderOptions","toBlob","Promise","resolve","ref","tagName","toUpperCase","download","filename","img","Image","src","link","document","createElement","href","click","copy","reject","blob","write","ClipboardItem","then"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AACjE,SAASC,cAAc,QAAQ,QAAQ;AACvC,SAASC,aAAa,QAAQ,6BAA6B;AAE3D,SAASC,mBAAmB,QAAQ,mCAAmC;AACvE,SAASC,QAAQ,QAAQ,yBAAyB;AAElD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,YAAY,CACvB;;GAEC,GACDC,MACAC;IAOA,MAAM,CAACC,OAAOC,SAAS,GAAGT,SAAuB;IACjD,MAAM,CAACU,SAASC,WAAW,GAAGX,SAC5B,IAAM,OAAOY,UAAUC,SAAS,KAAK;IAGvC,MAAMC,aAAaf,OAA6B;IAEhD,MAAM,CAACgB,QAAQC,UAAU,GAAGhB,SAAmC;IAE/DF,UAAU;QACR,8BAA8B;QAC9B,IAAIiB,QAAQ;YACV,IAAI,CAACD,WAAWG,OAAO,EAAE;gBACvBH,WAAWG,OAAO,GAAG,IAAIf,cAAca,QAAQ;oBAC7CG,OAAOX,SAASW,SAAS;oBACzB,GAAGX,OAAO;gBACZ;YACF;YAEAO,WAAWG,OAAO,CAACE,IAAI,CACrBlB,eACE;gBAAEmB,QAAQjB;gBAAqBkB,YAAY;YAAU,GACrDf;QAGN;IACF,GAAG;QAACS;QAAQT;KAAK;IAEjB,oBAAoB;IACpB,8BAA8B;IAC9B,+BAA+B;IAC/B,2DAA2D;IAC3D,kEAAkE;IAClE,eAAe;IACf,UAAU;IACV,SAAS;IACT,MAAM;IACN,cAAc;IAEd,MAAMgB,YAAY,CAACC,MAAeC;QAChC,I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AI,CAAC,EAAEoB;oBAAK;iBAAG,EAChDG,IAAI,CAACnB,SAASe;YACnB;QACF;IACF,GAAG;QAAC3B;KAAO;IAEX,OAAO;QACLP;QACA;;KAEC,GACDoB;QACA;;KAEC,GACDN;QACA;;KAEC,GACDG;QACA;;KAEC,GACDM;QACA;;KAEC,GACDrB;QACA+B;IACF;AACF,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"usePreloadData.d.ts","sourceRoot":"","sources":["../src/usePreloadData.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,cAAc;;;CAgB1B,CAAC"}
1
+ {"version":3,"file":"usePreloadData.d.ts","sourceRoot":"","sources":["../src/usePreloadData.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,cAAc;;;CAoD1B,CAAC"}
@@ -1,9 +1,29 @@
1
1
  import { useMemo } from "react";
2
- import { useQuery } from ".";
2
+ import { useConfig, useQuery, useSWR } from ".";
3
+ import { getGlobalObject } from "@orderly.network/utils";
3
4
  export const usePreLoadData = ()=>{
4
5
  const { error: tokenError, data: tokenData } = useQuery("https://api-evm.orderly.org/v1/public/token", {
5
6
  revalidateOnFocus: false
6
7
  });
8
+ /// get service timestamp
9
+ /// get local timestamp
10
+ /// calculate delta offset = SD - LD
11
+ /// save to getGlobalObject.__ORDERLY_timestamp_offset
12
+ const apiBaseUrl = useConfig("apiBaseUrl");
13
+ const { data: systemInfo } = useSWR("/v1/public/system_info", async (url, init)=>{
14
+ const data = await fetch(url.startsWith("http") ? url : `${apiBaseUrl}${url}`, init);
15
+ return await data.json();
16
+ }, {
17
+ errorRetryCount: 3,
18
+ errorRetryInterval: 500
19
+ });
20
+ if (typeof systemInfo !== "undefined") {
21
+ const sd = systemInfo.timestamp;
22
+ const ld = Date.now();
23
+ // @ts-ignore
24
+ getGlobalObject().__ORDERLY_timestamp_offset = sd - ld;
25
+ }
26
+ ;
7
27
  const isDone = useMemo(()=>{
8
28
  return !!tokenData;
9
29
  }, [
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/usePreloadData.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useQuery } from \".\";\n\nexport const usePreLoadData = () => {\n const { error: tokenError, data: tokenData } = useQuery(\n \"https://api-evm.orderly.org/v1/public/token\",\n {\n revalidateOnFocus: false,\n }\n );\n\n const isDone = useMemo(() => {\n return !!tokenData;\n }, [tokenData]);\n\n return {\n error: tokenError,\n done: isDone,\n };\n};\n"],"names":["useMemo","useQuery","usePreLoadData","error","tokenError","data","tokenData","revalidateOnFocus","isDone","done"],"rangeMappings":";;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,OAAO,QAAQ,QAAQ;AAChC,SAASC,QAAQ,QAAQ,IAAI;AAE7B,OAAO,MAAMC,iBAAiB;IAC5B,MAAM,EAAEC,OAAOC,UAAU,EAAEC,MAAMC,SAAS,EAAE,GAAGL,SAC7C,+CACA;QACEM,mBAAmB;IACrB;IAGF,MAAMC,SAASR,QAAQ;QACrB,OAAO,CAAC,CAACM;IACX,GAAG;QAACA;KAAU;IAEd,OAAO;QACLH,OAAOC;QACPK,MAAMD;IACR;AACF,EAAE"}
1
+ {"version":3,"sources":["../src/usePreloadData.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useConfig, useQuery, useSWR } from \".\";\nimport { request } from \"@orderly.network/net/src/fetch\";\nimport { getGlobalObject } from \"@orderly.network/utils\";\n\nexport const usePreLoadData = () => {\n const { error: tokenError, data: tokenData } = useQuery(\n \"https://api-evm.orderly.org/v1/public/token\",\n {\n revalidateOnFocus: false,\n }\n );\n\n /// get service timestamp\n /// get local timestamp\n /// calculate delta offset = SD - LD\n /// save to getGlobalObject.__ORDERLY_timestamp_offset\n\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n\n const { data: systemInfo } = useSWR(\n \"/v1/public/system_info\",\n async (url: any, init: any) => {\n const data = await fetch(\n url.startsWith(\"http\") ? url : `${apiBaseUrl}${url}`,\n init\n );\n return await data.json();\n },\n {\n errorRetryCount: 3,\n errorRetryInterval: 500,\n }\n );\n\n if (typeof systemInfo !== \"undefined\") {\n const sd = systemInfo.timestamp;\n const ld = Date.now();\n // @ts-ignore\n getGlobalObject().__ORDERLY_timestamp_offset = sd - ld;\n }\n\n // @ts-ignore\n console.log(\n \"systemInfo\",\n systemInfo,\n getGlobalObject().__ORDERLY_timestamp_offset\n );\n\n const isDone = useMemo(() => {\n return !!tokenData;\n }, [tokenData]);\n\n return {\n error: tokenError,\n done: isDone,\n };\n};\n"],"names":["useMemo","useConfig","useQuery","useSWR","getGlobalObject","usePreLoadData","error","tokenError","data","tokenData","revalidateOnFocus","apiBaseUrl","systemInfo","url","init","fetch","startsWith","json","errorRetryCount","errorRetryInterval","sd","timestamp","ld","Date","now","__ORDERLY_timestamp_offset","isDone","done"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,OAAO,QAAQ,QAAQ;AAChC,SAASC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,QAAQ,IAAI;AAEhD,SAASC,eAAe,QAAQ,yBAAyB;AAEzD,OAAO,MAAMC,iBAAiB;IAC5B,MAAM,EAAEC,OAAOC,UAAU,EAAEC,MAAMC,SAAS,EAAE,GAAGP,SAC7C,+CACA;QACEQ,mBAAmB;IACrB;IAGF,yBAAyB;IACzB,uBAAuB;IACvB,oCAAoC;IACpC,sDAAsD;IAEtD,MAAMC,aAAaV,UAAU;IAE7B,MAAM,EAAEO,MAAMI,UAAU,EAAE,GAAGT,OAC3B,0BACA,OAAOU,KAAUC;QACf,MAAMN,OAAO,MAAMO,MACjBF,IAAIG,UAAU,CAAC,UAAUH,MAAM,CAAC,EAAEF,WAAW,EAAEE,IAAI,CAAC,EACpDC;QAEF,OAAO,MAAMN,KAAKS,IAAI;IACxB,GACA;QACEC,iBAAiB;QACjBC,oBAAoB;IACtB;IAGF,IAAI,OAAOP,eAAe,aAAa;QACrC,MAAMQ,KAAKR,WAAWS,SAAS;QAC/B,MAAMC,KAAKC,KAAKC,GAAG;QACnB,aAAa;QACbpB,kBAAkBqB,0BAA0B,GAAGL,KAAKE;IACtD;;IASA,MAAMI,SAAS1B,QAAQ;QACrB,OAAO,CAAC,CAACS;IACX,GAAG;QAACA;KAAU;IAEd,OAAO;QACLH,OAAOC;QACPoB,MAAMD;IACR;AACF,EAAE"}
package/esm/version.d.ts CHANGED
@@ -5,6 +5,6 @@ declare global {
5
5
  };
6
6
  }
7
7
  }
8
- declare const _default: "1.5.2";
8
+ declare const _default: "1.5.3-alpha.0";
9
9
  export default _default;
10
10
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,CAAC;IACX,UAAU,MAAM;QACZ,mBAAmB,CAAC,EAAE;YAClB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;SACzB,CAAC;KACL;CACJ;;AAMD,wBAAuB"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,CAAC;IACX,UAAU,MAAM;QACZ,mBAAmB,CAAC,EAAE;YAClB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;SACzB,CAAC;KACL;CACJ;;AAMD,wBAA+B"}
package/esm/version.js CHANGED
@@ -1,7 +1,7 @@
1
1
  if (typeof window !== 'undefined') {
2
2
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
3
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "1.5.2";
3
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "1.5.3-alpha.0";
4
4
  }
5
- export default "1.5.2";
5
+ export default "1.5.3-alpha.0";
6
6
 
7
7
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["\ndeclare global {\n interface Window {\n __ORDERLY_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif(typeof window !== 'undefined') {\n window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};\n window.__ORDERLY_VERSION__[\"@orderly.network/hooks\"] = \"1.5.2\";\n};\n\nexport default \"1.5.2\";\n"],"names":["window","__ORDERLY_VERSION__"],"rangeMappings":";;;;","mappings":"AAQA,IAAG,OAAOA,WAAW,aAAa;IAC9BA,OAAOC,mBAAmB,GAAGD,OAAOC,mBAAmB,IAAI,CAAC;IAC5DD,OAAOC,mBAAmB,CAAC,yBAAyB,GAAG;AAC3D;AAEA,eAAe,QAAQ"}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["\ndeclare global {\n interface Window {\n __ORDERLY_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif(typeof window !== 'undefined') {\n window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};\n window.__ORDERLY_VERSION__[\"@orderly.network/hooks\"] = \"1.5.3-alpha.0\";\n};\n\nexport default \"1.5.3-alpha.0\";\n"],"names":["window","__ORDERLY_VERSION__"],"rangeMappings":";;;;","mappings":"AAQA,IAAG,OAAOA,WAAW,aAAa;IAC9BA,OAAOC,mBAAmB,GAAGD,OAAOC,mBAAmB,IAAI,CAAC;IAC5DD,OAAOC,mBAAmB,CAAC,yBAAyB,GAAG;AAC3D;AAEA,eAAe,gBAAgB"}
@@ -1 +1 @@
1
- {"version":3,"file":"signatureMiddleware.d.ts","sourceRoot":"","sources":["../../src/middleware/signatureMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,UAAU,EAAE,MAAM,KAAK,CAAC;AAI1C,eAAO,MAAM,mBAAmB,EAAE,UAiCjC,CAAC"}
1
+ {"version":3,"file":"signatureMiddleware.d.ts","sourceRoot":"","sources":["../../src/middleware/signatureMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,UAAU,EAAE,MAAM,KAAK,CAAC;AAK1C,eAAO,MAAM,mBAAmB,EAAE,UAiCjC,CAAC"}
@@ -10,6 +10,7 @@ Object.defineProperty(exports, "signatureMiddleware", {
10
10
  });
11
11
  const _core = require("@orderly.network/core");
12
12
  const _useConfig = require("../useConfig");
13
+ const _utils = require("@orderly.network/utils");
13
14
  const signatureMiddleware = (useSWRNext)=>{
14
15
  const apiBaseUrl = (0, _useConfig.useConfig)("apiBaseUrl");
15
16
  return (key, fetcher, config)=>{
@@ -23,7 +24,7 @@ const signatureMiddleware = (useSWRNext)=>{
23
24
  method: "GET",
24
25
  url
25
26
  };
26
- const signature = await signer.sign(payload);
27
+ const signature = await signer.sign(payload, (0, _utils.getTimestamp)());
27
28
  // @ts-ignore
28
29
  return fetcher(fullUrl, {
29
30
  headers: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/signatureMiddleware.ts"],"sourcesContent":["import { SWRHook, Middleware } from \"swr\";\nimport { SimpleDI, Account, MessageFactor } from \"@orderly.network/core\";\nimport { useConfig } from \"../useConfig\";\n\nexport const signatureMiddleware: Middleware = (useSWRNext: SWRHook) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n return (key, fetcher, config) => {\n try {\n const extendedFetcher = async (args: any) => {\n let url = Array.isArray(args) ? args[0] : args;\n\n let account = SimpleDI.get<Account>(\"account\");\n let fullUrl = `${apiBaseUrl}${url}`;\n\n const signer = account.signer;\n\n const payload: MessageFactor = {\n method: \"GET\",\n url,\n };\n\n const signature = await signer.sign(payload);\n\n // @ts-ignore\n return fetcher(fullUrl, {\n headers: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n });\n };\n return useSWRNext(key, extendedFetcher, config);\n } catch (e) {\n console.error(\"signature error:\", e);\n throw e;\n }\n };\n};\n"],"names":["signatureMiddleware","useSWRNext","apiBaseUrl","useConfig","key","fetcher","config","extendedFetcher","args","url","Array","isArray","account","SimpleDI","get","fullUrl","signer","payload","method","signature","sign","headers","accountId","e","console","error"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAIaA;;;eAAAA;;;sBAHoC;2BACvB;AAEnB,MAAMA,sBAAkC,CAACC;IAC9C,MAAMC,aAAaC,IAAAA,oBAAS,EAAC;IAC7B,OAAO,CAACC,KAAKC,SAASC;QACpB,IAAI;YACF,MAAMC,kBAAkB,OAAOC;gBAC7B,IAAIC,MAAMC,MAAMC,OAAO,CAACH,QAAQA,IAAI,CAAC,EAAE,GAAGA;gBAE1C,IAAII,UAAUC,cAAQ,CAACC,GAAG,CAAU;gBACpC,IAAIC,UAAU,CAAC,EAAEb,WAAW,EAAEO,IAAI,CAAC;gBAEnC,MAAMO,SAASJ,QAAQI,MAAM;gBAE7B,MAAMC,UAAyB;oBAC7BC,QAAQ;oBACRT;gBACF;gBAEA,MAAMU,YAAY,MAAMH,OAAOI,IAAI,CAACH;gBAEpC,aAAa;gBACb,OAAOZ,QAAQU,SAAS;oBACtBM,SAAS;wBACP,GAAGF,SAAS;wBACZ,sBAAsBP,QAAQU,SAAS;oBACzC;gBACF;YACF;YACA,OAAOrB,WAAWG,KAAKG,iBAAiBD;QAC1C,EAAE,OAAOiB,GAAG;YACVC,QAAQC,KAAK,CAAC,oBAAoBF;YAClC,MAAMA;QACR;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/middleware/signatureMiddleware.ts"],"sourcesContent":["import { SWRHook, Middleware } from \"swr\";\nimport { SimpleDI, Account, MessageFactor } from \"@orderly.network/core\";\nimport { useConfig } from \"../useConfig\";\nimport { getTimestamp } from \"@orderly.network/utils\";\n\nexport const signatureMiddleware: Middleware = (useSWRNext: SWRHook) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n return (key, fetcher, config) => {\n try {\n const extendedFetcher = async (args: any) => {\n let url = Array.isArray(args) ? args[0] : args;\n\n let account = SimpleDI.get<Account>(\"account\");\n let fullUrl = `${apiBaseUrl}${url}`;\n\n const signer = account.signer;\n\n const payload: MessageFactor = {\n method: \"GET\",\n url,\n };\n\n const signature = await signer.sign(payload, getTimestamp());\n\n // @ts-ignore\n return fetcher(fullUrl, {\n headers: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n });\n };\n return useSWRNext(key, extendedFetcher, config);\n } catch (e) {\n console.error(\"signature error:\", e);\n throw e;\n }\n };\n};\n"],"names":["signatureMiddleware","useSWRNext","apiBaseUrl","useConfig","key","fetcher","config","extendedFetcher","args","url","Array","isArray","account","SimpleDI","get","fullUrl","signer","payload","method","signature","sign","getTimestamp","headers","accountId","e","console","error"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAKaA;;;eAAAA;;;sBAJoC;2BACvB;uBACG;AAEtB,MAAMA,sBAAkC,CAACC;IAC9C,MAAMC,aAAaC,IAAAA,oBAAS,EAAC;IAC7B,OAAO,CAACC,KAAKC,SAASC;QACpB,IAAI;YACF,MAAMC,kBAAkB,OAAOC;gBAC7B,IAAIC,MAAMC,MAAMC,OAAO,CAACH,QAAQA,IAAI,CAAC,EAAE,GAAGA;gBAE1C,IAAII,UAAUC,cAAQ,CAACC,GAAG,CAAU;gBACpC,IAAIC,UAAU,CAAC,EAAEb,WAAW,EAAEO,IAAI,CAAC;gBAEnC,MAAMO,SAASJ,QAAQI,MAAM;gBAE7B,MAAMC,UAAyB;oBAC7BC,QAAQ;oBACRT;gBACF;gBAEA,MAAMU,YAAY,MAAMH,OAAOI,IAAI,CAACH,SAASI,IAAAA,mBAAY;gBAEzD,aAAa;gBACb,OAAOhB,QAAQU,SAAS;oBACtBO,SAAS;wBACP,GAAGH,SAAS;wBACZ,sBAAsBP,QAAQW,SAAS;oBACzC;gBACF;YACF;YACA,OAAOtB,WAAWG,KAAKG,iBAAiBD;QAC1C,EAAE,OAAOkB,GAAG;YACVC,QAAQC,KAAK,CAAC,oBAAoBF;YAClC,MAAMA;QACR;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"useMutation.d.ts","sourceRoot":"","sources":["../src/useMutation.ts"],"names":[],"mappings":"AAAA,OAAuB,EAErB,KAAK,wBAAwB,EAE9B,MAAM,cAAc,CAAC;AAStB,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAmC7C;;GAEG;AACH,eAAO,MAAM,WAAW,cAKjB,MAAM,WAIH,WAAW,4EA6BX,OAAO,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,WAIvB,OAAO,MAAM,EAAE,GAAG,CAAC,2DAE3B,QAAQ,GAAG,CAAC;;;;;EAsChB,CAAC"}
1
+ {"version":3,"file":"useMutation.d.ts","sourceRoot":"","sources":["../src/useMutation.ts"],"names":[],"mappings":"AAAA,OAAuB,EAErB,KAAK,wBAAwB,EAE9B,MAAM,cAAc,CAAC;AAUtB,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAmC7C;;GAEG;AACH,eAAO,MAAM,WAAW,cAKjB,MAAM,WAIH,WAAW,4EA6BX,OAAO,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,WAIvB,OAAO,MAAM,EAAE,GAAG,CAAC,2DAE3B,QAAQ,GAAG,CAAC;;;;;EAsChB,CAAC"}
@@ -12,6 +12,7 @@ const _mutation = /*#__PURE__*/ _interop_require_default(require("swr/mutation")
12
12
  const _net = require("@orderly.network/net");
13
13
  const _useAccountInstance = require("./useAccountInstance");
14
14
  const _useConfig = require("./useConfig");
15
+ const _utils = require("@orderly.network/utils");
15
16
  function _interop_require_default(obj) {
16
17
  return obj && obj.__esModule ? obj : {
17
18
  default: obj
@@ -68,7 +69,7 @@ const useMutation = (/**
68
69
  url: newUrl,
69
70
  data
70
71
  };
71
- const signature = await signer.sign(payload);
72
+ const signature = await signer.sign(payload, (0, _utils.getTimestamp)());
72
73
  return trigger({
73
74
  data,
74
75
  params,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/useMutation.ts"],"sourcesContent":["import useSWRMutation, {\n TriggerWithOptionsArgs,\n type SWRMutationConfiguration,\n TriggerWithoutArgs,\n} from \"swr/mutation\";\nimport { mutate } from \"@orderly.network/net\";\nimport {\n type MessageFactor,\n type SignedMessagePayload,\n} from \"@orderly.network/core\";\nimport { useAccountInstance } from \"./useAccountInstance\";\nimport { useConfig } from \"./useConfig\";\n\ntype HTTP_METHOD = \"POST\" | \"PUT\" | \"DELETE\";\n\nconst fetcher = (\n url: string,\n options: {\n arg: {\n data?: any;\n params?: any;\n method: HTTP_METHOD;\n signature: SignedMessagePayload;\n };\n }\n) => {\n const init: RequestInit = {\n method: options.arg.method,\n headers: {\n ...options.arg.signature,\n },\n };\n\n if (options.arg.data) {\n init.body = JSON.stringify(options.arg.data);\n }\n\n if (\n typeof options.arg.params === \"object\" &&\n Object.keys(options.arg.params).length\n ) {\n let search = new URLSearchParams(options.arg.params);\n url = `${url}?${search.toString()}`;\n }\n\n return mutate(url, init);\n};\n\n/**\n * This hook is used to execute API requests for data mutation, such as POST, DELETE, PUT, etc.\n */\nexport const useMutation = <T, E>(\n /**\n * The URL to send the request to. If the URL does not start with \"http\",\n * it will be prefixed with the API base URL.\n */\n url: string,\n /**\n * The HTTP method to use for the request. Defaults to \"POST\".\n */\n method: HTTP_METHOD = \"POST\",\n /**\n * The configuration object for the mutation.\n * @see [useSWRMutation](https://swr.vercel.app/docs/mutation#api)\n *\n * @link https://swr.vercel.app/docs/mutation#api\n */\n options?: SWRMutationConfiguration<T, E>\n) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n\n let fullUrl = url;\n if (!url.startsWith(\"http\")) {\n fullUrl = `${apiBaseUrl}${url}`;\n }\n\n const account = useAccountInstance();\n const signer = account.signer;\n const { trigger, data, error, reset, isMutating } = useSWRMutation(\n fullUrl,\n // method === \"POST\" ? fetcher : deleteFetcher,\n fetcher,\n options\n );\n\n const mutation = async (\n /**\n * The data to send with the request.\n */\n data: Record<string, any> | null,\n /**\n * The query parameters to send with the request.\n */\n params?: Record<string, any>,\n options?: SWRMutationConfiguration<T, E>\n ): Promise<any> => {\n let newUrl = url;\n if (typeof params === \"object\" && Object.keys(params).length) {\n let search = new URLSearchParams(params);\n newUrl = `${url}?${search.toString()}`;\n }\n\n const payload: MessageFactor = {\n method,\n url: newUrl,\n data,\n };\n\n const signature = await signer.sign(payload);\n\n return trigger(\n {\n data,\n params,\n method,\n signature: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n },\n options\n );\n };\n\n return [\n mutation,\n {\n data,\n error,\n reset,\n isMutating,\n },\n ] as const;\n};\n"],"names":["useMutation","fetcher","url","options","init","method","arg","headers","signature","data","body","JSON","stringify","params","Object","keys","length","search","URLSearchParams","toString","mutate","apiBaseUrl","useConfig","fullUrl","startsWith","account","useAccountInstance","signer","trigger","error","reset","isMutating","useSWRMutation","mutation","newUrl","payload","sign","accountId"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAmDaA;;;eAAAA;;;iEA/CN;qBACgB;oCAKY;2BACT;;;;;;AAI1B,MAAMC,UAAU,CACdC,KACAC;IASA,MAAMC,OAAoB;QACxBC,QAAQF,QAAQG,GAAG,CAACD,MAAM;QAC1BE,SAAS;YACP,GAAGJ,QAAQG,GAAG,CAACE,SAAS;QAC1B;IACF;IAEA,IAAIL,QAAQG,GAAG,CAACG,IAAI,EAAE;QACpBL,KAAKM,IAAI,GAAGC,KAAKC,SAAS,CAACT,QAAQG,GAAG,CAACG,IAAI;IAC7C;IAEA,IACE,OAAON,QAAQG,GAAG,CAACO,MAAM,KAAK,YAC9BC,OAAOC,IAAI,CAACZ,QAAQG,GAAG,CAACO,MAAM,EAAEG,MAAM,EACtC;QACA,IAAIC,SAAS,IAAIC,gBAAgBf,QAAQG,GAAG,CAACO,MAAM;QACnDX,MAAM,CAAC,EAAEA,IAAI,CAAC,EAAEe,OAAOE,QAAQ,GAAG,CAAC;IACrC;IAEA,OAAOC,IAAAA,WAAM,EAAClB,KAAKE;AACrB;AAKO,MAAMJ,cAAc,CACzB;;;GAGC,GACDE,KACA;;GAEC,GACDG,SAAsB,MAAM,EAC5B;;;;;GAKC,GACDF;IAEA,MAAMkB,aAAaC,IAAAA,oBAAS,EAAC;IAE7B,IAAIC,UAAUrB;IACd,IAAI,CAACA,IAAIsB,UAAU,CAAC,SAAS;QAC3BD,UAAU,CAAC,EAAEF,WAAW,EAAEnB,IAAI,CAAC;IACjC;IAEA,MAAMuB,UAAUC,IAAAA,sCAAkB;IAClC,MAAMC,SAASF,QAAQE,MAAM;IAC7B,MAAM,EAAEC,OAAO,EAAEnB,IAAI,EAAEoB,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAE,GAAGC,IAAAA,iBAAc,EAChET,SACA,+CAA+C;IAC/CtB,SACAE;IAGF,MAAM8B,WAAW,OACf;;KAEC,GACDxB,MACA;;KAEC,GACDI,QACAV;QAEA,IAAI+B,SAAShC;QACb,IAAI,OAAOW,WAAW,YAAYC,OAAOC,IAAI,CAACF,QAAQG,MAAM,EAAE;YAC5D,IAAIC,SAAS,IAAIC,gBAAgBL;YACjCqB,SAAS,CAAC,EAAEhC,IAAI,CAAC,EAAEe,OAAOE,QAAQ,GAAG,CAAC;QACxC;QAEA,MAAMgB,UAAyB;YAC7B9B;YACAH,KAAKgC;YACLzB;QACF;QAEA,MAAMD,YAAY,MAAMmB,OAAOS,IAAI,CAACD;QAEpC,OAAOP,QACL;YACEnB;YACAI;YACAR;YACAG,WAAW;gBACT,GAAGA,SAAS;gBACZ,sBAAsBiB,QAAQY,SAAS;YACzC;QACF,GACAlC;IAEJ;IAEA,OAAO;QACL8B;QACA;YACExB;YACAoB;YACAC;YACAC;QACF;KACD;AACH"}
1
+ {"version":3,"sources":["../src/useMutation.ts"],"sourcesContent":["import useSWRMutation, {\n TriggerWithOptionsArgs,\n type SWRMutationConfiguration,\n TriggerWithoutArgs,\n} from \"swr/mutation\";\nimport { mutate } from \"@orderly.network/net\";\nimport {\n type MessageFactor,\n type SignedMessagePayload,\n} from \"@orderly.network/core\";\nimport { useAccountInstance } from \"./useAccountInstance\";\nimport { useConfig } from \"./useConfig\";\nimport { getTimestamp } from \"@orderly.network/utils\";\n\ntype HTTP_METHOD = \"POST\" | \"PUT\" | \"DELETE\";\n\nconst fetcher = (\n url: string,\n options: {\n arg: {\n data?: any;\n params?: any;\n method: HTTP_METHOD;\n signature: SignedMessagePayload;\n };\n }\n) => {\n const init: RequestInit = {\n method: options.arg.method,\n headers: {\n ...options.arg.signature,\n },\n };\n\n if (options.arg.data) {\n init.body = JSON.stringify(options.arg.data);\n }\n\n if (\n typeof options.arg.params === \"object\" &&\n Object.keys(options.arg.params).length\n ) {\n let search = new URLSearchParams(options.arg.params);\n url = `${url}?${search.toString()}`;\n }\n\n return mutate(url, init);\n};\n\n/**\n * This hook is used to execute API requests for data mutation, such as POST, DELETE, PUT, etc.\n */\nexport const useMutation = <T, E>(\n /**\n * The URL to send the request to. If the URL does not start with \"http\",\n * it will be prefixed with the API base URL.\n */\n url: string,\n /**\n * The HTTP method to use for the request. Defaults to \"POST\".\n */\n method: HTTP_METHOD = \"POST\",\n /**\n * The configuration object for the mutation.\n * @see [useSWRMutation](https://swr.vercel.app/docs/mutation#api)\n *\n * @link https://swr.vercel.app/docs/mutation#api\n */\n options?: SWRMutationConfiguration<T, E>\n) => {\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n\n let fullUrl = url;\n if (!url.startsWith(\"http\")) {\n fullUrl = `${apiBaseUrl}${url}`;\n }\n\n const account = useAccountInstance();\n const signer = account.signer;\n const { trigger, data, error, reset, isMutating } = useSWRMutation(\n fullUrl,\n // method === \"POST\" ? fetcher : deleteFetcher,\n fetcher,\n options\n );\n\n const mutation = async (\n /**\n * The data to send with the request.\n */\n data: Record<string, any> | null,\n /**\n * The query parameters to send with the request.\n */\n params?: Record<string, any>,\n options?: SWRMutationConfiguration<T, E>\n ): Promise<any> => {\n let newUrl = url;\n if (typeof params === \"object\" && Object.keys(params).length) {\n let search = new URLSearchParams(params);\n newUrl = `${url}?${search.toString()}`;\n }\n\n const payload: MessageFactor = {\n method,\n url: newUrl,\n data,\n };\n\n const signature = await signer.sign(payload, getTimestamp());\n\n return trigger(\n {\n data,\n params,\n method,\n signature: {\n ...signature,\n \"orderly-account-id\": account.accountId,\n },\n },\n options\n );\n };\n\n return [\n mutation,\n {\n data,\n error,\n reset,\n isMutating,\n },\n ] as const;\n};\n"],"names":["useMutation","fetcher","url","options","init","method","arg","headers","signature","data","body","JSON","stringify","params","Object","keys","length","search","URLSearchParams","toString","mutate","apiBaseUrl","useConfig","fullUrl","startsWith","account","useAccountInstance","signer","trigger","error","reset","isMutating","useSWRMutation","mutation","newUrl","payload","sign","getTimestamp","accountId"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAoDaA;;;eAAAA;;;iEAhDN;qBACgB;oCAKY;2BACT;uBACG;;;;;;AAI7B,MAAMC,UAAU,CACdC,KACAC;IASA,MAAMC,OAAoB;QACxBC,QAAQF,QAAQG,GAAG,CAACD,MAAM;QAC1BE,SAAS;YACP,GAAGJ,QAAQG,GAAG,CAACE,SAAS;QAC1B;IACF;IAEA,IAAIL,QAAQG,GAAG,CAACG,IAAI,EAAE;QACpBL,KAAKM,IAAI,GAAGC,KAAKC,SAAS,CAACT,QAAQG,GAAG,CAACG,IAAI;IAC7C;IAEA,IACE,OAAON,QAAQG,GAAG,CAACO,MAAM,KAAK,YAC9BC,OAAOC,IAAI,CAACZ,QAAQG,GAAG,CAACO,MAAM,EAAEG,MAAM,EACtC;QACA,IAAIC,SAAS,IAAIC,gBAAgBf,QAAQG,GAAG,CAACO,MAAM;QACnDX,MAAM,CAAC,EAAEA,IAAI,CAAC,EAAEe,OAAOE,QAAQ,GAAG,CAAC;IACrC;IAEA,OAAOC,IAAAA,WAAM,EAAClB,KAAKE;AACrB;AAKO,MAAMJ,cAAc,CACzB;;;GAGC,GACDE,KACA;;GAEC,GACDG,SAAsB,MAAM,EAC5B;;;;;GAKC,GACDF;IAEA,MAAMkB,aAAaC,IAAAA,oBAAS,EAAC;IAE7B,IAAIC,UAAUrB;IACd,IAAI,CAACA,IAAIsB,UAAU,CAAC,SAAS;QAC3BD,UAAU,CAAC,EAAEF,WAAW,EAAEnB,IAAI,CAAC;IACjC;IAEA,MAAMuB,UAAUC,IAAAA,sCAAkB;IAClC,MAAMC,SAASF,QAAQE,MAAM;IAC7B,MAAM,EAAEC,OAAO,EAAEnB,IAAI,EAAEoB,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAE,GAAGC,IAAAA,iBAAc,EAChET,SACA,+CAA+C;IAC/CtB,SACAE;IAGF,MAAM8B,WAAW,OACf;;KAEC,GACDxB,MACA;;KAEC,GACDI,QACAV;QAEA,IAAI+B,SAAShC;QACb,IAAI,OAAOW,WAAW,YAAYC,OAAOC,IAAI,CAACF,QAAQG,MAAM,EAAE;YAC5D,IAAIC,SAAS,IAAIC,gBAAgBL;YACjCqB,SAAS,CAAC,EAAEhC,IAAI,CAAC,EAAEe,OAAOE,QAAQ,GAAG,CAAC;QACxC;QAEA,MAAMgB,UAAyB;YAC7B9B;YACAH,KAAKgC;YACLzB;QACF;QAEA,MAAMD,YAAY,MAAMmB,OAAOS,IAAI,CAACD,SAASE,IAAAA,mBAAY;QAEzD,OAAOT,QACL;YACEnB;YACAI;YACAR;YACAG,WAAW;gBACT,GAAGA,SAAS;gBACZ,sBAAsBiB,QAAQa,SAAS;YACzC;QACF,GACAnC;IAEJ;IAEA,OAAO;QACL8B;QACA;YACExB;YACAoB;YACAC;YACAC;QACF;KACD;AACH"}
@@ -4,12 +4,13 @@ import { type DrawOptions } from "./services/painter/basePaint";
4
4
  * @example
5
5
  * ```tsx
6
6
  * const { ref, toDataURL, toBlob, download, copy } = usePoster({
7
- * backgroundColor: "#0b8c70",
8
- * backgroundImg: "/images/poster_bg.png",
9
- * color: "rgba(255, 255, 255, 0.98)",
10
- * profitColor: "rgb(0,181,159)",
11
- * ...
7
+ * backgroundColor: "#0b8c70",
8
+ * backgroundImg: "/images/poster_bg.png",
9
+ * color: "rgba(255, 255, 255, 0.98)",
10
+ * profitColor: "rgb(0,181,159)",
11
+ * // ...
12
12
  * });
13
+ * ```
13
14
  */
14
15
  export declare const usePoster: (data: DrawOptions, options?: {
15
16
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"usePoster.d.ts","sourceRoot":"","sources":["../src/usePoster.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIhE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,SAAS,SAId,WAAW,YACP;IACR;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;IAiHC;;OAEG;wBAnDa,iBAAiB,GAAG,IAAI;IAqDxC;;OAEG;gCA9EqB,MAAM,mBAAmB,MAAM;IAgFvD;;OAEG;6BAvEK,MAAM,mBAAmB,MAAM,KAAG,QAAQ,IAAI,GAAG,IAAI,CAAC;IAyE9D;;OAEG;kCApDQ,MAAM,SAAQ,MAAM,mBAAiC,MAAM;IAsDtE;;OAEG;;;CAIN,CAAC"}
1
+ {"version":3,"file":"usePoster.d.ts","sourceRoot":"","sources":["../src/usePoster.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIhE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,SAId,WAAW,YACP;IACR;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;IAiHC;;OAEG;wBAnDa,iBAAiB,GAAG,IAAI;IAqDxC;;OAEG;gCA9EqB,MAAM,mBAAmB,MAAM;IAgFvD;;OAEG;6BAvEK,MAAM,mBAAmB,MAAM,KAAG,QAAQ,IAAI,GAAG,IAAI,CAAC;IAyE9D;;OAEG;kCApDQ,MAAM,SAAQ,MAAM,mBAAiC,MAAM;IAsDtE;;OAEG;;;CAIN,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/usePoster.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { mergeDeepRight } from \"ramda\";\nimport { PosterPainter } from \"./services/painter/painter\";\nimport { type DrawOptions } from \"./services/painter/basePaint\";\nimport { DefaultLayoutConfig } from \"./services/painter/layout.config\";\nimport { SDKError } from \"@orderly.network/types\";\n\n/**\n * Generates a poster image based on position information. You can set the size, background color, font color, font size, and content position of the poster.\n * @example\n * ```tsx\n * const { ref, toDataURL, toBlob, download, copy } = usePoster({\n * backgroundColor: \"#0b8c70\",\n * backgroundImg: \"/images/poster_bg.png\",\n * color: \"rgba(255, 255, 255, 0.98)\",\n * profitColor: \"rgb(0,181,159)\",\n * ...\n * });\n */\nexport const usePoster = (\n /**\n * The options to draw the poster\n */\n data: DrawOptions,\n options?: {\n /**\n * The ratio of the poster\n */\n ratio?: number;\n }\n) => {\n const [error, setError] = useState<Error | null>(null);\n const [canCopy, setCanCopy] = useState<boolean>(\n () => typeof navigator.clipboard !== \"undefined\"\n );\n\n const painterRef = useRef<PosterPainter | null>(null);\n\n const [target, setTarget] = useState<HTMLCanvasElement | null>(null);\n\n useEffect(() => {\n // Create the painter instance\n if (target) {\n if (!painterRef.current) {\n painterRef.current = new PosterPainter(target, {\n ratio: options?.ratio || 1,\n ...options,\n });\n }\n\n painterRef.current.draw(\n mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n data\n )\n );\n }\n }, [target, data]);\n\n // useEffect(() => {\n // if (painterRef.current) {\n // painterRef.current.draw(\n // mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n // { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n // data\n // )\n // );\n // }\n // }, [data]);\n\n const toDataURL = (type?: string, encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n return target.toDataURL(type, encoderOptions);\n };\n\n /**\n * Converts the poster to a blob\n */\n const toBlob = useCallback(\n (type?: string, encoderOptions?: number): Promise<Blob | null> => {\n return new Promise<Blob | null>((resolve) => {\n if (!target) {\n resolve(null);\n return;\n }\n target.toBlob(resolve, type, encoderOptions);\n });\n },\n [target]\n );\n\n const ref = (ref: HTMLCanvasElement | null) => {\n if (!ref) return;\n if (ref.tagName.toUpperCase() !== \"CANVAS\") {\n // throw new Error(\"The ref must be a canvas element\");\n setError(new SDKError(\"The ref must be a canvas element\"));\n return;\n }\n setTarget(ref);\n };\n\n const download = useCallback(\n (filename: string, type: string = \"image/png\", encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n const img = new Image();\n img.src = target.toDataURL(type, encoderOptions);\n const link = document.createElement(\"a\");\n link.href = img.src;\n link.download = filename;\n link.click();\n },\n [target]\n );\n\n const copy = useCallback(() => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n // copy image to clipboard\n return new Promise<void>((resolve, reject) => {\n if (!navigator.clipboard) {\n reject(new SDKError(\"Clipboard API is not supported\"));\n return;\n }\n target.toBlob((blob) => {\n if (!blob) {\n reject(new SDKError(\"Failed to create blob\"));\n return;\n }\n return navigator.clipboard\n .write([new ClipboardItem({ [blob.type]: blob })])\n .then(resolve, reject);\n });\n });\n }, [target]);\n\n return {\n error,\n /**\n * The ref to the canvas element, you should pass this ref to the canvas element\n */\n ref,\n /**\n * Converts the poster to a data URL\n */\n toDataURL,\n /**\n * Converts the poster to a blob\n */\n toBlob,\n /**\n * Downloads the poster as an image\n */\n download,\n /**\n * Browser if supports copy image to clipboard\n */\n canCopy,\n copy,\n } as const;\n};\n"],"names":["usePoster","data","options","error","setError","useState","canCopy","setCanCopy","navigator","clipboard","painterRef","useRef","target","setTarget","useEffect","current","PosterPainter","ratio","draw","mergeDeepRight","layout","DefaultLayoutConfig","fontFamily","toDataURL","type","encoderOptions","SDKError","toBlob","useCallback","Promise","resolve","ref","tagName","toUpperCase","download","filename","img","Image","src","link","document","createElement","href","click","copy","reject","blob","write","ClipboardItem","then"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAmBaA;;;eAAAA;;;uBAnB4C;uBAC1B;yBACD;8BAEM;uBACX;AAclB,MAAMA,YAAY,CACvB;;GAEC,GACDC,MACAC;IAOA,MAAM,CAACC,OAAOC,SAAS,GAAGC,IAAAA,eAAQ,EAAe;IACjD,MAAM,CAACC,SAASC,WAAW,GAAGF,IAAAA,eAAQ,EACpC,IAAM,OAAOG,UAAUC,SAAS,KAAK;IAGvC,MAAMC,aAAaC,IAAAA,aAAM,EAAuB;IAEhD,MAAM,CAACC,QAAQC,UAAU,GAAGR,IAAAA,eAAQ,EAA2B;IAE/DS,IAAAA,gBAAS,EAAC;QACR,8BAA8B;QAC9B,IAAIF,QAAQ;YACV,IAAI,CAACF,WAAWK,OAAO,EAAE;gBACvBL,WAAWK,OAAO,GAAG,IAAIC,sBAAa,CAACJ,QAAQ;oBAC7CK,OAAOf,SAASe,SAAS;oBACzB,GAAGf,OAAO;gBACZ;YACF;YAEAQ,WAAWK,OAAO,CAACG,IAAI,CACrBC,IAAAA,qBAAc,EACZ;gBAAEC,QAAQC,iCAAmB;gBAAEC,YAAY;YAAU,GACrDrB;QAGN;IACF,GAAG;QAACW;QAAQX;KAAK;IAEjB,oBAAoB;IACpB,8BAA8B;IAC9B,+BAA+B;IAC/B,2DAA2D;IAC3D,kEAAkE;IAClE,eAAe;IACf,UAAU;IACV,SAAS;IACT,MAAM;IACN,cAAc;IAEd,MAAMsB,YAAY,CAACC,MAAeC;QAChC,IAAI,CAACb,QAAQ;YACX,MAAM,IAAIc,eA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oBAAC,IAAIC,cAAc;wBAAE,CAACF,KAAKtB,IAAI,CAAC,EAAEsB;oBAAK;iBAAG,EAChDG,IAAI,CAACnB,SAASe;YACnB;QACF;IACF,GAAG;QAACjC;KAAO;IAEX,OAAO;QACLT;QACA;;KAEC,GACD4B;QACA;;KAEC,GACDR;QACA;;KAEC,GACDI;QACA;;KAEC,GACDO;QACA;;KAEC,GACD5B;QACAsC;IACF;AACF"}
1
+ {"version":3,"sources":["../src/usePoster.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { mergeDeepRight } from \"ramda\";\nimport { PosterPainter } from \"./services/painter/painter\";\nimport { type DrawOptions } from \"./services/painter/basePaint\";\nimport { DefaultLayoutConfig } from \"./services/painter/layout.config\";\nimport { SDKError } from \"@orderly.network/types\";\n\n/**\n * Generates a poster image based on position information. You can set the size, background color, font color, font size, and content position of the poster.\n * @example\n * ```tsx\n * const { ref, toDataURL, toBlob, download, copy } = usePoster({\n * backgroundColor: \"#0b8c70\",\n * backgroundImg: \"/images/poster_bg.png\",\n * color: \"rgba(255, 255, 255, 0.98)\",\n * profitColor: \"rgb(0,181,159)\",\n * // ...\n * });\n * ```\n */\nexport const usePoster = (\n /**\n * The options to draw the poster\n */\n data: DrawOptions,\n options?: {\n /**\n * The ratio of the poster\n */\n ratio?: number;\n }\n) => {\n const [error, setError] = useState<Error | null>(null);\n const [canCopy, setCanCopy] = useState<boolean>(\n () => typeof navigator.clipboard !== \"undefined\"\n );\n\n const painterRef = useRef<PosterPainter | null>(null);\n\n const [target, setTarget] = useState<HTMLCanvasElement | null>(null);\n\n useEffect(() => {\n // Create the painter instance\n if (target) {\n if (!painterRef.current) {\n painterRef.current = new PosterPainter(target, {\n ratio: options?.ratio || 1,\n ...options,\n });\n }\n\n painterRef.current.draw(\n mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n data\n )\n );\n }\n }, [target, data]);\n\n // useEffect(() => {\n // if (painterRef.current) {\n // painterRef.current.draw(\n // mergeDeepRight<Partial<DrawOptions>, DrawOptions>(\n // { layout: DefaultLayoutConfig, fontFamily: \"Manrope\" },\n // data\n // )\n // );\n // }\n // }, [data]);\n\n const toDataURL = (type?: string, encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n return target.toDataURL(type, encoderOptions);\n };\n\n /**\n * Converts the poster to a blob\n */\n const toBlob = useCallback(\n (type?: string, encoderOptions?: number): Promise<Blob | null> => {\n return new Promise<Blob | null>((resolve) => {\n if (!target) {\n resolve(null);\n return;\n }\n target.toBlob(resolve, type, encoderOptions);\n });\n },\n [target]\n );\n\n const ref = (ref: HTMLCanvasElement | null) => {\n if (!ref) return;\n if (ref.tagName.toUpperCase() !== \"CANVAS\") {\n // throw new Error(\"The ref must be a canvas element\");\n setError(new SDKError(\"The ref must be a canvas element\"));\n return;\n }\n setTarget(ref);\n };\n\n const download = useCallback(\n (filename: string, type: string = \"image/png\", encoderOptions?: number) => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n const img = new Image();\n img.src = target.toDataURL(type, encoderOptions);\n const link = document.createElement(\"a\");\n link.href = img.src;\n link.download = filename;\n link.click();\n },\n [target]\n );\n\n const copy = useCallback(() => {\n if (!target) {\n throw new SDKError(\"The ref must be a canvas element\");\n }\n // copy image to clipboard\n return new Promise<void>((resolve, reject) => {\n if (!navigator.clipboard) {\n reject(new SDKError(\"Clipboard API is not supported\"));\n return;\n }\n target.toBlob((blob) => {\n if (!blob) {\n reject(new SDKError(\"Failed to create blob\"));\n return;\n }\n return navigator.clipboard\n .write([new ClipboardItem({ [blob.type]: blob })])\n .then(resolve, reject);\n });\n });\n }, [target]);\n\n return {\n error,\n /**\n * The ref to the canvas element, you should pass this ref to the canvas element\n */\n ref,\n /**\n * Converts the poster to a data URL\n */\n toDataURL,\n /**\n * Converts the poster to a blob\n */\n toBlob,\n /**\n * Downloads the poster as an image\n */\n download,\n /**\n * Browser if supports copy image to clipboard\n */\n canCopy,\n copy,\n } as const;\n};\n"],"names":["usePoster","data","options","error","setError","useState","canCopy","setCanCopy","navigator","clipboard","painterRef","useRef","target","setTarget","useEffect","current","PosterPainter","ratio","draw","mergeDeepRight","layout","DefaultLayoutConfig","fontFamily","toDataURL","type","encoderOptions","SDKError","toBlob","useCallback","Promise","resolve","ref","tagName","toUpperCase","download","filename","img","Image","src","link","document","createElement","href","click","copy","reject","blob","write","ClipboardItem","then"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAoBaA;;;eAAAA;;;uBApB4C;uBAC1B;yBACD;8BAEM;uBACX;AAelB,MAAMA,YAAY,CACvB;;GAEC,GACDC,MACAC;IAOA,MAAM,CAACC,OAAOC,SAAS,GAAGC,IAAAA,eAAQ,EAAe;IACjD,MAAM,CAACC,SAASC,WAAW,GAAGF,IAAAA,eAAQ,EACpC,IAAM,OAAOG,UAAUC,SAAS,KAAK;IAGvC,MAAMC,aAAaC,IAAAA,aAAM,EAAuB;IAEhD,MAAM,CAACC,QAAQC,UAAU,GAAGR,IAAAA,eAAQ,EAA2B;IAE/DS,IAAAA,gBAAS,EAAC;QACR,8BAA8B;QAC9B,IAAIF,QAAQ;YACV,IAAI,CAACF,WAAWK,OAAO,EAAE;gBACvBL,WAAWK,OAAO,GAAG,IAAIC,sBAAa,CAACJ,QAAQ;oBAC7CK,OAAOf,SAASe,SAAS;oBACzB,GAAGf,OAAO;gBACZ;YACF;YAEAQ,WAAWK,OAAO,CAACG,IAAI,CACrBC,IAAAA,qBAAc,EACZ;gBAAEC,QAAQC,iCAAmB;gBAAEC,YAAY;YAAU,GACrDrB;QAGN;IACF,GAAG;QAACW;QAAQX;KAAK;IAEjB,oBAAoB;IAC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oC,OAAO,IAAInB,eAAQ,CAAC;gBACpB;YACF;YACAd,OAAOe,MAAM,CAAC,CAACmB;gBACb,IAAI,CAACA,MAAM;oBACTD,OAAO,IAAInB,eAAQ,CAAC;oBACpB;gBACF;gBACA,OAAOlB,UAAUC,SAAS,CACvBsC,KAAK,CAAC;oBAAC,IAAIC,cAAc;wBAAE,CAACF,KAAKtB,IAAI,CAAC,EAAEsB;oBAAK;iBAAG,EAChDG,IAAI,CAACnB,SAASe;YACnB;QACF;IACF,GAAG;QAACjC;KAAO;IAEX,OAAO;QACLT;QACA;;KAEC,GACD4B;QACA;;KAEC,GACDR;QACA;;KAEC,GACDI;QACA;;KAEC,GACDO;QACA;;KAEC,GACD5B;QACAsC;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"usePreloadData.d.ts","sourceRoot":"","sources":["../src/usePreloadData.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,cAAc;;;CAgB1B,CAAC"}
1
+ {"version":3,"file":"usePreloadData.d.ts","sourceRoot":"","sources":["../src/usePreloadData.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,cAAc;;;CAoD1B,CAAC"}
@@ -10,10 +10,30 @@ Object.defineProperty(exports, "usePreLoadData", {
10
10
  });
11
11
  const _react = require("react");
12
12
  const _ = require(".");
13
+ const _utils = require("@orderly.network/utils");
13
14
  const usePreLoadData = ()=>{
14
15
  const { error: tokenError, data: tokenData } = (0, _.useQuery)("https://api-evm.orderly.org/v1/public/token", {
15
16
  revalidateOnFocus: false
16
17
  });
18
+ /// get service timestamp
19
+ /// get local timestamp
20
+ /// calculate delta offset = SD - LD
21
+ /// save to getGlobalObject.__ORDERLY_timestamp_offset
22
+ const apiBaseUrl = (0, _.useConfig)("apiBaseUrl");
23
+ const { data: systemInfo } = (0, _.useSWR)("/v1/public/system_info", async (url, init)=>{
24
+ const data = await fetch(url.startsWith("http") ? url : `${apiBaseUrl}${url}`, init);
25
+ return await data.json();
26
+ }, {
27
+ errorRetryCount: 3,
28
+ errorRetryInterval: 500
29
+ });
30
+ if (typeof systemInfo !== "undefined") {
31
+ const sd = systemInfo.timestamp;
32
+ const ld = Date.now();
33
+ // @ts-ignore
34
+ (0, _utils.getGlobalObject)().__ORDERLY_timestamp_offset = sd - ld;
35
+ }
36
+ ;
17
37
  const isDone = (0, _react.useMemo)(()=>{
18
38
  return !!tokenData;
19
39
  }, [
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/usePreloadData.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useQuery } from \".\";\n\nexport const usePreLoadData = () => {\n const { error: tokenError, data: tokenData } = useQuery(\n \"https://api-evm.orderly.org/v1/public/token\",\n {\n revalidateOnFocus: false,\n }\n );\n\n const isDone = useMemo(() => {\n return !!tokenData;\n }, [tokenData]);\n\n return {\n error: tokenError,\n done: isDone,\n };\n};\n"],"names":["usePreLoadData","error","tokenError","data","tokenData","useQuery","revalidateOnFocus","isDone","useMemo","done"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAGaA;;;eAAAA;;;uBAHW;kBACC;AAElB,MAAMA,iBAAiB;IAC5B,MAAM,EAAEC,OAAOC,UAAU,EAAEC,MAAMC,SAAS,EAAE,GAAGC,IAAAA,UAAQ,EACrD,+CACA;QACEC,mBAAmB;IACrB;IAGF,MAAMC,SAASC,IAAAA,cAAO,EAAC;QACrB,OAAO,CAAC,CAACJ;IACX,GAAG;QAACA;KAAU;IAEd,OAAO;QACLH,OAAOC;QACPO,MAAMF;IACR;AACF"}
1
+ {"version":3,"sources":["../src/usePreloadData.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useConfig, useQuery, useSWR } from \".\";\nimport { request } from \"@orderly.network/net/src/fetch\";\nimport { getGlobalObject } from \"@orderly.network/utils\";\n\nexport const usePreLoadData = () => {\n const { error: tokenError, data: tokenData } = useQuery(\n \"https://api-evm.orderly.org/v1/public/token\",\n {\n revalidateOnFocus: false,\n }\n );\n\n /// get service timestamp\n /// get local timestamp\n /// calculate delta offset = SD - LD\n /// save to getGlobalObject.__ORDERLY_timestamp_offset\n\n const apiBaseUrl = useConfig(\"apiBaseUrl\");\n\n const { data: systemInfo } = useSWR(\n \"/v1/public/system_info\",\n async (url: any, init: any) => {\n const data = await fetch(\n url.startsWith(\"http\") ? url : `${apiBaseUrl}${url}`,\n init\n );\n return await data.json();\n },\n {\n errorRetryCount: 3,\n errorRetryInterval: 500,\n }\n );\n\n if (typeof systemInfo !== \"undefined\") {\n const sd = systemInfo.timestamp;\n const ld = Date.now();\n // @ts-ignore\n getGlobalObject().__ORDERLY_timestamp_offset = sd - ld;\n }\n\n // @ts-ignore\n console.log(\n \"systemInfo\",\n systemInfo,\n getGlobalObject().__ORDERLY_timestamp_offset\n );\n\n const isDone = useMemo(() => {\n return !!tokenData;\n }, [tokenData]);\n\n return {\n error: tokenError,\n done: isDone,\n };\n};\n"],"names":["usePreLoadData","error","tokenError","data","tokenData","useQuery","revalidateOnFocus","apiBaseUrl","useConfig","systemInfo","useSWR","url","init","fetch","startsWith","json","errorRetryCount","errorRetryInterval","sd","timestamp","ld","Date","now","getGlobalObject","__ORDERLY_timestamp_offset","isDone","useMemo","done"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;+BAKaA;;;eAAAA;;;uBALW;kBACoB;uBAEZ;AAEzB,MAAMA,iBAAiB;IAC5B,MAAM,EAAEC,OAAOC,UAAU,EAAEC,MAAMC,SAAS,EAAE,GAAGC,IAAAA,UAAQ,EACrD,+CACA;QACEC,mBAAmB;IACrB;IAGF,yBAAyB;IACzB,uBAAuB;IACvB,oCAAoC;IACpC,sDAAsD;IAEtD,MAAMC,aAAaC,IAAAA,WAAS,EAAC;IAE7B,MAAM,EAAEL,MAAMM,UAAU,EAAE,GAAGC,IAAAA,QAAM,EACjC,0BACA,OAAOC,KAAUC;QACf,MAAMT,OAAO,MAAMU,MACjBF,IAAIG,UAAU,CAAC,UAAUH,MAAM,CAAC,EAAEJ,WAAW,EAAEI,IAAI,CAAC,EACpDC;QAEF,OAAO,MAAMT,KAAKY,IAAI;IACxB,GACA;QACEC,iBAAiB;QACjBC,oBAAoB;IACtB;IAGF,IAAI,OAAOR,eAAe,aAAa;QACrC,MAAMS,KAAKT,WAAWU,SAAS;QAC/B,MAAMC,KAAKC,KAAKC,GAAG;QACnB,aAAa;QACbC,IAAAA,sBAAe,IAAGC,0BAA0B,GAAGN,KAAKE;IACtD;;IASA,MAAMK,SAASC,IAAAA,cAAO,EAAC;QACrB,OAAO,CAAC,CAACtB;IACX,GAAG;QAACA;KAAU;IAEd,OAAO;QACLH,OAAOC;QACPyB,MAAMF;IACR;AACF"}
package/lib/version.d.ts CHANGED
@@ -5,6 +5,6 @@ declare global {
5
5
  };
6
6
  }
7
7
  }
8
- declare const _default: "1.5.2";
8
+ declare const _default: "1.5.3-alpha.0";
9
9
  export default _default;
10
10
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,CAAC;IACX,UAAU,MAAM;QACZ,mBAAmB,CAAC,EAAE;YAClB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;SACzB,CAAC;KACL;CACJ;;AAMD,wBAAuB"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,CAAC;IACX,UAAU,MAAM;QACZ,mBAAmB,CAAC,EAAE;YAClB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;SACzB,CAAC;KACL;CACJ;;AAMD,wBAA+B"}
package/lib/version.js CHANGED
@@ -10,8 +10,8 @@ Object.defineProperty(exports, "default", {
10
10
  });
11
11
  if (typeof window !== 'undefined') {
12
12
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
13
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "1.5.2";
13
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "1.5.3-alpha.0";
14
14
  }
15
- const _default = "1.5.2";
15
+ const _default = "1.5.3-alpha.0";
16
16
 
17
17
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["\ndeclare global {\n interface Window {\n __ORDERLY_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif(typeof window !== 'undefined') {\n window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};\n window.__ORDERLY_VERSION__[\"@orderly.network/hooks\"] = \"1.5.2\";\n};\n\nexport default \"1.5.2\";\n"],"names":["window","__ORDERLY_VERSION__"],"rangeMappings":";;;;;;;;;;;;;;","mappings":";;;;+BAaA;;;eAAA;;;AALA,IAAG,OAAOA,WAAW,aAAa;IAC9BA,OAAOC,mBAAmB,GAAGD,OAAOC,mBAAmB,IAAI,CAAC;IAC5DD,OAAOC,mBAAmB,CAAC,yBAAyB,GAAG;AAC3D;MAEA,WAAe"}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["\ndeclare global {\n interface Window {\n __ORDERLY_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif(typeof window !== 'undefined') {\n window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};\n window.__ORDERLY_VERSION__[\"@orderly.network/hooks\"] = \"1.5.3-alpha.0\";\n};\n\nexport default \"1.5.3-alpha.0\";\n"],"names":["window","__ORDERLY_VERSION__"],"rangeMappings":";;;;;;;;;;;;;;","mappings":";;;;+BAaA;;;eAAA;;;AALA,IAAG,OAAOA,WAAW,aAAa;IAC9BA,OAAOC,mBAAmB,GAAGD,OAAOC,mBAAmB,IAAI,CAAC;IAC5DD,OAAOC,mBAAmB,CAAC,yBAAyB,GAAG;AAC3D;MAEA,WAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orderly.network/hooks",
3
- "version": "1.5.2",
3
+ "version": "1.5.3-alpha.0",
4
4
  "description": "",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",
@@ -32,7 +32,7 @@
32
32
  "tsup": "^7.1.0",
33
33
  "typedoc": "^0.24.8",
34
34
  "typescript": "^5.1.6",
35
- "tsconfig": "0.3.2"
35
+ "tsconfig": "0.3.3-alpha.0"
36
36
  },
37
37
  "dependencies": {
38
38
  "@akamfoad/qr": "^0.4.0",
@@ -40,11 +40,11 @@
40
40
  "swr": "2.2.4",
41
41
  "use-constant": "^1.1.1",
42
42
  "use-debounce": "^9.0.4",
43
- "@orderly.network/core": "1.5.2",
44
- "@orderly.network/net": "1.5.2",
45
- "@orderly.network/types": "1.5.2",
46
- "@orderly.network/utils": "1.5.2",
47
- "@orderly.network/perp": "3.3.2"
43
+ "@orderly.network/core": "1.5.3-alpha.0",
44
+ "@orderly.network/perp": "3.3.3-alpha.0",
45
+ "@orderly.network/types": "1.5.3-alpha.0",
46
+ "@orderly.network/utils": "1.5.3-alpha.0",
47
+ "@orderly.network/net": "1.5.3-alpha.0"
48
48
  },
49
49
  "publishConfig": {
50
50
  "access": "public"