UNPKG

@gear-js/react-hooks

Version:
854 lines (853 loc) 30.8 kB
import { BigNumber as x } from "bignumber.js"; import { BigNumber as en } from "bignumber.js"; import { jsx as G, jsxs as ye, Fragment as Se } from "react/jsx-runtime"; import { nanoid as Ee } from "nanoid/non-secure"; import { useRef as O, createContext as $, useContext as J, useState as w, useCallback as D, useMemo as k, useEffect as E } from "react"; import { createPortal as ve } from "react-dom"; import { Transition as we, TransitionGroup as Ie } from "react-transition-group"; import { GearApi as Pe, getStateMetadata as Re } from "@gear-js/api"; import { ScProvider as Te, WsProvider as be, Keyring as te } from "@polkadot/api"; import * as Ce from "@substrate/connect"; import Ve from "@twa-dev/sdk"; import { injectVaranWallet as Fe } from "@varan-wallet/varan-connect"; import { u8aToHex as De, formatBalance as Ge } from "@polkadot/util"; import { useQuery as Be, useQueryClient as Y, useMutation as ne } from "@tanstack/react-query"; import { Sails as xe } from "sails-js"; import { SailsIdlParser as Oe } from "sails-js-parser"; var j = /* @__PURE__ */ ((e) => (e.INFO = "info", e.ERROR = "error", e.LOADING = "loading", e.SUCCESS = "success", e))(j || {}); const Q = { style: { marginBottom: "10px" }, isClosed: !0, timeout: 5e3 }, Me = { ...Q, type: j.INFO }, U = { ...Q, type: j.ERROR }, X = { ...Q, type: j.SUCCESS }, Ue = { ...Q, type: j.LOADING, isClosed: !1, timeout: 0 }, se = 137, re = 250, Le = { opacity: 0, transition: `opacity ${re}ms ease` }, ke = { entering: { opacity: 0 }, entered: { opacity: 1 } }, je = ({ children: e, ...n }) => { const t = O(null); return /* @__PURE__ */ G(we, { nodeRef: t, timeout: re, ...n, children: (s) => /* @__PURE__ */ G( "div", { ref: t, style: { ...Le, ...ke[s] }, children: e } ) }); }, oe = $({}), It = ({ children: e, template: n, containerClassName: t }) => { const s = O(null), r = O(/* @__PURE__ */ new Map()), [o, c] = w([]), i = D((f) => { const l = r.current.get(f); l && (clearTimeout(l), r.current.delete(f)); }, []), a = D( (f) => { i(f), c((l) => l.filter((g) => g.id !== f)); }, [i] ), u = D( (f, l = 0) => { if (l > 0) { const g = setTimeout(() => a(f), l); r.current.set(f, g); } }, [a] ), d = D( (f, l) => { const g = Ee(6); return u(g, l.timeout), c((A) => [ ...A, { id: g, content: f, options: l } ]), g; }, [u] ), p = D( (f, l, g) => { i(f), c( (A) => A.map((y) => { if (y.id !== f) return y; const v = { id: y.id, content: l, options: { ...y.options, ...g } }; return u(v.id, v.options.timeout), v; }) ); }, [i, u] ), m = D( (f) => (l, g) => d(l, { ...f, ...g }), [d] ), h = k( () => ({ update: p, remove: a, info: m(Me), error: m(U), success: m(X), loading: m(Ue) }), [p, a, m] ); return E(() => { s.current = document.createElement("div"), s.current.id = "alert-root", t && s.current.classList.add(t), document.body.appendChild(s.current); }, []), /* @__PURE__ */ ye(Se, { children: [ /* @__PURE__ */ G(oe.Provider, { value: h, children: e }), s.current && ve( /* @__PURE__ */ G(Ie, { appear: !0, children: o.map((f) => /* @__PURE__ */ G(je, { children: /* @__PURE__ */ G(n, { alert: f, close: () => a(f.id) }) }, f.id)) }), s.current ) ] }); }, P = () => J(oe), Ne = { api: void 0, isApiReady: !1, isV110Runtime: !1, switchNetwork: () => Promise.resolve() }, ie = $(Ne), { Provider: ze } = ie; function Pt({ initialArgs: e, children: n }) { const [t, s] = w(), r = O(void 0), o = O(void 0), c = async (a) => { r.current && o.current && (s(void 0), await r.current.disconnect(), o.current()); const u = "spec" in a, d = u ? ( // TODO: remove assertion after https://github.com/polkadot-js/api/issues/6065 is resolved new Te(Ce, a.spec, a.sharedSandbox) ) : new be(a.endpoint, a.autoConnectMs, a.headers, a.timeout); r.current = d, o.current = d.on("connected", async () => s(await Pe.create({ provider: d }))), u && await d.connect(); }; E(() => { c(e); }, []); const i = k( () => t ? { api: t, isApiReady: !0, isV110Runtime: t.specVersion >= 1100, switchNetwork: c } : { api: t, isApiReady: !1, isV110Runtime: !1, switchNetwork: c }, [t] ); return /* @__PURE__ */ G(ze, { value: i, children: n }); } const S = () => J(ie), _e = 200, ce = { INJECTED: "injected", CONNECTED: "connected" }, L = { WALLET_IDS: "walletIds", ACCOUNT_ADDRESS: "accountAddress" }, Z = (e, n, t) => t.filter(({ type: s }) => s !== "ethereum").map(({ address: s, name: r, genesisHash: o, type: c }) => { const i = new te({ type: c }), a = De(i.decodeAddress(s)); return { address: i.encodeAddress(a, se), decodedAddress: a, meta: { source: e, name: r, genesisHash: o }, type: c, signer: n }; }), We = (e) => { const n = localStorage.getItem(L.ACCOUNT_ADDRESS); if (n) return Object.values(e).flatMap(({ accounts: t }) => t).find((t) => t?.address === n); }, ae = () => { const e = localStorage.getItem(L.WALLET_IDS); return e ? JSON.parse(e) : []; }, Qe = (e) => { const n = /* @__PURE__ */ new Set([...ae(), e]), t = JSON.stringify(Array.from(n)); localStorage.setItem(L.WALLET_IDS, t); }, ue = async (e, n, t, s, r) => { try { const o = t.connect || t.enable; if (!o) throw new Error("Connection method is not found"); const { version: c } = t, i = ce.CONNECTED, a = await o.bind(t)(e), { signer: u } = a, d = Z(n, u, await a.accounts.get()), p = a.accounts.subscribe( (m) => s(n, Z(n, u, m)) ); return r(p), { id: n, version: c, status: i, accounts: d, connect: () => Promise.reject(new Error("Wallet is already connected")) }; } catch (o) { console.error("Error while connecting wallet: ", o); } }, ee = (e, n, t, s, r, o) => { const { version: c } = t, i = ce.INJECTED; return { id: n, version: c, status: i, connect: async () => { const u = await ue(e, n, t, s, o); u && (Qe(n), r(n, u)); } }; }, He = async (e, n, t, s) => { const { injectedWeb3: r } = window; if (!r) return {}; const o = Object.entries(r).map( async ([c, i]) => [ c, ae().includes(c) && await ue(e, c, i, n, s) || // in case if wallet was connected, but extension's auth access is not present, // localStorage entry still exists and we're trying to establish connection again ee(e, c, i, n, t, s) ] ); return Object.fromEntries(await Promise.all(o)); }; function qe() { const e = new URLSearchParams(window.location.hash.slice(1)); return e.has("tgWebAppPlatform") && e.has("tgWebAppVersion"); } const Ke = { wallets: void 0, account: void 0, isAnyWallet: !1, isAccountReady: !1, login: () => { }, logout: () => { } }, le = $(Ke), { Provider: $e } = le, T = () => J(le); function Rt({ appName: e, children: n }) { const [t, s] = w(), [r, o] = w(), c = O([]), i = Object.keys(t || {}).length > 0, a = !!t, u = (l) => { o(l), localStorage.setItem(L.ACCOUNT_ADDRESS, l.address); }, d = () => { o(void 0), localStorage.removeItem(L.ACCOUNT_ADDRESS); }, p = (l, g) => { s( (A) => A && { ...A, [l]: { ...A[l], accounts: g } } ), o((A) => { if (!A || l !== A.meta.source || !!g.length && g.some(({ address: v }) => v === A.address)) return A; }); }, m = (l, g) => s((A) => A && { ...A, [l]: g }), h = (l) => c.current.push(l); E(() => { qe() && Fe(Ve); const l = setTimeout(() => { He(e, p, m, h).then((g) => { s(g), o(We(g)); }); }, _e); return () => { clearTimeout(l), c.current.forEach((g) => g()), c.current = []; }; }, []); const f = k( () => ({ wallets: t, account: r, isAnyWallet: i, isAccountReady: a, login: u, logout: d }), [t, r, i, a] ); return /* @__PURE__ */ G($e, { value: f, children: n }); } function Tt(e) { const { api: n, isApiReady: t } = S(), s = P(), [r, o] = w(), c = r !== void 0; return E(() => { if (o(void 0), !t || !e) return; n.balance.findOut(e).then((a) => o(a)).catch(({ message: a }) => s.error(a)); const i = n.gearEvents.subscribeToBalanceChanges(e, (a) => o(a)); return () => { i.then((a) => a()); }; }, [t, e]), { balance: r, isBalanceReady: c }; } function bt() { const { api: e, isApiReady: n } = S(), [t] = n ? e.registry.chainDecimals : [0], s = n ? e.valuePerGas.toString() : "1000", r = new x(10).exponentiatedBy(t); return { balanceMultiplier: r, decimals: t, getChainBalanceValue: (d) => new x(d).multipliedBy(r), getChainGasValue: (d) => new x(d).multipliedBy(r).dividedBy(s).integerValue(x.ROUND_UP), getFormattedBalanceValue: (d) => new x(d).dividedBy(r), getFormattedGasValue: (d) => new x(d).multipliedBy(s).dividedBy(r), getFormattedBalance: (d) => { if (!n) throw new Error("API is not initialized"); const [p] = e.registry.chainTokens; return { value: Ge(d, { decimals: t, forceUnit: p, withSiFull: !1, withSi: !1, withUnit: p }), unit: p }; } }; } function de() { const { api: e, isApiReady: n } = S(); return D( async (s) => { if (!n) throw new Error("API is not initialized"); const { block: r } = await e.rpc.chain.getBlock(), o = r.header.number.toNumber(), c = e.consts.babe.expectedBlockTime.toNumber(), i = (s - o) * c; return Date.now() + i; }, [n, e] ); } function Ct(e) { const { isApiReady: n } = S(), t = P(), s = de(), [r, o] = w(); return E(() => { o(void 0), !(!n || e === void 0) && s(e).then((c) => o(c)).catch(({ message: c }) => t.error(c)); }, [n, e]), r === void 0 ? { blockTimestamp: r, isBlockTimestampReady: !1 } : { blockTimestamp: r, isBlockTimestampReady: !0 }; } function N(e, n) { const t = Be(e, n); return t.queryKey = e.queryKey, t; } function Vt({ address: e, watch: n, query: t }) { const { api: s, isApiReady: r } = S(), o = Y(), c = ["deriveBalancesAll", s?.provider.endpoint, e], i = () => { if (!r) throw new Error("API is not initialized"); if (!e) throw new Error("Address not found"); return s.derive.balances.all(e); }; return E(() => { if (!r || !e || !n) return; const a = s.derive.balances.all(e, (u) => { o.setQueryData(c, u); }); return () => { a.then((u) => u()); }; }, [s, e, n]), N({ ...t, queryKey: c, queryFn: i, enabled: r && !!e && (t?.enabled ?? !0) }); } function Ft({ address: e, watch: n, query: t }) { const { api: s, isApiReady: r } = S(), o = Y(), c = ["deriveStakingAccount", s?.provider.endpoint, e], i = () => { if (!r) throw new Error("API is not initialized"); if (!e) throw new Error("Address not found"); return s.derive.staking.account(e); }; return E(() => { if (!r || !e || !n) return; const a = s.derive.staking.account(e, void 0, (u) => { o.setQueryData(c, u); }); return () => { a.then((u) => u()); }; }, [s, e, n]), N({ ...t, queryKey: c, queryFn: i, enabled: r && !!e && (t?.enabled ?? !0) }); } function Dt(e, n, t) { const { api: s, isApiReady: r } = S(), { account: o } = T(); return (i, a = 0) => { if (!r) return Promise.reject(new Error("API is not initialized")); if (!o) return Promise.reject(new Error("No account address")); if (!e) return Promise.reject(new Error("No program source")); const { decodedAddress: u } = o, { isOtherPanicsAllowed: d = !1 } = t || {}; return s.program.calculateGas.initUpload(u, e, i, a, d, n); }; } function Je(e, n, t) { const { api: s, isApiReady: r } = S(), { account: o } = T(); return (i, a = 0) => { if (!r) return Promise.reject(new Error("API is not initialized")); if (!o) return Promise.reject(new Error("No account address")); if (!e) return Promise.reject(new Error("No program source")); const { decodedAddress: u } = o, { isOtherPanicsAllowed: d = !1 } = t || {}; return s.program.calculateGas.initCreate(u, e, i, a, d, n); }; } function Ye(e, n, t) { const { api: s, isApiReady: r } = S(), { account: o } = T(); return (i, a = 0) => { if (!r) return Promise.reject(new Error("API is not initialized")); if (!o) return Promise.reject(new Error("No account address")); if (!e) return Promise.reject(new Error("No program source")); const { decodedAddress: u } = o, { isOtherPanicsAllowed: d = !1 } = t || {}; return s.program.calculateGas.handle( u, e, i, a, d, n ); }; } function Gt(e, n, t) { const { api: s, isApiReady: r } = S(), { account: o } = T(); return (i, a = 0) => { if (!r) return Promise.reject(new Error("API is not initialized")); if (!o) return Promise.reject(new Error("No account address")); if (!e) return Promise.reject(new Error("No program source")); const { decodedAddress: u } = o, { isOtherPanicsAllowed: d = !1 } = t || {}; return s.program.calculateGas.reply(u, e, i, a, d, n); }; } var q = /* @__PURE__ */ ((e) => (e.Transfer = "Transfer", e.CodeSaved = "CodeSaved", e.ProgramChanged = "ProgramChanged", e.UserMessageSent = "UserMessageSent", e.UserMessageRead = "UserMessageRead", e.MessageQueued = "MessageQueued", e.MessagesDispatched = "MessagesDispatched", e.ExtrinsicFailed = "ExtrinsicFailed", e.ExtrinsicSuccess = "ExtrinsicSuccess", e))(q || {}), _ = /* @__PURE__ */ ((e) => (e.Ready = "Ready", e.InBlock = "InBlock", e.IsInvalid = "IsInvalid", e.Finalized = "Finalized", e))(_ || {}), W = /* @__PURE__ */ ((e) => (e.Success = "success", e.Failed = "failed", e.InProgress = "in progress", e))(W || {}), K = /* @__PURE__ */ ((e) => (e.SendReply = "gear.sendReply", e.SendMessage = "gear.sendMessage", e.ClaimMessage = "gear.claimValueFromMailbox", e.SubmitCode = "gear.submitCode", e.CreateProgram = "gear.createProgram", e.UploadProgram = "gear.uploadProgram", e))(K || {}), fe = /* @__PURE__ */ ((e) => (e.Unauthorized = "Unauthorized", e.InvalidParams = "Invalid method parameters", e.InvalidTransaction = "Transaction error. Status: isInvalid", e.InitFail = "Program initialization failed", e.NodeError = "Gear node error", e.LowBalance = "Invalid transaction. Account balance too low", e.PayloadError = "payload.toHex is not a function", e))(fe || {}); const ge = ({ waited: e, min_limit: n }, t) => { const s = new x(n.toString()), r = t || (e ? 1.1 : 1); return s.multipliedBy(r).toFixed(0); }, Bt = (e) => e.replace(/,/g, ""), me = (e, n) => { const { docs: t, method: s } = e.getExtrinsicFailedError(n); return `${s}: ${t}`; }, xt = (e) => new te().encodeAddress(e, se), Ot = (e) => Object.entries(e); function Xe() { const { api: e, isApiReady: n } = S(), t = P(), s = (o, c, i) => { if (!n) throw new Error("API is not initialized"); const { onError: a, onSuccess: u } = i || {}; o.forEach(({ event: d }) => { const { method: p, section: m } = d, h = { title: `${m}.${p}` }; p === q.ExtrinsicFailed ? (t.error(me(e, d), h), a && a()) : p === q.MessageQueued && (t.success("Success", h), u && u(c)); }); }; return (o) => { const { result: c, alertId: i, callbacks: a, programId: u } = o, { onError: d } = a || {}, { status: p, events: m } = c, { isReady: h, isInBlock: f, isFinalized: l, isInvalid: g } = p; h ? t.update(i, _.Ready) : f ? t.update(i, _.InBlock) : l ? (t.update(i, _.Finalized, X), s(m, u, a)) : g && (t.update(i, fe.InvalidTransaction, U), d && d()); }; } function Ze() { const e = P(); return { handleSignStatus: Xe(), handleInitStatus: (r) => { const { status: o, programId: c, onError: i } = r; o === W.Failed && (e.error(c, { title: "Program initialization" }), i && i()); }, handleError: (r) => { const { alertId: o, message: c, onError: i } = r; e.update(o, c, U), i && i(); } }; } const et = (e, n) => { let t; const s = async () => (await t)(); return new Promise((r) => { t = e.gearEvents.subscribeToGearEvent("ProgramChanged", ({ data: o }) => { o.id.eq(n) && (o.change.isActive ? r(W.Success) : o.change.isTerminated && r(W.Failed)); }); }).finally(s); }; function he(e, n, t, s) { const r = P(), { api: o, isApiReady: c } = S(), { account: i } = T(), { handleSignStatus: a, handleInitStatus: u, handleError: d } = Ze(); return (m, h, f) => { if (!c) return Promise.reject(new Error("API is not initialized")); if (!i) return Promise.reject(new Error("No account address")); if (!n) return Promise.reject(new Error("No program buffer")); const { value: l = 0, salt: g, onSuccess: A, onError: y } = f || {}, v = e === "upload", R = v ? "code" : "codeId", I = v ? K.UploadProgram : K.CreateProgram, C = { [R]: n, initPayload: m, gasLimit: h, value: l, salt: g }, V = { onSuccess: A, onError: y }, { address: M, signer: H } = i, { programId: b } = o.program[e](C, t, s), F = r.loading("SignIn", { title: I }), z = et(o, b); return o.program.signAndSend(M, { signer: H }, (B) => a({ result: B, callbacks: V, alertId: F, programId: b })).then(() => z).then((B) => u({ status: B, programId: b, onError: y })).catch(({ message: B }) => d({ message: B, alertId: F, onError: y })); }; } function Mt(e, n, t) { return he("upload", e, n, t); } function tt(e, n, t) { return he("create", e, n, t); } function Ut(e, n, t, s) { const { api: r } = S(), o = P(), [c, i] = w(), [a, u] = w(!0), [d, p] = w(""), m = t !== void 0, h = (l) => { !r || !e || !n || !m || (l && u(!1), r.programState.read({ programId: e, payload: t }, n).then((g) => g.toHuman()).then((g) => { i(g), s || u(!0); }).catch(({ message: g }) => p(g)).finally(() => { s && u(!0); })); }, f = ({ data: l }) => { l.stateChanges.toHuman().some((y) => y === e) && h(); }; return E(() => { if (!r || !e || !n || !m) return; const l = r.gearEvents.subscribeToGearEvent("MessagesDispatched", f); return () => { l.then((g) => g()); }; }, [r, e, n, t]), E(() => { h(!0), p(""); }, [r, e, n, t]), E(() => { d && o.error(d); }, [d]), { state: c, isStateRead: a, error: d }; } function Lt(e, n) { const { programId: t, wasm: s, programMetadata: r, functionName: o, payload: c, argument: i } = e, { api: a } = S(), u = P(), [d, p] = w(), [m, h] = w(!0), [f, l] = w(""), g = c !== void 0, A = i !== void 0, y = (R) => { !a || !t || !s || !r || !o || !A || !g || (R && h(!1), Re(s).then( (I) => a.programState.readUsingWasm( { programId: t, wasm: s, fn_name: o, argument: i, payload: c }, I, r ) ).then((I) => I.toHuman()).then((I) => { p(I), n || h(!0); }).catch(({ message: I }) => l(I)).finally(() => { n && h(!0); })); }, v = ({ data: R }) => { R.stateChanges.toHuman().some((V) => V === t) && y(); }; return E(() => { if (!a || !t || !s || !r || !o || !A || !g) return; const R = a.gearEvents.subscribeToGearEvent("MessagesDispatched", v); return () => { R.then((I) => I()); }; }, [a, t, s, r, o, i, c]), E(() => { y(!0), l(""); }, [a, t, s, r, o, i, c]), E(() => { f && u.error(f); }, [f]), { state: d, isStateRead: m, error: f }; } function nt(e, n, { disableAlerts: t, pair: s } = {}) { const { api: r, isApiReady: o } = S(), { account: c } = T(), i = P(), a = "gear.sendMessage", u = (m, h, f) => { if (!o) throw new Error("API is not initialized"); m.forEach(({ event: l }) => { const { method: g, section: A } = l; if (g === "MessageQueued") { t || i.success(`${A}.MessageQueued`); const y = l.data.id.toHex(); h && h(y); } else if (g === "ExtrinsicFailed") { const y = me(r, l); console.error(y), i.error(y, { title: a }), f && f(); } }); }, d = (m, h, f, l, g) => { const { status: A, events: y } = m, { isReady: v, isInBlock: R, isInvalid: I, isFinalized: C } = A; I ? h ? i.update(h, "Transaction error. Status: isInvalid", U) : i.error("Transaction error. Status: isInvalid") : v && h ? i.update(h, "Ready") : R ? (h && i.update(h, "In Block"), y.forEach(({ event: V }) => { if (V.method === "MessageQueued") { const M = V.data.id.toHex(); l && l(M); } })) : C && (h && i.update(h, "Finalized", X), u(y, f, g)); }; return async (m) => { if (!o) throw new Error("API is not initialized"); if (!c) throw new Error("No account address"); if (!n) throw new Error("Metadata not found"); const h = t ? "" : i.loading("Sign In", { title: a }), { payload: f, gasLimit: l, value: g = 0, voucherId: A, onSuccess: y, onInBlock: v, onError: R } = m, { address: I, signer: C } = c, V = { destination: e, payload: f, gasLimit: l, value: g }, M = "keepAlive" in m ? m.keepAlive : !1, H = { ...V, keepAlive: M }; try { const b = r.message.send(H, n), F = A ? r.voucher.call(A, { SendMessage: b }) : b, z = (B) => d(B, h, y, v, R); s ? await F.signAndSend(s, z) : await F.signAndSend(I, { signer: C }, z); } catch (b) { const F = b.message; console.error(b), h ? i.update(h, F, U) : i.error(F), R && R(); } }; } function pe() { const e = de(); return D( async (t) => { const s = await e(t), r = s > Date.now(); return { expirationTimestamp: s, isVoucherActive: r }; }, [e] ); } function kt(e) { const { isApiReady: n } = S(), t = P(), s = pe(), [r, o] = w(); return E(() => { o(void 0), !(!n || !e) && s(e).then((c) => o(c)).catch(({ message: c }) => t.error(c)); }, [n, e]), r === void 0 ? { expirationTimestamp: void 0, isVoucherActive: void 0, isVoucherStatusReady: !1 } : { ...r, isVoucherStatusReady: !0 }; } function Ae(e, n) { const { api: t, isApiReady: s } = S(), r = P(), [o, c] = w(), i = o !== void 0; return E(() => { c(void 0); const a = arguments.length > 1; !s || !e || a && !n || t.voucher.getAllForAccount(e, n).then((u) => c(u)).catch((u) => r.error(u instanceof Error ? u.message : String(u))); }, [s, t, e, n]), { vouchers: o, isEachVoucherReady: i }; } function jt(e) { const { account: n } = T(), t = arguments.length ? [n?.address, e] : [n?.address]; return Ae(...t); } function st(e, n) { const { vouchers: t } = Ae(e, n), s = k(() => Object.entries(t || {}), [t]), r = P(), o = pe(), [c, i] = w(), a = c !== void 0, u = async () => { for (const [, { expiry: d }] of s) { const { isVoucherActive: p } = await o(d); if (p) return !0; } return !1; }; return E(() => { i(void 0), s.length && u().then((d) => i(d)).catch(({ message: d }) => r.error(d)); }, [s, o]), { isAnyVoucherActive: c, isAnyVoucherActiveReady: a }; } function Nt(e) { const { account: n } = T(); return st(n?.address, e); } function rt(e, n) { const { api: t, isApiReady: s } = S(), r = P(), [o, c] = w(), i = o !== void 0; return E(() => { c(void 0), !(!e || !s || !n) && t.voucher.exists(n, e).then((a) => c(a)).catch(({ message: a }) => r.error(a)); }, [s, n, e]), { isVoucherExists: o, isVoucherExistsReady: i }; } function zt(e) { const { account: n } = T(); return rt(e, n?.decodedAddress); } function ot(e) { const { api: n, isApiReady: t } = S(), s = P(), [r, o] = w(), c = r !== void 0; return E(() => { o(void 0), !(!e || !t) && n.voucher.getAllIssuedByAccount(e).then((i) => o(i)).catch(({ message: i }) => s.error(i)); }, [e, n, t]), { vouchers: r, isEachVoucherReady: c }; } function _t() { const { account: e } = T(); return ot(e?.address); } function it(e, n) { const { api: t } = S(), s = P(), [r, o] = w(), c = r !== void 0; return E(() => { o(void 0), !(!t || !n || !e) && t.voucher.getDetails(n, e).then((i) => o(i)).catch((i) => s.error(i instanceof Error ? i.message : String(i))); }, [t, n, e]), { voucher: r, isVoucherReady: c }; } function Wt(e) { const { account: n } = T(); return it(e, n?.address); } function Qt(e, n, t = {}) { const { api: s, isApiReady: r } = S(), o = P(), c = Ye(e, n), i = nt(e, n, t); return (a) => { if (!r) throw new Error("API is not initialized"); const { payload: u, value: d, onError: p = () => { } } = a, m = "isMaxGasLimit" in t ? t.isMaxGasLimit : !1, h = "gasMultiplier" in t ? t.gasMultiplier : void 0; (m ? Promise.resolve(s.blockGasLimit) : c(u, d).then((l) => ge(l, h))).then((l) => i({ ...a, gasLimit: l })).catch(({ message: l }) => { o.error(l), p(); }); }; } function Ht(e, n) { const t = P(), s = tt(e, n), r = Je(e, n); return (o, c) => { const { onError: i = () => { } } = c || {}; r(o).then((a) => ge(a)).then((a) => s(o, a, c)).catch(({ message: a }) => { t.error(a), i(); }); }; } function ct({ program: e, serviceName: n, functionName: t }) { const { account: s } = T(), r = async ({ args: i, value: a, voucherId: u, account: d, gasLimit: p }) => { if (!e) throw new Error("Program is not found"); const m = e[n][t](...i); if (d) { const { addressOrPair: f, signerOptions: l } = d; m.withAccount(f, l); } else { if (!s) throw new Error("Account is not found"); const { address: f, signer: l } = s; m.withAccount(f, { signer: l }); } if (a !== void 0 && m.withValue(a), u && m.withVoucher(u), typeof p == "bigint") m.withGas(p); else { const { allowOtherPanics: f, increaseGas: l } = p || {}; await m.calculateGas(f, l); } const h = await m.transactionFee(); return { transaction: m, fee: h }; }, o = e && typeof e == "object" && "programId" in e ? e.programId : void 0, c = ne({ mutationKey: ["prepareTransaction", o, n, t], mutationFn: r }); return { prepareTransaction: c.mutate, prepareTransactionAsync: c.mutateAsync, ...c }; } function qt({ library: e, id: n, query: t }) { const { api: s, isApiReady: r } = S(), o = () => { if (!r) throw new Error("API is not initialized"); if (!n) throw new Error("Program ID is not found"); return new e(s, n); }; return N({ ...t, queryKey: ["program", e.toString(), n, s?.provider.endpoint], queryFn: o, enabled: r && !!n && (t?.enabled ?? !0) }); } function Kt({ program: e, serviceName: n, functionName: t, onData: s }) { const r = e && typeof e == "object" && "programId" in e ? e.programId : void 0; E(() => { if (!e) return; const o = e[n][t](s); return () => { o.then((c) => c()); }; }, [r, n, t]); } function $t({ program: e, serviceName: n, functionName: t, args: s, originAddress: r, value: o, gasLimit: c, atBlock: i, query: a, watch: u }) { const { api: d, isApiReady: p } = S(), m = Y(), { account: h } = T(), f = r || h?.decodedAddress, l = () => { if (!e) throw new Error("Program is not found"); const y = e[n][t]( ...s ); return f && y.withAddress(f), o && y.withValue(o), c && y.withGasLimit(c), i && y.atBlock(i), y.call(); }, g = e && typeof e == "object" && "programId" in e ? e.programId : void 0, A = k( () => [ "query", g, f, n, // TODO: can we remove this cast by giving TProgram some type to extend? t, JSON.stringify(s), // stringify for types consistency, is it a good practice? o?.toString(), c?.toString(), i ], [g, f, n, t, s, o, c, i] ); return E(() => { if (!p || !u) return; const y = d.gearEvents.subscribeToGearEvent("MessagesDispatched", ({ data: v }) => { v.stateChanges.toHuman().some((C) => C === g) && m.invalidateQueries({ queryKey: A }); }); return () => { y.then((v) => v()); }; }, [d, g, u]), N({ ...a, queryKey: A, queryFn: l, enabled: !!e && (a?.enabled ?? !0) }); } const at = { programId: void 0, idl: void 0, query: {} }; function Jt({ programId: e, idl: n, query: t } = at) { const { api: s, isApiReady: r } = S(), o = async () => { if (!r) throw new Error("API is not initialized"); const c = await Oe.new(), i = new xe(c); return i.setApi(s), e && i.setProgramId(e), n && i.parseIdl(n), i; }; return N({ ...t, queryKey: ["sails", s?.provider.endpoint, e, n], queryFn: o, enabled: r && (t?.enabled ?? !0) }); } function Yt({ program: e, serviceName: n, functionName: t }) { const { prepareTransactionAsync: s } = ct({ program: e, serviceName: n, functionName: t }), r = async ({ awaitFinalization: i, ...a }) => { const { transaction: u } = "transaction" in a ? a : await s(a), { blockHash: d, msgId: p, isFinalized: m, txHash: h, response: f } = await u.signAndSend(), l = await f(), g = i ? await m : m; return { response: l, isFinalized: g, blockHash: d, msgId: p, txHash: h }; }, o = e && typeof e == "object" && "programId" in e ? e.programId : void 0, c = ne({ mutationKey: ["sendTransaction", o, n, t], mutationFn: r }); return { sendTransaction: c.mutate, sendTransactionAsync: c.mutateAsync, ...c }; } export { Rt as AccountProvider, It as AlertProvider, j as AlertType, Pt as ApiProvider, en as BigNumber, U as DEFAULT_ERROR_OPTIONS, Me as DEFAULT_INFO_OPTIONS, Ue as DEFAULT_LOADING_OPTIONS, Q as DEFAULT_OPTIONS, X as DEFAULT_SUCCESS_OPTIONS, se as VARA_SS58_FORMAT, ce as WALLET_STATUS, Ot as getTypedEntries, xt as getVaraAddress, T as useAccount, _t as useAccountIssuedVouchers, Wt as useAccountVoucher, jt as useAccountVouchers, P as useAlert, S as useApi, Ct as useApproxBlockTimestamp, Tt as useBalance, bt as useBalanceFormat, Je as useCreateCalculateGas, Ht as useCreateHandler, tt as useCreateProgram, Vt as useDeriveBalancesAll, Ft as useDeriveStakingAccount, de as useGetApproxBlockTimestamp, pe as useGetVoucherStatus, Ye as useHandleCalculateGas, zt as useIsAccountVoucherExists, Nt as useIsAnyAccountVoucherActive, st as useIsAnyVoucherActive, rt as useIsVoucherExists, ot as useIssuedVouchers, ct as usePrepareProgramTransaction, qt as useProgram, Kt as useProgramEvent, $t as useProgramQuery, Ut as useReadFullState, Lt as useReadWasmState, Gt as useReplyCalculateGas, Jt as useSails, nt as useSendMessage, Qt as useSendMessageWithGas, Yt as useSendProgramTransaction, Dt as useUploadCalculateGas, Mt as useUploadProgram, it as useVoucher, kt as useVoucherStatus, Ae as useVouchers, Bt as withoutCommas };