@monerium/sdk-react-provider 0.0.2 → 0.0.4

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/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var ee=(o,e,t)=>{if(!e.has(o))throw TypeError("Cannot "+t)};var y=(o,e,t)=>(ee(o,e,"read from private field"),t?t.call(o):e.get(o)),H=(o,e,t)=>{if(e.has(o))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(o):e.set(o,t)},O=(o,e,t,n)=>(ee(o,e,"write to private field"),n?n.call(o,t):e.set(o,t),t);var I=(o,e,t)=>(ee(o,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const he=require("react/jsx-runtime"),B=require("react"),se=B.createContext(null),Y=o=>{var e;return o&&((e=Object.entries(o))==null?void 0:e.length)>0?Object.entries(o).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&"):""},pe=o=>{switch(o){case 1:case 5:return"ethereum";case 100:case 10200:return"gnosis";case 137:case 80001:return"polygon";default:throw new Error(`Chain not supported: ${o}`)}},ve=o=>{switch(o){case 1:case 100:case 137:return"mainnet";case 5:return"goerli";case 10200:return"chiado";case 80001:return"mumbai";default:throw new Error(`Network not supported: ${o}`)}},te={environments:{production:{api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}},V="monerium.sdk.code_verifier",re="monerium.sdk.refresh_token";var j=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ue(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}function ge(o){if(o.__esModule)return o;var e=o.default;if(typeof e=="function"){var t=function n(){if(this instanceof n){var i=[null];i.push.apply(i,arguments);var c=Function.bind.apply(e,i);return new c}return e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(o).forEach(function(n){var i=Object.getOwnPropertyDescriptor(o,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return o[n]}})}),t}var le={exports:{}};function we(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var ne={exports:{}};const ye={},me=Object.freeze(Object.defineProperty({__proto__:null,default:ye},Symbol.toStringTag,{value:"Module"})),_e=ge(me);var ie;function fe(){return ie||(ie=1,function(o,e){(function(t,n){o.exports=n()})(j,function(){var t=t||function(n,i){var c;if(typeof window<"u"&&window.crypto&&(c=window.crypto),typeof self<"u"&&self.crypto&&(c=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(c=globalThis.crypto),!c&&typeof window<"u"&&window.msCrypto&&(c=window.msCrypto),!c&&typeof j<"u"&&j.crypto&&(c=j.crypto),!c&&typeof we=="function")try{c=_e}catch{}var f=function(){if(c){if(typeof c.getRandomValues=="function")try{return c.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof c.randomBytes=="function")try{return c.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},k=Object.create||function(){function r(){}return function(s){var u;return r.prototype=s,u=new r,r.prototype=null,u}}(),h={},w=h.lib={},m=w.Base=function(){return{extend:function(r){var s=k(this);return r&&s.mixIn(r),(!s.hasOwnProperty("init")||this.init===s.init)&&(s.init=function(){s.$super.init.apply(this,arguments)}),s.init.prototype=s,s.$super=this,s},create:function(){var r=this.extend();return r.init.apply(r,arguments),r},init:function(){},mixIn:function(r){for(var s in r)r.hasOwnProperty(s)&&(this[s]=r[s]);r.hasOwnProperty("toString")&&(this.toString=r.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),g=w.WordArray=m.extend({init:function(r,s){r=this.words=r||[],s!=i?this.sigBytes=s:this.sigBytes=r.length*4},toString:function(r){return(r||d).stringify(this)},concat:function(r){var s=this.words,u=r.words,l=this.sigBytes,_=r.sigBytes;if(this.clamp(),l%4)for(var b=0;b<_;b++){var x=u[b>>>2]>>>24-b%4*8&255;s[l+b>>>2]|=x<<24-(l+b)%4*8}else for(var E=0;E<_;E+=4)s[l+E>>>2]=u[E>>>2];return this.sigBytes+=_,this},clamp:function(){var r=this.words,s=this.sigBytes;r[s>>>2]&=4294967295<<32-s%4*8,r.length=n.ceil(s/4)},clone:function(){var r=m.clone.call(this);return r.words=this.words.slice(0),r},random:function(r){for(var s=[],u=0;u<r;u+=4)s.push(f());return new g.init(s,r)}}),S=h.enc={},d=S.Hex={stringify:function(r){for(var s=r.words,u=r.sigBytes,l=[],_=0;_<u;_++){var b=s[_>>>2]>>>24-_%4*8&255;l.push((b>>>4).toString(16)),l.push((b&15).toString(16))}return l.join("")},parse:function(r){for(var s=r.length,u=[],l=0;l<s;l+=2)u[l>>>3]|=parseInt(r.substr(l,2),16)<<24-l%8*4;return new g.init(u,s/2)}},v=S.Latin1={stringify:function(r){for(var s=r.words,u=r.sigBytes,l=[],_=0;_<u;_++){var b=s[_>>>2]>>>24-_%4*8&255;l.push(String.fromCharCode(b))}return l.join("")},parse:function(r){for(var s=r.length,u=[],l=0;l<s;l++)u[l>>>2]|=(r.charCodeAt(l)&255)<<24-l%4*8;return new g.init(u,s)}},a=S.Utf8={stringify:function(r){try{return decodeURIComponent(escape(v.stringify(r)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(r){return v.parse(unescape(encodeURIComponent(r)))}},p=w.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new g.init,this._nDataBytes=0},_append:function(r){typeof r=="string"&&(r=a.parse(r)),this._data.concat(r),this._nDataBytes+=r.sigBytes},_process:function(r){var s,u=this._data,l=u.words,_=u.sigBytes,b=this.blockSize,x=b*4,E=_/x;r?E=n.ceil(E):E=n.max((E|0)-this._minBufferSize,0);var D=E*b,U=n.min(D*4,_);if(D){for(var q=0;q<D;q+=b)this._doProcessBlock(l,q);s=l.splice(0,D),u.sigBytes-=U}return new g.init(s,U)},clone:function(){var r=m.clone.call(this);return r._data=this._data.clone(),r},_minBufferSize:0});w.Hasher=p.extend({cfg:m.extend(),init:function(r){this.cfg=this.cfg.extend(r),this.reset()},reset:function(){p.reset.call(this),this._doReset()},update:function(r){return this._append(r),this._process(),this},finalize:function(r){r&&this._append(r);var s=this._doFinalize();return s},blockSize:16,_createHelper:function(r){return function(s,u){return new r.init(u).finalize(s)}},_createHmacHelper:function(r){return function(s,u){return new C.HMAC.init(r,u).finalize(s)}}});var C=h.algo={};return h}(Math);return t})}(ne)),ne.exports}(function(o,e){(function(t,n){o.exports=n(fe())})(j,function(t){return function(){var n=t,i=n.lib,c=i.WordArray,f=n.enc;f.Base64url={stringify:function(h,w){w===void 0&&(w=!0);var m=h.words,g=h.sigBytes,S=w?this._safe_map:this._map;h.clamp();for(var d=[],v=0;v<g;v+=3)for(var a=m[v>>>2]>>>24-v%4*8&255,p=m[v+1>>>2]>>>24-(v+1)%4*8&255,C=m[v+2>>>2]>>>24-(v+2)%4*8&255,r=a<<16|p<<8|C,s=0;s<4&&v+s*.75<g;s++)d.push(S.charAt(r>>>6*(3-s)&63));var u=S.charAt(64);if(u)for(;d.length%4;)d.push(u);return d.join("")},parse:function(h,w){w===void 0&&(w=!0);var m=h.length,g=w?this._safe_map:this._map,S=this._reverseMap;if(!S){S=this._reverseMap=[];for(var d=0;d<g.length;d++)S[g.charCodeAt(d)]=d}var v=g.charAt(64);if(v){var a=h.indexOf(v);a!==-1&&(m=a)}return k(h,m,S)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function k(h,w,m){for(var g=[],S=0,d=0;d<w;d++)if(d%4){var v=m[h.charCodeAt(d-1)]<<d%4*2,a=m[h.charCodeAt(d)]>>>6-d%4*2,p=v|a;g[S>>>2]|=p<<24-S%4*8,S++}return c.create(g,S)}}(),t.enc.Base64url})})(le);var be=le.exports;const Se=ue(be);var de={exports:{}};(function(o,e){(function(t,n){o.exports=n(fe())})(j,function(t){return function(n){var i=t,c=i.lib,f=c.WordArray,k=c.Hasher,h=i.algo,w=[],m=[];(function(){function d(C){for(var r=n.sqrt(C),s=2;s<=r;s++)if(!(C%s))return!1;return!0}function v(C){return(C-(C|0))*4294967296|0}for(var a=2,p=0;p<64;)d(a)&&(p<8&&(w[p]=v(n.pow(a,1/2))),m[p]=v(n.pow(a,1/3)),p++),a++})();var g=[],S=h.SHA256=k.extend({_doReset:function(){this._hash=new f.init(w.slice(0))},_doProcessBlock:function(d,v){for(var a=this._hash.words,p=a[0],C=a[1],r=a[2],s=a[3],u=a[4],l=a[5],_=a[6],b=a[7],x=0;x<64;x++){if(x<16)g[x]=d[v+x]|0;else{var E=g[x-15],D=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,U=g[x-2],q=(U<<15|U>>>17)^(U<<13|U>>>19)^U>>>10;g[x]=D+g[x-7]+q+g[x-16]}var Z=u&l^~u&_,A=p&C^p&r^C&r,z=(p<<30|p>>>2)^(p<<19|p>>>13)^(p<<10|p>>>22),L=(u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25),W=b+L+Z+m[x]+g[x],N=z+A;b=_,_=l,l=u,u=s+W|0,s=r,r=C,C=p,p=W+N|0}a[0]=a[0]+p|0,a[1]=a[1]+C|0,a[2]=a[2]+r|0,a[3]=a[3]+s|0,a[4]=a[4]+u|0,a[5]=a[5]+l|0,a[6]=a[6]+_|0,a[7]=a[7]+b|0},_doFinalize:function(){var d=this._data,v=d.words,a=this._nDataBytes*8,p=d.sigBytes*8;return v[p>>>5]|=128<<24-p%32,v[(p+64>>>9<<4)+14]=n.floor(a/4294967296),v[(p+64>>>9<<4)+15]=a,d.sigBytes=v.length*4,this._process(),this._hash},clone:function(){var d=k.clone.call(this);return d._hash=this._hash.clone(),d}});i.SHA256=k._createHelper(S),i.HmacSHA256=k._createHmacHelper(S)}(Math),t.SHA256})})(de);var ke=de.exports;const Be=ue(ke),Ce=(o,e)=>{const{client_id:t,redirect_uri:n,scope:i,state:c,chainId:f,chain:k,network:h,address:w,signature:m}=o,g=w?{address:w,...m!==void 0?{signature:m}:{},...f!==void 0||k!==void 0?{chain:f?pe(f):k}:{},...f!==void 0||h!==void 0?{network:f?ve(f):h}:{}}:{};return Y({client_id:t,redirect_uri:n,...i!==void 0?{scope:i}:{},...c!==void 0?{state:c}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...g})},xe=()=>{let o="";const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length;let n=0;for(;n<128;)o+=e.charAt(Math.floor(Math.random()*t)),n+=1;return o},Ee=o=>Se.stringify(Be(o)),ae=(o,e)=>{const t=xe(),n=Ee(t);return sessionStorage.setItem(V,t||""),`${o}/auth?${Ce(e,n)}`},Ae=()=>{const o=window.location.href,[e,t]=o.split("?");t&&window.history.replaceState(null,"",e)},ce=o=>o.code!=null,Pe=o=>o.refresh_token!=null,Oe=o=>o.client_secret!=null,Ie=async(o,e,t,n)=>{const i=await fetch(`${o}`,{method:e,headers:n,body:t});let c;const f=await i.text();try{c=JSON.parse(f)}catch{throw f}if(!i.ok)throw c;return c},oe=typeof window>"u";var T,G,F,M,$,P,R,J,K,Q;class Re{constructor(e){H(this,P);H(this,T,void 0);H(this,G,void 0);H(this,F,void 0);H(this,M,void 0);H(this,$,void 0);H(this,J,void 0);H(this,K,void 0);H(this,Q,void 0);if(O(this,M,new Map),this.isAuthorized=!!this.bearerProfile,O(this,J,async(t,n,i)=>{const c=sessionStorage.getItem(V)||"";if(!c)throw new Error("Code verifier not found");return this.codeVerifier=c,sessionStorage.removeItem(V),await this.getBearerToken({code:i,redirect_uri:n,client_id:t,code_verifier:c})}),O(this,K,async({clientId:t,clientSecret:n})=>await this.getBearerToken({client_id:t,client_secret:n})),O(this,Q,async(t,n)=>await this.getBearerToken({refresh_token:n,client_id:t})),this.subscribeToOrderNotifications=()=>{var i,c;const t=`${y(this,T).wss}/profiles/${(i=this.bearerProfile)==null?void 0:i.profile}/orders?access_token=${(c=this.bearerProfile)==null?void 0:c.access_token}`,n=new WebSocket(t);return n.addEventListener("open",()=>{console.info(`Socket connected: ${t}`)}),n.addEventListener("error",f=>{throw console.error(f),new Error(`Socket error: ${t}`)}),n.addEventListener("message",f=>{var h;const k=JSON.parse(f.data);(h=y(this,M).get(k.meta.state))==null||h(k)}),n.addEventListener("close",()=>{console.info(`Socket connection closed: ${t}`)}),n},this.auth=async t=>await this.getBearerToken(t),this.getAuthFlowURI=t=>ae(y(this,T).api,t),this.pkceRequest=t=>this.getAuthFlowURI(t),this.getEnvironment=()=>y(this,T),!e){O(this,T,te.environments.sandbox);return}if(typeof e=="string")O(this,T,te.environments[e]);else if(O(this,T,te.environments[e.environment||"sandbox"]),oe){const{clientId:t,clientSecret:n}=e;O(this,$,{clientId:t,clientSecret:n})}else{const{clientId:t,redirectUrl:n}=e;O(this,$,{clientId:t,redirectUrl:n})}}async authorize(e){var c,f;const t=(e==null?void 0:e.clientId)||((c=y(this,$))==null?void 0:c.clientId),n=(e==null?void 0:e.redirectUrl)||((f=y(this,$))==null?void 0:f.redirectUrl);if(!t)throw new Error("Missing ClientId");if(!n)throw new Error("Missing RedirectUrl");const i=ae(y(this,T).api,{client_id:t,redirect_uri:n,...e==null?void 0:e.wallet});window.location.replace(i)}async connect(e){var k,h,w;const t=(e==null?void 0:e.clientId)||((k=y(this,$))==null?void 0:k.clientId);if((e==null?void 0:e.clientSecret)||((h=y(this,$))==null?void 0:h.clientSecret)){if(!oe)throw new Error("Only use client credentials on server side");return await y(this,K).call(this,y(this,$)),!!this.bearerProfile}const i=(e==null?void 0:e.redirectUrl)||((w=y(this,$))==null?void 0:w.redirectUrl);if(!t)throw new Error("Missing ClientId");if(oe)throw new Error("This only works on client side");const c=new URLSearchParams(window.location.search).get("code")||void 0,f=sessionStorage.getItem(re)||void 0;return c?await y(this,J).call(this,t,i,c):f&&await y(this,Q).call(this,t,f),!!this.bearerProfile}async getBearerToken(e){let t;if(ce(e))t={...e,grant_type:"authorization_code"};else if(Pe(e))t={...e,grant_type:"refresh_token"};else if(Oe(e))t={...e,grant_type:"client_credentials"};else throw new Error("Authentication method could not be detected.");return await I(this,P,R).call(this,"post","auth/token",t,!0).then(n=>{var i;this.bearerProfile=n,this.isAuthorized=!!n,O(this,G,`Bearer ${n==null?void 0:n.access_token}`),window.sessionStorage.setItem(re,((i=this.bearerProfile)==null?void 0:i.refresh_token)||"")}).catch(n=>{throw sessionStorage.removeItem(V),sessionStorage.removeItem(re),new Error(n==null?void 0:n.message)}),ce(e)&&Ae(),this.bearerProfile}getAuthContext(){return I(this,P,R).call(this,"get","auth/context")}getProfile(e){return I(this,P,R).call(this,"get",`profiles/${e}`)}getBalances(e){return e?I(this,P,R).call(this,"get",`profiles/${e}/balances`):I(this,P,R).call(this,"get","balances")}getOrders(e){const t=Y(e);return I(this,P,R).call(this,"get",`orders?${t}`)}getOrder(e){return I(this,P,R).call(this,"get",`orders/${e}`)}getTokens(){return I(this,P,R).call(this,"get","tokens")}linkAddress(e,t){return I(this,P,R).call(this,"post",`profiles/${e}/addresses`,JSON.stringify(t))}placeOrder(e,t){const n={...e,kind:"redeem",currency:"eur"};return t?I(this,P,R).call(this,"post",`profiles/${t}/orders`,JSON.stringify(n)):I(this,P,R).call(this,"post","orders",JSON.stringify(n))}uploadSupportingDocument(e){const t=Y(e);return I(this,P,R).call(this,"post","files/supporting-document",t,!0)}async connectOrderSocket(){var e;(e=this.bearerProfile)!=null&&e.access_token&&y(this,M).size>0&&O(this,F,this.subscribeToOrderNotifications())}async disconnect(){var e;sessionStorage.removeItem(V),y(this,M).clear(),(e=y(this,F))==null||e.close()}subscribeOrders(e,t){y(this,M).set(e,t)}unsubscribeOrders(e){var t;y(this,M).delete(e),y(this,M).size===0&&((t=y(this,F))==null||t.close(),O(this,F,void 0))}}T=new WeakMap,G=new WeakMap,F=new WeakMap,M=new WeakMap,$=new WeakMap,P=new WeakSet,R=async function(e,t,n,i){return Ie(`${y(this,T).api}/${t}`,e,i?Y(n):n,{Authorization:y(this,G)||"","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`})},J=new WeakMap,K=new WeakMap,Q=new WeakMap;const ze=({children:o,clientId:e="f99e629b-6dca-11ee-8aa6-5273f65ed05b",redirectUrl:t="http://localhost:5173",environment:n="sandbox"})=>{const[i,c]=B.useState(),[f,k]=B.useState(!1),[h,w]=B.useState(null),[m,g]=B.useState(null),[S,d]=B.useState(!1),[v,a]=B.useState(!1),[p,C]=B.useState(!1),[r,s]=B.useState(!1),[u,l]=B.useState(null),[_,b]=B.useState([]),[x,E]=B.useState([]);B.useEffect(()=>{const A=new Re({environment:n,clientId:e,redirectUrl:t});c(A)},[]),B.useEffect(()=>((async()=>{i&&k(await i.connect())})(),()=>{i&&i.disconnect()}),[i]),B.useEffect(()=>{(async()=>{if(i&&f)try{d(!0);const z=await i.getAuthContext(),L=await i.getProfile(z.defaultProfile),W=await i.getBalances(),N=await i.getOrders(),X=await i.getTokens();w(L),g(W),b(N),E(X)}catch(z){console.error("Error fetching data:",z),l(z)}finally{d(!1)}})()},[i,f]);const D=B.useCallback(async()=>{try{i&&await i.authorize()}catch(A){console.error("Error during authorization:",A),l(A)}},[i]),U=B.useCallback(async()=>{if(i&&f)try{s(!0);const A=await i.getBalances();g(A)}catch(A){console.error("Error getting balances:",A),l(A)}finally{s(!1)}},[i,f]),q=B.useCallback(async(A,z)=>{if(i&&f)try{a(!0);let L;parseInt(A.amount)>15e3&&z&&(L=(await i.uploadSupportingDocument(z)).id);const W={...A,documentId:L},N=await i.placeOrder(W);b(X=>[...X,N])}catch(L){console.error("Error placing order:",L),l(L)}finally{a(!1)}},[i,f]),Z=B.useCallback(async A=>{if(i&&f&&h)try{return C(!0),await i.linkAddress(h.id,A)}catch(z){console.error("Error linking address:",z),l(z)}finally{C(!1)}},[i,f,h]);return he.jsx(se.Provider,{value:{authorize:D,isAuthorized:f,profile:h,balances:m,loading:S,loadingPlaceOrder:v,loadingLinkAddress:p,loadingBalances:r,getBalances:U,linkAddress:Z,placeOrder:q,orders:_,tokens:x,error:u},children:o})};function Te(){const o=B.useContext(se);if(o===null)throw new Error("useMonerium must be used within a MoneriumProvider");return o}exports.MoneriumContext=se;exports.MoneriumProvider=ze;exports.useMonerium=Te;