@galacticcouncil/common 0.4.1 → 0.5.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.
package/build/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Q=Object.create;var y=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty;var s=(e,t)=>{for(var r in t)y(e,r,{get:t[r],enumerable:!0})},U=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ee(t))!te.call(e,o)&&o!==r&&y(e,o,{get:()=>t[o],enumerable:!(n=Z(t,o))||n.enumerable});return e};var ne=(e,t,r)=>(r=e!=null?Q(re(e)):{},U(t||!e||!e.__esModule?y(r,"default",{value:e,enumerable:!0}):r,e)),oe=e=>U(y({},"__esModule",{value:!0}),e);var xe={};s(xe,{HYDRATION_SS58_PREFIX:()=>h,RUNTIME_DECIMALS:()=>Ae,big:()=>v,encodeAssetId:()=>C,encodeLocation:()=>H,enums:()=>w,erc20:()=>R,h160:()=>D,hex:()=>N,log:()=>F,meta:()=>G,transform:()=>i,xc:()=>T,xcm:()=>O});module.exports=oe(xe);var Ae=18,h=63;var v={};s(v,{asBigInt:()=>ie,convertDecimals:()=>se,pow10:()=>ue,toBigInt:()=>P,toDecimal:()=>_});var c=ne(require("big.js"));c.default.NE=-18;function _(e,t,r){let n=(0,c.default)(e.toString().replace(/[^0-9]/g,"")),o=(0,c.default)(10).pow(t);return n.div(o).round(t,r).toString()}function P(e,t){if(typeof e=="bigint")return e;let r=(0,c.default)(10).pow(t),n=(0,c.default)(e).mul(r);return BigInt(n.toFixed(0,c.default.roundDown))}function ie(e){return BigInt(e.round(0,c.default.roundDown).toFixed(0))}function se(e,t,r){let n=_(e,t);return P(n.toString(),r)}function ue(e){if(e<0)throw new Error(`pow10: negative exp ${e}`);return 10n**BigInt(e)}var w={};s(w,{enumPath:()=>ce});function ce(e){let t=[],r=e;for(;r&&typeof r=="object"&&"type"in r;)t.push(r.type),r=r.value;return t.join(".")}var R={};s(R,{ERC20:()=>I});var I=class{static fromAssetId(t){let r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(t){let r=Buffer.from(t.replace("0x",""),"hex");return r.length!==20||!this.isAssetAddress(t)?null:r.readUInt32BE(16)}static isAssetAddress(t){let r=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(r.subarray(0,16))}};var D={};s(D,{H160:()=>S,isEvmAccount:()=>M,isEvmAddress:()=>X,isSs58Address:()=>K});var d=require("polkadot-api"),L=require("@polkadot-api/utils"),u=require("buffer");var k="ETH\0";function M(e){if(!e)return!1;try{let t=(0,d.AccountId)().enc(e),r=u.Buffer.from(k);return u.Buffer.from(t.subarray(0,r.length)).equals(r)}catch{return!1}}function X(e){return!!/^0x[a-fA-F0-9]{40}$/.test(e)}function K(e){try{return(0,d.AccountId)(63).enc(e),!0}catch{return!1}}var S=class e{static toAccount=t=>{let r=u.Buffer.from(t.slice(2),"hex"),n=u.Buffer.from(k),o=Uint8Array.from(u.Buffer.concat([n,r,u.Buffer.alloc(8)])),m=(0,L.toHex)(o);return(0,d.AccountId)(63).dec(m)};static fromAccount=t=>{let r=(0,d.AccountId)().enc(t),n=u.Buffer.from(k),o=r.slice(n.length,-8);return"0x"+u.Buffer.from(o).toString("hex")};static fromSS58=t=>{let n=(0,d.AccountId)().enc(t).slice(0,20);return(0,L.toHex)(n)};static fromAny=t=>{if(X(t))return t;if(M(t))return e.fromAccount(t);if(K(t))return e.fromSS58(t);throw new Error("Unknown address type")}};var N={};s(N,{assertHexLen:()=>le,ensureHexPrefix:()=>$,hexNormalize:()=>de,isHex:()=>W,stripHexPrefix:()=>ae});var fe=/^0x[0-9a-fA-F]*$/;function W(e,t=!1){return e==="0x"?!0:!fe.test(e)||!t&&e.length<4?!1:t||e.length%2===0}function ae(e){return e.startsWith("0x")?e.slice(2):e}function $(e){return e.startsWith("0x")?e:`0x${e}`}function de(e){return $(e.toLowerCase())}function le(e,t){if(!W(e)||e.length-2!==t*2)throw new Error(`Expected 0x hex of ${t} bytes`)}var F={};s(F,{logger:()=>ge});var x={all:0,trace:1,debug:2,info:3,warn:4,error:5,silent:6};function l(e){return e.padEnd(11)}var p={TRACE:l("[GC][TRACE]"),DEBUG:l("[GC][DEBUG]"),INFO:l("[GC][INFO]"),WARN:l("[GC][WARN]"),ERROR:l("[GC][ERROR]")};function pe(){if(typeof window<"u")try{let e=window.localStorage.getItem("gc.log");if(e&&e in x)return e}catch{}if(typeof process<"u"){let e=process.env.GC_LOG;if(e&&e in x)return e}return"silent"}function g(e){let t=pe();return x[e]>=x[t]}var ge={trace(...e){g("trace")&&console.debug(p.TRACE,...e)},debug(...e){g("debug")&&console.debug(p.DEBUG,...e)},info(...e){g("info")&&console.info(p.INFO,...e)},warn(...e){g("warn")&&console.warn(p.WARN,...e)},error(...e){if(!g("error"))return;e.some(r=>r instanceof Error)?console.error(p.ERROR,...e):this.warn(...e)}};var G={};s(G,{ErrorDecoder:()=>me});var B=require("@polkadot-api/substrate-bindings");function me(e){let{metadata:t}=B.metadata.dec(e),{pallets:r,lookup:n}=t.value,o=new Map(r.map(f=>[f.index,f])),m=new Map(n.map(f=>[f.id,f]));return{decode(f,z){let A=o.get(f);if(!A?.errors)return;let E=m.get(A.errors);if(!E||E.def.tag!=="variant")return;let Y=B.u32.dec(z),b=E.def.value.find(J=>J.index===Y);if(b)return{pallet:A.name,error:b.name,desc:b.docs[0]}}}}var O={};s(O,{encodeAssetId:()=>C,encodeLocation:()=>H,toAccountId32:()=>j,toAccountKey20:()=>V,transform:()=>i});var a=require("polkadot-api"),j=e=>{let t=(0,a.AccountId)().enc(e);return{type:"AccountId32",value:{network:void 0,id:a.FixedSizeBinary.fromBytes(t)}}},V=e=>({type:"AccountKey20",value:{network:void 0,key:a.FixedSizeBinary.fromHex(e)}}),i=e=>{if(Array.isArray(e))return e.map(i);if(typeof e=="object"&&e!==null){let t=Object.keys(e);if(t.length===1){let r=t[0],n=e[r];if(r==="AccountKey20"&&typeof n=="object"){let o=V(n.key);return n.network&&(o.value.network=i(n.network)),o}if(r==="AccountId32"&&typeof n=="object"){let o=j(n.id);return n.network&&(o.value.network=i(n.network)),o}return r==="GeneralKey"&&typeof n=="object"&&"data"in n?{type:r,value:{length:n.length,data:typeof n.data=="string"?a.Binary.fromHex(n.data):n.data}}:r==="GlobalConsensus"&&typeof n=="object"&&("Polkadot"in n||"Kusama"in n)?{type:r,value:n}:r==="Ethereum"?{type:r,value:{chain_id:BigInt("chainId"in n?n.chainId:n.chain_id)}}:r==="PalletInstance"?{type:r,value:n}:r==="GeneralIndex"?{type:r,value:BigInt(n)}:r==="X1"&&Array.isArray(n)?{type:r,value:n.length===1?i(n[0]):n.map(i)}:typeof n=="string"?{type:r,value:{type:n}}:typeof n=="number"?{type:r,value:n}:{type:r,value:i(n)}}else{let r={};for(let n of t){let o=e[n];r[n]=i(o)}return r}}else return e};function H(e){if(!e||typeof e!="object")return e;let{parents:t,interior:r}=e;return!r||r==="Here"?{parents:t,interior:{type:"Here"}}:{parents:t,interior:i(r)}}function C(e){return e==null?e:typeof e=="string"?BigInt(e):typeof e=="object"&&!Array.isArray(e)?i(e):e}var T={};s(T,{convertToId:()=>ye});var q=require("buffer");function ye(e){let r=q.Buffer.from(e.replace("0x",""),"hex").subarray(16);return r.readUIntBE(0,r.length)}0&&(module.exports={HYDRATION_SS58_PREFIX,RUNTIME_DECIMALS,big,encodeAssetId,encodeLocation,enums,erc20,h160,hex,log,meta,transform,xc,xcm});
1
+ "use strict";var ce=Object.create;var w=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var le=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var u=(e,t)=>{for(var r in t)w(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fe(t))!de.call(e,o)&&o!==r&&w(e,o,{get:()=>t[o],enumerable:!(n=ue(t,o))||n.enumerable});return e};var pe=(e,t,r)=>(r=e!=null?ce(le(e)):{},V(t||!e||!e.__esModule?w(r,"default",{value:e,enumerable:!0}):r,e)),ge=e=>V(w({},"__esModule",{value:!0}),e);var Re={};u(Re,{HYDRATION_SS58_PREFIX:()=>S,RUNTIME_DECIMALS:()=>ke,SubstrateApis:()=>j,acc:()=>R,big:()=>H,blockProbe$:()=>X,encodeAssetId:()=>G,encodeLocation:()=>F,enums:()=>k,erc20:()=>L,h160:()=>M,hex:()=>N,log:()=>T,meta:()=>D,transform:()=>c,xc:()=>$,xcm:()=>W});module.exports=ge(Re);var ke=18,S=63;var R={};u(R,{getMultilocationDerivatedAccount:()=>me,getSovereignAccounts:()=>he});var f=require("@polkadot-api/substrate-bindings"),C=require("@polkadot-api/utils");function me(e,t,r,n=!1){let o=t.length===42,s=o?"AccountKey20":"AccountId32",i;if(o)i=(0,C.fromHex)(t.slice(2));else{let b=(0,f.getSs58AddressInfo)(t);if(!b.isValid)throw new Error("Invalid SS58 address");i=b.publicKey}let m="SiblingChain";r==0&&e?m="ChildChain":r==1&&!e&&(m="ParentChain");let l=f.compactNumber.enc,x=new Uint8Array([...new TextEncoder().encode(m),...e?l(e):[],...l(s.length+(o?20:32)),...new TextEncoder().encode(s),...i]),h=(0,f.Blake2256)(x);return n?(0,C.toHex)(h.slice(0,20)):(0,f.AccountId)().dec(h)}function he(e){let t=f.u32.enc(e),r=new TextEncoder().encode("para"),n=new TextEncoder().encode("sibl"),o=(0,C.toHex)(new Uint8Array([...r,...t])).padEnd(66,"0"),s=(0,C.toHex)(new Uint8Array([...n,...t])).padEnd(66,"0"),i=s.slice(0,42);return{generic:s,moonbeam:i,relay:o}}var H={};u(H,{asBigInt:()=>be,convertDecimals:()=>ye,pow10:()=>xe,toBigInt:()=>z,toDecimal:()=>q});var g=pe(require("big.js"));g.default.NE=-18;function q(e,t,r){let n=(0,g.default)(e.toString().replace(/[^0-9]/g,"")),o=(0,g.default)(10).pow(t);return n.div(o).round(t,r).toString()}function z(e,t){if(typeof e=="bigint")return e;let r=(0,g.default)(10).pow(t),n=(0,g.default)(e).mul(r);return BigInt(n.toFixed(0,g.default.roundDown))}function be(e){return BigInt(e.round(0,g.default.roundDown).toFixed(0))}function ye(e,t,r){let n=q(e,t);return z(n.toString(),r)}function xe(e){if(e<0)throw new Error(`pow10: negative exp ${e}`);return 10n**BigInt(e)}var k={};u(k,{enumPath:()=>Ce});function Ce(e){let t=[],r=e;for(;r&&typeof r=="object"&&"type"in r;)t.push(r.type),r=r.value;return t.join(".")}var L={};u(L,{ERC20:()=>_});var _=class{static fromAssetId(t){let r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(t){let r=Buffer.from(t.replace("0x",""),"hex");return r.length!==20||!this.isAssetAddress(t)?null:r.readUInt32BE(16)}static isAssetAddress(t){let r=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(r.subarray(0,16))}};var M={};u(M,{H160:()=>K,isEvmAccount:()=>Y,isEvmAddress:()=>J,isSs58Address:()=>Q});var v=require("polkadot-api"),O=require("@polkadot-api/utils"),d=require("buffer");var U="ETH\0";function Y(e){if(!e)return!1;try{let t=(0,v.AccountId)().enc(e),r=d.Buffer.from(U);return d.Buffer.from(t.subarray(0,r.length)).equals(r)}catch{return!1}}function J(e){return!!/^0x[a-fA-F0-9]{40}$/.test(e)}function Q(e){try{return(0,v.AccountId)(63).enc(e),!0}catch{return!1}}var K=class e{static toAccount=t=>{let r=d.Buffer.from(t.slice(2),"hex"),n=d.Buffer.from(U),o=Uint8Array.from(d.Buffer.concat([n,r,d.Buffer.alloc(8)])),s=(0,O.toHex)(o);return(0,v.AccountId)(63).dec(s)};static fromAccount=t=>{let r=(0,v.AccountId)().enc(t),n=d.Buffer.from(U),o=r.slice(n.length,-8);return"0x"+d.Buffer.from(o).toString("hex")};static fromSS58=t=>{let n=(0,v.AccountId)().enc(t).slice(0,20);return(0,O.toHex)(n)};static fromAny=t=>{if(J(t))return t;if(Y(t))return e.fromAccount(t);if(Q(t))return e.fromSS58(t);throw new Error("Unknown address type")}};var N={};u(N,{assertHexLen:()=>Ee,ensureHexPrefix:()=>ee,hexNormalize:()=>Pe,isHex:()=>Z,stripHexPrefix:()=>Ae});var ve=/^0x[0-9a-fA-F]*$/;function Z(e,t=!1){return e==="0x"?!0:!ve.test(e)||!t&&e.length<4?!1:t||e.length%2===0}function Ae(e){return e.startsWith("0x")?e.slice(2):e}function ee(e){return e.startsWith("0x")?e:`0x${e}`}function Pe(e){return ee(e.toLowerCase())}function Ee(e,t){if(!Z(e)||e.length-2!==t*2)throw new Error(`Expected 0x hex of ${t} bytes`)}var T={};u(T,{logger:()=>Be});var B={all:0,trace:1,debug:2,info:3,warn:4,error:5,silent:6};function A(e){return e.padEnd(11)}var P={TRACE:A("[GC][TRACE]"),DEBUG:A("[GC][DEBUG]"),INFO:A("[GC][INFO]"),WARN:A("[GC][WARN]"),ERROR:A("[GC][ERROR]")};function we(){if(typeof window<"u")try{let e=window.localStorage.getItem("gc.log");if(e&&e in B)return e}catch{}if(typeof process<"u"){let e=process.env.GC_LOG;if(e&&e in B)return e}return"silent"}function E(e){let t=we();return B[e]>=B[t]}var Be={trace(...e){E("trace")&&console.debug(P.TRACE,...e)},debug(...e){E("debug")&&console.debug(P.DEBUG,...e)},info(...e){E("info")&&console.info(P.INFO,...e)},warn(...e){E("warn")&&console.warn(P.WARN,...e)},error(...e){if(!E("error"))return;e.some(r=>r instanceof Error)?console.error(P.ERROR,...e):this.warn(...e)}};var D={};u(D,{ErrorDecoder:()=>Ie});var I=require("@polkadot-api/substrate-bindings");function Ie(e){let{metadata:t}=I.metadata.dec(e),{pallets:r,lookup:n}=t.value,o=new Map(r.map(i=>[i.index,i])),s=new Map(n.map(i=>[i.id,i]));return{decode(i,m){let l=o.get(i);if(!l?.errors)return;let x=s.get(l.errors);if(!x||x.def.tag!=="variant")return;let h=I.u32.dec(m),b=x.def.value.find(ae=>ae.index===h);if(b)return{pallet:l.name,error:b.name,desc:b.docs[0]}}}}var W={};u(W,{encodeAssetId:()=>G,encodeLocation:()=>F,toAccountId32:()=>te,toAccountKey20:()=>re,transform:()=>c});var y=require("polkadot-api"),te=e=>{let t=(0,y.AccountId)().enc(e);return{type:"AccountId32",value:{network:void 0,id:y.FixedSizeBinary.fromBytes(t)}}},re=e=>({type:"AccountKey20",value:{network:void 0,key:y.FixedSizeBinary.fromHex(e)}}),c=e=>{if(Array.isArray(e))return e.map(c);if(typeof e=="object"&&e!==null){let t=Object.keys(e);if(t.length===1){let r=t[0],n=e[r];if(r==="AccountKey20"&&typeof n=="object"){let o=re(n.key);return n.network&&(o.value.network=c(n.network)),o}if(r==="AccountId32"&&typeof n=="object"){let o=te(n.id);return n.network&&(o.value.network=c(n.network)),o}return r==="GeneralKey"&&typeof n=="object"&&"data"in n?{type:r,value:{length:n.length,data:typeof n.data=="string"?y.Binary.fromHex(n.data):n.data}}:r==="GlobalConsensus"&&typeof n=="object"&&("Polkadot"in n||"Kusama"in n)?{type:r,value:n}:r==="Ethereum"?{type:r,value:{chain_id:BigInt("chainId"in n?n.chainId:n.chain_id)}}:r==="PalletInstance"?{type:r,value:n}:r==="GeneralIndex"?{type:r,value:BigInt(n)}:r==="X1"&&Array.isArray(n)?{type:r,value:n.length===1?c(n[0]):n.map(c)}:typeof n=="string"?{type:r,value:{type:n}}:typeof n=="number"?{type:r,value:n}:{type:r,value:c(n)}}else{let r={};for(let n of t){let o=e[n];r[n]=c(o)}return r}}else return e};function F(e){if(!e||typeof e!="object")return e;let{parents:t,interior:r}=e;return!r||r==="Here"?{parents:t,interior:{type:"Here"}}:{parents:t,interior:c(r)}}function G(e){return e==null?e:typeof e=="string"?BigInt(e):typeof e=="object"&&!Array.isArray(e)?c(e):e}var $={};u($,{convertToId:()=>Se});var ne=require("buffer");function Se(e){let r=ne.Buffer.from(e.replace("0x",""),"hex").subarray(16);return r.readUIntBE(0,r.length)}var oe=require("polkadot-api"),ie=require("polkadot-api/ws-provider"),se=require("lru-cache");var p=require("rxjs"),a=require("rxjs/operators");function X(e,{intervalMs:t=5e3,timeoutMs:r=5e3,staleThreshold:n=3}={}){let o=i=>(0,p.defer)(()=>(0,p.from)(e._request("chain_getHeader",[]))).pipe((0,a.timeout)({first:r}),(0,a.map)(m=>{let l=parseInt(m.number,16),h=i.blockNumber!==void 0&&l<=i.blockNumber?i.staleCount+1:0;return{state:h>=n?"stale":"healthy",blockNumber:l,staleCount:h,delayMs:t}}),(0,a.catchError)(()=>(0,p.of)({state:"stale",staleCount:0,delayMs:t})));return(0,p.of)({state:"healthy",staleCount:0,delayMs:0}).pipe((0,a.expand)(i=>(0,p.timer)(i.delayMs).pipe((0,a.switchMap)(()=>o(i)))),(0,a.skip)(1),(0,a.map)(i=>i.state),(0,a.distinctUntilChanged)(),(0,a.shareReplay)({bufferSize:1,refCount:!0}))}var j=class e{static _instance=new e;_cache=new se.LRUCache({max:40});_metadataCache;constructor(){if(e._instance)throw new Error("Use SubstrateApis.getInstance() instead of new.");e._instance=this}static getInstance(){return e._instance}configureMetadataCache(t){this._metadataCache=t}createCacheKey(t){return t.join(",")}findCacheKey(t){let r=t.find(o=>this._cache.has(o));if(r)return r;let n=this.createCacheKey(t);return this._cache.has(n)?n:null}createClient(t,r){let n=(0,ie.getWsProvider)(t,r?.wsProviderOpts),o=(0,oe.createClient)(n,this._metadataCache),s=this.createCacheKey(t);console.log(`Created PAPI client for ${s}`);let i={client:o,provider:n,endpoints:t,currentEndpointIndex:0};return this._cache.set(s,i,{noDisposeOnSet:!0}),r?.probeConfig?.enabled!==!1&&this.startHealthProbe(i,r?.probeConfig),o}api(t,r){let n=typeof t=="string"?t.split(","):t,o=this.findCacheKey(n);return o?this._cache.get(o).client:this.createClient(n,r)}release(){for(let[t,r]of this._cache.entries())this.stopHealthProbe(r),console.log("Releasing "+t),r.client.destroy();this._cache.clear()}configureHealthProbe(t,r){let n=typeof t=="string"?t.split(","):t,o=this.findCacheKey(n);if(o){let s=this._cache.get(o);this.stopHealthProbe(s),r.enabled!==!1&&this.startHealthProbe(s,r)}}startHealthProbe(t,r={}){let n=o=>{if(t.endpoints.length>1){let s=(t.currentEndpointIndex+1)%t.endpoints.length,i=t.endpoints[s];console.log(`${o} on ${t.endpoints[t.currentEndpointIndex]}, switching to ${i}`),t.provider.switch(i),t.currentEndpointIndex=s,this.stopHealthProbe(t),this.startHealthProbe(t,r)}};t.probeSubscription=X(t.client,r).subscribe({next:o=>{o==="stale"&&n("RPC stale")}})}stopHealthProbe(t){t.probeSubscription&&(t.probeSubscription.unsubscribe(),t.probeSubscription=void 0)}getWs(t){let r=typeof t=="string"?t.split(","):t,n=this.findCacheKey(r);if(n)return this._cache.get(n)?.provider}};0&&(module.exports={HYDRATION_SS58_PREFIX,RUNTIME_DECIMALS,SubstrateApis,acc,big,blockProbe$,encodeAssetId,encodeLocation,enums,erc20,h160,hex,log,meta,transform,xc,xcm});
package/build/index.mjs CHANGED
@@ -1 +1 @@
1
- var q=Object.defineProperty;var s=(e,t)=>{for(var r in t)q(e,r,{get:t[r],enumerable:!0})};var pe=18,A=63;var I={};s(I,{asBigInt:()=>z,convertDecimals:()=>Y,pow10:()=>J,toBigInt:()=>w,toDecimal:()=>v});import f from"big.js";f.NE=-18;function v(e,t,r){let n=f(e.toString().replace(/[^0-9]/g,"")),o=f(10).pow(t);return n.div(o).round(t,r).toString()}function w(e,t){if(typeof e=="bigint")return e;let r=f(10).pow(t),n=f(e).mul(r);return BigInt(n.toFixed(0,f.roundDown))}function z(e){return BigInt(e.round(0,f.roundDown).toFixed(0))}function Y(e,t,r){let n=v(e,t);return w(n.toString(),r)}function J(e){if(e<0)throw new Error(`pow10: negative exp ${e}`);return 10n**BigInt(e)}var R={};s(R,{enumPath:()=>Q});function Q(e){let t=[],r=e;for(;r&&typeof r=="object"&&"type"in r;)t.push(r.type),r=r.value;return t.join(".")}var L={};s(L,{ERC20:()=>E});var E=class{static fromAssetId(t){let r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(t){let r=Buffer.from(t.replace("0x",""),"hex");return r.length!==20||!this.isAssetAddress(t)?null:r.readUInt32BE(16)}static isAssetAddress(t){let r=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(r.subarray(0,16))}};var F={};s(F,{H160:()=>h,isEvmAccount:()=>S,isEvmAddress:()=>D,isSs58Address:()=>N});import{AccountId as a}from"polkadot-api";import{toHex as k}from"@polkadot-api/utils";import{Buffer as u}from"buffer";var b="ETH\0";function S(e){if(!e)return!1;try{let t=a().enc(e),r=u.from(b);return u.from(t.subarray(0,r.length)).equals(r)}catch{return!1}}function D(e){return!!/^0x[a-fA-F0-9]{40}$/.test(e)}function N(e){try{return a(63).enc(e),!0}catch{return!1}}var h=class e{static toAccount=t=>{let r=u.from(t.slice(2),"hex"),n=u.from(b),o=Uint8Array.from(u.concat([n,r,u.alloc(8)])),g=k(o);return a(63).dec(g)};static fromAccount=t=>{let r=a().enc(t),n=u.from(b),o=r.slice(n.length,-8);return"0x"+u.from(o).toString("hex")};static fromSS58=t=>{let n=a().enc(t).slice(0,20);return k(n)};static fromAny=t=>{if(D(t))return t;if(S(t))return e.fromAccount(t);if(N(t))return e.fromSS58(t);throw new Error("Unknown address type")}};var C={};s(C,{assertHexLen:()=>te,ensureHexPrefix:()=>H,hexNormalize:()=>re,isHex:()=>G,stripHexPrefix:()=>ee});var Z=/^0x[0-9a-fA-F]*$/;function G(e,t=!1){return e==="0x"?!0:!Z.test(e)||!t&&e.length<4?!1:t||e.length%2===0}function ee(e){return e.startsWith("0x")?e.slice(2):e}function H(e){return e.startsWith("0x")?e:`0x${e}`}function re(e){return H(e.toLowerCase())}function te(e,t){if(!G(e)||e.length-2!==t*2)throw new Error(`Expected 0x hex of ${t} bytes`)}var O={};s(O,{logger:()=>oe});var m={all:0,trace:1,debug:2,info:3,warn:4,error:5,silent:6};function d(e){return e.padEnd(11)}var l={TRACE:d("[GC][TRACE]"),DEBUG:d("[GC][DEBUG]"),INFO:d("[GC][INFO]"),WARN:d("[GC][WARN]"),ERROR:d("[GC][ERROR]")};function ne(){if(typeof window<"u")try{let e=window.localStorage.getItem("gc.log");if(e&&e in m)return e}catch{}if(typeof process<"u"){let e=process.env.GC_LOG;if(e&&e in m)return e}return"silent"}function p(e){let t=ne();return m[e]>=m[t]}var oe={trace(...e){p("trace")&&console.debug(l.TRACE,...e)},debug(...e){p("debug")&&console.debug(l.DEBUG,...e)},info(...e){p("info")&&console.info(l.INFO,...e)},warn(...e){p("warn")&&console.warn(l.WARN,...e)},error(...e){if(!p("error"))return;e.some(r=>r instanceof Error)?console.error(l.ERROR,...e):this.warn(...e)}};var T={};s(T,{ErrorDecoder:()=>ue});import{metadata as ie,u32 as se}from"@polkadot-api/substrate-bindings";function ue(e){let{metadata:t}=ie.dec(e),{pallets:r,lookup:n}=t.value,o=new Map(r.map(c=>[c.index,c])),g=new Map(n.map(c=>[c.id,c]));return{decode(c,$){let y=o.get(c);if(!y?.errors)return;let x=g.get(y.errors);if(!x||x.def.tag!=="variant")return;let j=se.dec($),B=x.def.value.find(V=>V.index===j);if(B)return{pallet:y.name,error:B.name,desc:B.docs[0]}}}}var K={};s(K,{encodeAssetId:()=>X,encodeLocation:()=>M,toAccountId32:()=>_,toAccountKey20:()=>P,transform:()=>i});import{AccountId as ce,Binary as fe,FixedSizeBinary as U}from"polkadot-api";var _=e=>{let t=ce().enc(e);return{type:"AccountId32",value:{network:void 0,id:U.fromBytes(t)}}},P=e=>({type:"AccountKey20",value:{network:void 0,key:U.fromHex(e)}}),i=e=>{if(Array.isArray(e))return e.map(i);if(typeof e=="object"&&e!==null){let t=Object.keys(e);if(t.length===1){let r=t[0],n=e[r];if(r==="AccountKey20"&&typeof n=="object"){let o=P(n.key);return n.network&&(o.value.network=i(n.network)),o}if(r==="AccountId32"&&typeof n=="object"){let o=_(n.id);return n.network&&(o.value.network=i(n.network)),o}return r==="GeneralKey"&&typeof n=="object"&&"data"in n?{type:r,value:{length:n.length,data:typeof n.data=="string"?fe.fromHex(n.data):n.data}}:r==="GlobalConsensus"&&typeof n=="object"&&("Polkadot"in n||"Kusama"in n)?{type:r,value:n}:r==="Ethereum"?{type:r,value:{chain_id:BigInt("chainId"in n?n.chainId:n.chain_id)}}:r==="PalletInstance"?{type:r,value:n}:r==="GeneralIndex"?{type:r,value:BigInt(n)}:r==="X1"&&Array.isArray(n)?{type:r,value:n.length===1?i(n[0]):n.map(i)}:typeof n=="string"?{type:r,value:{type:n}}:typeof n=="number"?{type:r,value:n}:{type:r,value:i(n)}}else{let r={};for(let n of t){let o=e[n];r[n]=i(o)}return r}}else return e};function M(e){if(!e||typeof e!="object")return e;let{parents:t,interior:r}=e;return!r||r==="Here"?{parents:t,interior:{type:"Here"}}:{parents:t,interior:i(r)}}function X(e){return e==null?e:typeof e=="string"?BigInt(e):typeof e=="object"&&!Array.isArray(e)?i(e):e}var W={};s(W,{convertToId:()=>de});import{Buffer as ae}from"buffer";function de(e){let r=ae.from(e.replace("0x",""),"hex").subarray(16);return r.readUIntBE(0,r.length)}export{A as HYDRATION_SS58_PREFIX,pe as RUNTIME_DECIMALS,I as big,X as encodeAssetId,M as encodeLocation,R as enums,L as erc20,F as h160,C as hex,O as log,T as meta,i as transform,W as xc,K as xcm};
1
+ var ee=Object.defineProperty;var c=(e,t)=>{for(var r in t)ee(e,r,{get:t[r],enumerable:!0})};var De=18,v=63;var B={};c(B,{getMultilocationDerivatedAccount:()=>ae,getSovereignAccounts:()=>ce});import{AccountId as te,Blake2256 as re,compactNumber as ne,getSs58AddressInfo as oe,u32 as ie}from"@polkadot-api/substrate-bindings";import{toHex as A,fromHex as se}from"@polkadot-api/utils";function ae(e,t,r,n=!1){let o=t.length===42,s=o?"AccountKey20":"AccountId32",i;if(o)i=se(t.slice(2));else{let p=oe(t);if(!p.isValid)throw new Error("Invalid SS58 address");i=p.publicKey}let l="SiblingChain";r==0&&e?l="ChildChain":r==1&&!e&&(l="ParentChain");let u=ne.enc,m=new Uint8Array([...new TextEncoder().encode(l),...e?u(e):[],...u(s.length+(o?20:32)),...new TextEncoder().encode(s),...i]),d=re(m);return n?A(d.slice(0,20)):te().dec(d)}function ce(e){let t=ie.enc(e),r=new TextEncoder().encode("para"),n=new TextEncoder().encode("sibl"),o=A(new Uint8Array([...r,...t])).padEnd(66,"0"),s=A(new Uint8Array([...n,...t])).padEnd(66,"0"),i=s.slice(0,42);return{generic:s,moonbeam:i,relay:o}}var R={};c(R,{asBigInt:()=>ue,convertDecimals:()=>fe,pow10:()=>le,toBigInt:()=>S,toDecimal:()=>I});import g from"big.js";g.NE=-18;function I(e,t,r){let n=g(e.toString().replace(/[^0-9]/g,"")),o=g(10).pow(t);return n.div(o).round(t,r).toString()}function S(e,t){if(typeof e=="bigint")return e;let r=g(10).pow(t),n=g(e).mul(r);return BigInt(n.toFixed(0,g.roundDown))}function ue(e){return BigInt(e.round(0,g.roundDown).toFixed(0))}function fe(e,t,r){let n=I(e,t);return S(n.toString(),r)}function le(e){if(e<0)throw new Error(`pow10: negative exp ${e}`);return 10n**BigInt(e)}var H={};c(H,{enumPath:()=>de});function de(e){let t=[],r=e;for(;r&&typeof r=="object"&&"type"in r;)t.push(r.type),r=r.value;return t.join(".")}var k={};c(k,{ERC20:()=>P});var P=class{static fromAssetId(t){let r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(t){let r=Buffer.from(t.replace("0x",""),"hex");return r.length!==20||!this.isAssetAddress(t)?null:r.readUInt32BE(16)}static isAssetAddress(t){let r=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(r.subarray(0,16))}};var K={};c(K,{H160:()=>w,isEvmAccount:()=>L,isEvmAddress:()=>O,isSs58Address:()=>U});import{AccountId as h}from"polkadot-api";import{toHex as _}from"@polkadot-api/utils";import{Buffer as f}from"buffer";var E="ETH\0";function L(e){if(!e)return!1;try{let t=h().enc(e),r=f.from(E);return f.from(t.subarray(0,r.length)).equals(r)}catch{return!1}}function O(e){return!!/^0x[a-fA-F0-9]{40}$/.test(e)}function U(e){try{return h(63).enc(e),!0}catch{return!1}}var w=class e{static toAccount=t=>{let r=f.from(t.slice(2),"hex"),n=f.from(E),o=Uint8Array.from(f.concat([n,r,f.alloc(8)])),s=_(o);return h(63).dec(s)};static fromAccount=t=>{let r=h().enc(t),n=f.from(E),o=r.slice(n.length,-8);return"0x"+f.from(o).toString("hex")};static fromSS58=t=>{let n=h().enc(t).slice(0,20);return _(n)};static fromAny=t=>{if(O(t))return t;if(L(t))return e.fromAccount(t);if(U(t))return e.fromSS58(t);throw new Error("Unknown address type")}};var T={};c(T,{assertHexLen:()=>he,ensureHexPrefix:()=>N,hexNormalize:()=>me,isHex:()=>M,stripHexPrefix:()=>ge});var pe=/^0x[0-9a-fA-F]*$/;function M(e,t=!1){return e==="0x"?!0:!pe.test(e)||!t&&e.length<4?!1:t||e.length%2===0}function ge(e){return e.startsWith("0x")?e.slice(2):e}function N(e){return e.startsWith("0x")?e:`0x${e}`}function me(e){return N(e.toLowerCase())}function he(e,t){if(!M(e)||e.length-2!==t*2)throw new Error(`Expected 0x hex of ${t} bytes`)}var D={};c(D,{logger:()=>ye});var C={all:0,trace:1,debug:2,info:3,warn:4,error:5,silent:6};function b(e){return e.padEnd(11)}var y={TRACE:b("[GC][TRACE]"),DEBUG:b("[GC][DEBUG]"),INFO:b("[GC][INFO]"),WARN:b("[GC][WARN]"),ERROR:b("[GC][ERROR]")};function be(){if(typeof window<"u")try{let e=window.localStorage.getItem("gc.log");if(e&&e in C)return e}catch{}if(typeof process<"u"){let e=process.env.GC_LOG;if(e&&e in C)return e}return"silent"}function x(e){let t=be();return C[e]>=C[t]}var ye={trace(...e){x("trace")&&console.debug(y.TRACE,...e)},debug(...e){x("debug")&&console.debug(y.DEBUG,...e)},info(...e){x("info")&&console.info(y.INFO,...e)},warn(...e){x("warn")&&console.warn(y.WARN,...e)},error(...e){if(!x("error"))return;e.some(r=>r instanceof Error)?console.error(y.ERROR,...e):this.warn(...e)}};var F={};c(F,{ErrorDecoder:()=>ve});import{metadata as xe,u32 as Ce}from"@polkadot-api/substrate-bindings";function ve(e){let{metadata:t}=xe.dec(e),{pallets:r,lookup:n}=t.value,o=new Map(r.map(i=>[i.index,i])),s=new Map(n.map(i=>[i.id,i]));return{decode(i,l){let u=o.get(i);if(!u?.errors)return;let m=s.get(u.errors);if(!m||m.def.tag!=="variant")return;let d=Ce.dec(l),p=m.def.value.find(Z=>Z.index===d);if(p)return{pallet:u.name,error:p.name,desc:p.docs[0]}}}}var V={};c(V,{encodeAssetId:()=>j,encodeLocation:()=>X,toAccountId32:()=>W,toAccountKey20:()=>$,transform:()=>a});import{AccountId as Ae,Binary as Pe,FixedSizeBinary as G}from"polkadot-api";var W=e=>{let t=Ae().enc(e);return{type:"AccountId32",value:{network:void 0,id:G.fromBytes(t)}}},$=e=>({type:"AccountKey20",value:{network:void 0,key:G.fromHex(e)}}),a=e=>{if(Array.isArray(e))return e.map(a);if(typeof e=="object"&&e!==null){let t=Object.keys(e);if(t.length===1){let r=t[0],n=e[r];if(r==="AccountKey20"&&typeof n=="object"){let o=$(n.key);return n.network&&(o.value.network=a(n.network)),o}if(r==="AccountId32"&&typeof n=="object"){let o=W(n.id);return n.network&&(o.value.network=a(n.network)),o}return r==="GeneralKey"&&typeof n=="object"&&"data"in n?{type:r,value:{length:n.length,data:typeof n.data=="string"?Pe.fromHex(n.data):n.data}}:r==="GlobalConsensus"&&typeof n=="object"&&("Polkadot"in n||"Kusama"in n)?{type:r,value:n}:r==="Ethereum"?{type:r,value:{chain_id:BigInt("chainId"in n?n.chainId:n.chain_id)}}:r==="PalletInstance"?{type:r,value:n}:r==="GeneralIndex"?{type:r,value:BigInt(n)}:r==="X1"&&Array.isArray(n)?{type:r,value:n.length===1?a(n[0]):n.map(a)}:typeof n=="string"?{type:r,value:{type:n}}:typeof n=="number"?{type:r,value:n}:{type:r,value:a(n)}}else{let r={};for(let n of t){let o=e[n];r[n]=a(o)}return r}}else return e};function X(e){if(!e||typeof e!="object")return e;let{parents:t,interior:r}=e;return!r||r==="Here"?{parents:t,interior:{type:"Here"}}:{parents:t,interior:a(r)}}function j(e){return e==null?e:typeof e=="string"?BigInt(e):typeof e=="object"&&!Array.isArray(e)?a(e):e}var q={};c(q,{convertToId:()=>we});import{Buffer as Ee}from"buffer";function we(e){let r=Ee.from(e.replace("0x",""),"hex").subarray(16);return r.readUIntBE(0,r.length)}import{createClient as Ke}from"polkadot-api";import{getWsProvider as Me}from"polkadot-api/ws-provider";import{LRUCache as Ne}from"lru-cache";import{defer as Be,from as Ie,of as z,timer as Se}from"rxjs";import{catchError as Re,distinctUntilChanged as He,expand as ke,map as Y,shareReplay as _e,skip as Le,switchMap as Oe,timeout as Ue}from"rxjs/operators";function J(e,{intervalMs:t=5e3,timeoutMs:r=5e3,staleThreshold:n=3}={}){let o=i=>Be(()=>Ie(e._request("chain_getHeader",[]))).pipe(Ue({first:r}),Y(l=>{let u=parseInt(l.number,16),d=i.blockNumber!==void 0&&u<=i.blockNumber?i.staleCount+1:0;return{state:d>=n?"stale":"healthy",blockNumber:u,staleCount:d,delayMs:t}}),Re(()=>z({state:"stale",staleCount:0,delayMs:t})));return z({state:"healthy",staleCount:0,delayMs:0}).pipe(ke(i=>Se(i.delayMs).pipe(Oe(()=>o(i)))),Le(1),Y(i=>i.state),He(),_e({bufferSize:1,refCount:!0}))}var Q=class e{static _instance=new e;_cache=new Ne({max:40});_metadataCache;constructor(){if(e._instance)throw new Error("Use SubstrateApis.getInstance() instead of new.");e._instance=this}static getInstance(){return e._instance}configureMetadataCache(t){this._metadataCache=t}createCacheKey(t){return t.join(",")}findCacheKey(t){let r=t.find(o=>this._cache.has(o));if(r)return r;let n=this.createCacheKey(t);return this._cache.has(n)?n:null}createClient(t,r){let n=Me(t,r?.wsProviderOpts),o=Ke(n,this._metadataCache),s=this.createCacheKey(t);console.log(`Created PAPI client for ${s}`);let i={client:o,provider:n,endpoints:t,currentEndpointIndex:0};return this._cache.set(s,i,{noDisposeOnSet:!0}),r?.probeConfig?.enabled!==!1&&this.startHealthProbe(i,r?.probeConfig),o}api(t,r){let n=typeof t=="string"?t.split(","):t,o=this.findCacheKey(n);return o?this._cache.get(o).client:this.createClient(n,r)}release(){for(let[t,r]of this._cache.entries())this.stopHealthProbe(r),console.log("Releasing "+t),r.client.destroy();this._cache.clear()}configureHealthProbe(t,r){let n=typeof t=="string"?t.split(","):t,o=this.findCacheKey(n);if(o){let s=this._cache.get(o);this.stopHealthProbe(s),r.enabled!==!1&&this.startHealthProbe(s,r)}}startHealthProbe(t,r={}){let n=o=>{if(t.endpoints.length>1){let s=(t.currentEndpointIndex+1)%t.endpoints.length,i=t.endpoints[s];console.log(`${o} on ${t.endpoints[t.currentEndpointIndex]}, switching to ${i}`),t.provider.switch(i),t.currentEndpointIndex=s,this.stopHealthProbe(t),this.startHealthProbe(t,r)}};t.probeSubscription=J(t.client,r).subscribe({next:o=>{o==="stale"&&n("RPC stale")}})}stopHealthProbe(t){t.probeSubscription&&(t.probeSubscription.unsubscribe(),t.probeSubscription=void 0)}getWs(t){let r=typeof t=="string"?t.split(","):t,n=this.findCacheKey(r);if(n)return this._cache.get(n)?.provider}};export{v as HYDRATION_SS58_PREFIX,De as RUNTIME_DECIMALS,Q as SubstrateApis,B as acc,R as big,J as blockProbe$,j as encodeAssetId,X as encodeLocation,H as enums,k as erc20,K as h160,T as hex,D as log,F as meta,a as transform,q as xc,V as xcm};
@@ -1,2 +1,3 @@
1
1
  export * from './consts';
2
2
  export * from './utils';
3
+ export * from './substrate';
@@ -0,0 +1,31 @@
1
+ import { PolkadotClient } from 'polkadot-api';
2
+ import { getWsProvider } from 'polkadot-api/ws-provider';
3
+ import { HealthProbeConfig } from './probe';
4
+ export interface MetadataCache {
5
+ getMetadata: (codeHash: string) => Promise<Uint8Array | null>;
6
+ setMetadata: (codeHash: string, metadata: Uint8Array) => void;
7
+ }
8
+ type WsProvider = ReturnType<typeof getWsProvider>;
9
+ export type WsProviderOpts = Parameters<typeof getWsProvider>[1];
10
+ export interface ApiOptions {
11
+ wsProviderOpts?: WsProviderOpts;
12
+ probeConfig?: HealthProbeConfig;
13
+ }
14
+ export declare class SubstrateApis {
15
+ private static _instance;
16
+ private _cache;
17
+ private _metadataCache?;
18
+ constructor();
19
+ static getInstance(): SubstrateApis;
20
+ configureMetadataCache(cache: MetadataCache): void;
21
+ createCacheKey(endpoints: string[]): string;
22
+ findCacheKey(endpoints: string[]): string | null;
23
+ createClient(endpoints: string[], opts?: ApiOptions): PolkadotClient;
24
+ api(ws: string | string[], opts?: ApiOptions): PolkadotClient;
25
+ release(): void;
26
+ configureHealthProbe(ws: string | string[], config: HealthProbeConfig): void;
27
+ private startHealthProbe;
28
+ private stopHealthProbe;
29
+ getWs(ws: string | string[]): WsProvider | undefined;
30
+ }
31
+ export {};
@@ -0,0 +1,2 @@
1
+ export * from './SubstrateApis';
2
+ export * from './probe';
@@ -0,0 +1,12 @@
1
+ import { PolkadotClient } from 'polkadot-api';
2
+ import { Observable } from 'rxjs';
3
+ export type ProbeState = 'healthy' | 'stale';
4
+ export type ProbeConfig = {
5
+ intervalMs?: number;
6
+ timeoutMs?: number;
7
+ staleThreshold?: number;
8
+ };
9
+ export interface HealthProbeConfig extends ProbeConfig {
10
+ enabled?: boolean;
11
+ }
12
+ export declare function blockProbe$(client: PolkadotClient, { intervalMs, timeoutMs, staleThreshold, }?: ProbeConfig): Observable<ProbeState>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Multilocation-derivative account - an account computed when
3
+ * executing remote calls via XCM.
4
+ *
5
+ * @param parachainId parachain id or undefined in case of relay
6
+ * @param address sender address
7
+ * @param parents describe family
8
+ * @returns multilocation derivated account address
9
+ */
10
+ export declare function getMultilocationDerivatedAccount(parachainId: number | undefined, address: string, parents: number, isEthereumStyle?: boolean): string;
11
+ /**
12
+ * Sovereign account — an account each chain in the ecosystem has, one for the relay chain
13
+ * and the other for other parachains. The account is owned by root and can only be used
14
+ * through SUDO (if available) or democracy (technical committee or referenda).
15
+ *
16
+ * @param parachainId parachain id
17
+ * @returns sovereign account addresses
18
+ */
19
+ export declare function getSovereignAccounts(parachainId: number): {
20
+ generic: string;
21
+ moonbeam: string;
22
+ relay: string;
23
+ };
@@ -1,3 +1,4 @@
1
+ export * as acc from './account';
1
2
  export * as big from './big';
2
3
  export * as enums from './enums';
3
4
  export * as erc20 from './erc20';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/common",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Common utilities shared across Galactic SDK packages",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -31,7 +31,8 @@
31
31
  "test": "NODE_NO_WARNINGS=1 NODE_OPTIONS=--experimental-vm-modules jest"
32
32
  },
33
33
  "dependencies": {
34
- "big.js": "^6.2.1"
34
+ "big.js": "^6.2.1",
35
+ "lru-cache": "^11.2.2"
35
36
  },
36
37
  "devDependencies": {
37
38
  "@types/big.js": "^6.2.2"