UNPKG

bnb-passport-attestation

Version:

BAS SDK - A toolkit for blockchain interaction

2 lines (1 loc) 18.7 kB
import{useRef as t,useState as e,useEffect as n,useCallback as r}from"react";import{BrowserProvider as o,ethers as a}from"ethers";const s=i;function i(t,e){const n=u();return(i=function(t,e){return n[t-=327]})(t,e)}!function(){const t=i,e=u();for(;;)try{if(944447===parseInt(t(337))/1+parseInt(t(327))/2*(-parseInt(t(336))/3)+parseInt(t(332))/4+-parseInt(t(331))/5+parseInt(t(330))/6*(parseInt(t(328))/7)+-parseInt(t(335))/8+-parseInt(t(333))/9*(-parseInt(t(334))/10))break;e.push(e.shift())}catch(t){e.push(e.shift())}}();const c=5e7,l=s(338);function u(){const t=["78EgztlI","343591RsdjmX","https://dev.passsport.bnbattest.io/verify","94978OZvNNq","7wLmpwD","https:passport.bnbattest.io/verify","290502xeGDIX","8055390aIXcdk","3735720nPsVaM","30642471ddAHko","10LmjZHz","7523344fZlJIV"];return(u=function(){return t})()}const d=s(329);function w(t,e){const n=p();return(w=function(t,e){return n[t-=324]})(t,e)}function p(){const t=["1041843zAuVYS","0x38","60HmFhrs","1824459ZgSEFh","11493RKDCHR","22FGFLlg","https://testnet.bscscan.com","459492spnfKs","3096syRcCJ","20455BvQwzW","https://data-seed-prebsc-1-s1.bnbchain.org:8545","2188QXKGnH","BNB Smart Chain","292FKnQNe","BNB","https://bsc-dataseed.binance.org/","489335PKjrXO"];return(p=function(){return t})()}const h=w;!function(){const t=w,e=p();for(;;)try{if(400980===parseInt(t(324))/1*(parseInt(t(330))/2)+parseInt(t(339))/3+-parseInt(t(332))/4*(parseInt(t(328))/5)+-parseInt(t(326))/6+parseInt(t(335))/7+parseInt(t(327))/8*(-parseInt(t(340))/9)+-parseInt(t(338))/10*(-parseInt(t(336))/11))break;e.push(e.shift())}catch(t){e.push(e.shift())}}();const f={mainnet:{chainId:h(337),chainName:h(331),nativeCurrency:{name:h(333),symbol:h(333),decimals:18},rpcUrls:[h(334)],blockExplorerUrls:["https://bscscan.com/"]},testnet:{chainId:"0x61",chainName:"BNB Smart Chain Testnet",nativeCurrency:{name:h(333),symbol:h(333),decimals:18},rpcUrls:[h(329)],blockExplorerUrls:[h(325)]}};function m(){const t=["message","Failed to add "," network:","60MqrMQz","wallet_switchEthereumChain","1821fHLpXq","734035ScEmbk","302cMaFbd","684910SroOGg","33pySAzF","151319AHyWQr","request","getNetwork","41679NZrYaF","Network switch request already pending. Please check your wallet.","296GgXFIU","1572IMZuVb","Unknown error","12335868ihFZpN","code","User rejected the network switch request.","error","13BnRSNl","1417NXSALA","chainId"];return(m=function(){return t})()}function y(t,e){const n=m();return(y=function(t,e){return n[t-=321]})(t,e)}!function(){const t=y,e=m();for(;;)try{if(129288===parseInt(t(324))/1*(-parseInt(t(333))/2)+parseInt(t(331))/3*(-parseInt(t(342))/4)+parseInt(t(332))/5+parseInt(t(329))/6*(-parseInt(t(336))/7)+-parseInt(t(341))/8*(parseInt(t(339))/9)+-parseInt(t(334))/10*(parseInt(t(335))/11)+-parseInt(t(344))/12*(-parseInt(t(323))/13))break;e.push(e.shift())}catch(t){e.push(e.shift())}}();const I=E;function E(t,e){const n=v();return(E=function(t,e){return n[t-=332]})(t,e)}function g(t=I(350)){const[a,s]=e(null),[i,c]=e(""),[l,u]=e(!1),{switchToNetwork:d}={switchToNetwork:r((async(t,e)=>{const n=y,r=f[e],a=new o(t);try{const e=await a[n(338)](),o=BigInt(parseInt(r[n(325)],16));if(e[n(325)]===o)return;if(await t[n(337)]({method:n(330),params:[{chainId:r.chainId}]}),(await a[n(338)]())[n(325)]!==o)throw new Error("Network switch verification failed")}catch(o){if(4902!==o[n(345)])throw 4001===o[n(345)]?new Error(n(321)):-32002===o.code?new Error(n(340)):new Error("Failed to switch network: "+(o[n(326)]||n(343)));try{await t.request({method:"wallet_addEthereumChain",params:[r]})}catch(t){throw console[n(322)](n(327)+e+n(328),t),new Error(n(327)+e+" network. Please add it manually in your wallet.")}if((await a[n(338)]()).chainId!==BigInt(parseInt(r[n(325)],16)))throw new Error("Network addition verification failed")}}),[])},[w,p]=e(null),h=r((()=>{const t=E;var e,n,r;return(null===(e=window.ethereum)||void 0===e?void 0:e[t(336)])?(console.log("Detected MetaMask provider."),window[t(354)]):window.okxwallet?(console[t(340)](t(359)),window[t(356)]):window[t(334)]?(console[t(340)](t(349)),window[t(334)]):(null===(n=window.ethereum)||void 0===n?void 0:n.isBitgetWallet)?(console[t(340)]("Detected Bitget Wallet provider."),window.ethereum):(null===(r=window.ethereum)||void 0===r?void 0:r[t(341)])?(console[t(340)](t(367)),window.ethereum):window[t(354)]?(console[t(340)](t(343)),window[t(354)]):(console[t(340)]("No injected provider found."),null)}),[]),m=r((async()=>{const e=E;console[e(340)](e(368));const n=h();if(!n)throw console.error("No provider found, throwing error."),new Error(e(345));try{const r=await n[e(366)]({method:e(379)});if(!(null==r?void 0:r[e(360)]))throw console[e(373)](e(357)),new Error(e(369));s(r[0]),p(n);const o=await n[e(366)]({method:"eth_chainId"}),a=o===f[e(348)].chainId,i=o===f[e(350)][e(335)],c=a?e(348):i?"testnet":e(346);return c!==t&&(console[e(340)](e(333)+c+e(353)+t+e(380)),await d(n,t)),r[0]}catch(t){if(console[e(373)](e(352),t),4001===t[e(347)])throw new Error(e(332));throw t}}),[t,h,d]);return n((()=>{const e=E,n=h();if(!n)return;const r=t=>{const e=E;console[e(340)](e(362),t);const n=t[0]||null;s(n)},o=e=>{const n=E;console.log(n(370),e);const r=e===f[n(348)][n(335)],o=e===f[n(350)][n(335)],a=r?n(348):o?"testnet":n(346);c(a),u("mainnet"===t?r:o)},i=t=>{const e=E;console.log(e(339),t),s(null),p(null),c(""),u(!1)};return!a&&(console[e(340)]("Fetching initial account and chain."),Promise.all([n[e(366)]({method:e(361)}),n.request({method:"eth_chainId"})])[e(342)]((([r,o])=>{const a=e;(null==r?void 0:r[a(360)])>0&&(s(r[0]),console[a(340)]("Initial account set:",r[0]),p(n));const i=o===f[a(348)][a(335)],l=o===f[a(350)][a(335)],d=i?"mainnet":a(l?350:346);c(d),u(t===a(348)?i:l),console[a(340)](a(338),d)}))[e(344)](console.error)),n.on("accountsChanged",r),n.on(e(377),o),n.on("disconnect",i),()=>{const t=e;n[t(374)]("accountsChanged",r),n.removeListener(t(377),o),n[t(374)]("disconnect",i)}}),[a,t,h]),{provider:w,account:a,currentNetwork:i,isCorrectNetwork:l,connect:m,isConnected:!!a,switchToNetwork:d}}function v(){const t=["mainnet","Detected BitKeep provider.","testnet","1645932OteGHm","Wallet connection error:"," to ","ethereum","298419CrjXeo","okxwallet","No account found after requesting accounts.","10ZgbQYA","Detected OKX Wallet provider.","length","eth_accounts","Accounts changed:","410255WhGuWJ","17901hnFXih","5962gzEant","request","Detected TokenPocket provider.","Attempting to connect wallet...","No account found in your wallet. Please create or import an account.","Chain changed:","1646636QBumZA","103519jlIaLn","error","removeListener","7hKYppn","8320hBDYur","chainChanged","1448Uovplg","eth_requestAccounts"," network","1944EzagzW","User rejected wallet connection or wallet has no account. Please unlock your wallet and ensure you have at least one account.","Switching from ","bitkeep","chainId","isMetaMask","5PemBNK","Initial network set:","Disconnected:","log","isTokenPocket","then","Detected generic Ethereum provider.","catch","Please install a wallet extension like MetaMask, OKX, Bitget, TokenPocket, etc.","unknown","code"];return(v=function(){return t})()}function b({inviteCode:o,env:s="testnet"}){const i="testnet"===s?l:d,{iframeRef:u,loaded:w}=function(r){const{src:o,visible:a=!1}=r,s=t(null),[i,c]=e(!1);return n((()=>{const t=document.createElement("iframe");t.src=o,t.style.display="none",t.style.border="none",t.style.width="100%",t.style.height="100%",t.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(t),s.current=t;const e=()=>{c(!0)};return t.addEventListener("load",e),()=>{s.current&&(document.body.removeChild(s.current),s.current=null),t.removeEventListener("load",e)}}),[o,a]),{iframeRef:s,loaded:i}}({timeout:c,src:i}),p=t({}),h=t(0),[f,m]=e(!1),[y,I]=e(null),[E,v]=e(!1),[b,_]=e(!1),k=t([]),N=t([]),T=t([]),{provider:C,account:A,currentNetwork:F,isCorrectNetwork:B,connect:M,isConnected:P}=g(s);n((()=>{function t(t){var e;if(t.source!==(null===(e=u.current)||void 0===e?void 0:e.contentWindow))return;const n=t.data;if(!n||"object"!=typeof n)return;const{requestId:r,result:o,error:a}=n,s=p.current[r];s&&(clearTimeout(s.timeoutId),delete p.current[r],a?s.reject(new Error(a)):s.resolve(o))}return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}),[u]);const q=r((async t=>{var e;if(!(null===(e=u.current)||void 0===e?void 0:e.contentWindow))throw new Error("Iframe not initialized");if(!w)throw new Error("Iframe not loaded yet");if(!A)throw new Error("No wallet connected");const n=`req_${Date.now()}_${h.current++}`;return new Promise(((e,r)=>{const a=window.setTimeout((()=>{delete p.current[n],r(new Error("Call timed out (50000000ms)"))}),c);p.current[n]={resolve:e,reject:r,timeoutId:a},u.current.contentWindow.postMessage({requestId:n,method:"mint",args:[t,A,o]},"*")}))}),[w,u,A,o]),W=r((async t=>{let e;if(!A)throw new Error("No wallet account connected. Please connect wallet.");if(!t.abi||!t.functionName||!Array.isArray(t.args))throw new Error("Contract call arguments are incorrect.");if(!C)throw new Error("Ethers provider not initialized. MetaMask or other wallet is not installed or connected.");m(!0);try{const n=new a.BrowserProvider(C),r=await n.getSigner();e=new a.Contract(t.address,t.abi,r);const[o,s,i]=t.args;if(!o||"object"!=typeof o)throw new Error("Invalid request structure");const c=(await n.getFeeData()).gasPrice||BigInt(0),l=await n.getBalance(A),u=t.value,d={from:A,value:u};let w;try{w=await e[t.functionName].estimateGas(o,s,i,d)}catch(t){throw new Error(t)}console.log("Gas Estimate:",w),console.log("gasPrice:",c),console.log("balance:",l);const p=w*c+u;if(console.log("totalCost:",p),l<p)throw new Error(`Insufficient funds. Required: ${a.formatEther(p)} ETH, Available: ${a.formatEther(l)} ETH`);const h=await e[t.functionName](o,s,i,{...d,gasLimit:Math.floor(1.1*Number(w)),gasPrice:c});console.log("Transaction response:",h),I(h.hash),v(!0);const f=await h.wait();return console.log("Transaction receipt:",f),v(!1),_(!0),f}catch(t){m(!1),v(!1),_(!1);let n=null;if(t.data&&e&&e.interface)try{n=e.interface.parseError(t.data)}catch(t){console.log("Failed to parse estimation error data with ethers.js:",t)}throw n?new Error(`Transaction estimation failed: Contract reverted with ${n.name}`):new Error(t.shortMessage||t.message||"Gas estimation failed: Internal EVM error or insufficient funds for estimation.")}finally{m(!1)}}),[A,C]),z=r((t=>{if(k.current.push(t),A)try{t(A)}catch(t){console.error("Error in account change callback:",t)}}),[A]),D=r((t=>{if(N.current.push(t),F)try{t(F)}catch(t){console.error("Error in network change callback:",t)}}),[F]),H=r((t=>{T.current.push(t)}),[]);return{loaded:w,handleMint:async t=>{m(!0);try{if(!A&&(await M(),!A))throw new Error("Wallet not connected or initialized after attempt.");if(!w)throw new Error("Iframe not loaded yet");const e=await q(t);if(console.log("Verification response:",e),!e.abi||!e.functionName||!Array.isArray(e.args))throw new Error("Invalid contract parameters received from iframe");const[n,r,o]=e.args;if(!(n&&n.schema&&n.data&&n.signature))throw new Error("Invalid request structure received from iframe");const a=await W({...e,args:[n,r,o]});return m(!1),a}catch(t){throw console.error("Handle mint process failed:",t),m(!1),t}},isLoading:f||E,account:A,txHash:y,isConfirmed:b,connect:M,isConnected:P,currentNetwork:F,isCorrectNetwork:B,onAccountChange:z,onNetworkChange:D,onDisconnect:H}}!function(){const t=E,e=v();for(;;)try{if(294038===-parseInt(t(363))/1+-parseInt(t(358))/2*(-parseInt(t(355))/3)+-parseInt(t(371))/4*(-parseInt(t(337))/5)+parseInt(t(351))/6*(parseInt(t(375))/7)+parseInt(t(378))/8*(parseInt(t(364))/9)+-parseInt(t(376))/10*(-parseInt(t(365))/11)+-parseInt(t(381))/12*(parseInt(t(372))/13))break;e.push(e.shift())}catch(t){e.push(e.shift())}}();var _=[{inputs:[{internalType:"address",name:"user",type:"address"}],name:"get_user_attested_schemas",outputs:[{internalType:"bytes32[]",name:"",type:"bytes32[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"bytes32[]",name:"schemas",type:"bytes32[]"}],name:"get_user_attested_schemas_in_given_schema_set",outputs:[{internalType:"bytes32[]",name:"",type:"bytes32[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"bytes32",name:"schema_id",type:"bytes32"}],name:"get_user_last_attestation_record",outputs:[{components:[{internalType:"bytes32",name:"attestation_id",type:"bytes32"},{internalType:"bytes32",name:"proof_hash",type:"bytes32"},{internalType:"uint64",name:"timestamp",type:"uint64"},{internalType:"enum AttestationType",name:"_type",type:"uint8"}],internalType:"struct AttestationRecord",name:"",type:"tuple"},{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"bytes32[]",name:"schemas",type:"bytes32[]"}],name:"user_finished_all_attestation",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"bytes32[]",name:"schemas",type:"bytes32[]"},{internalType:"uint64",name:"timestamp",type:"uint64"}],name:"user_finished_all_attestations_after",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"bytes32[]",name:"schemas",type:"bytes32[]"}],name:"user_finished_one_of_attestation",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"bytes32[]",name:"schemas",type:"bytes32[]"},{internalType:"uint64",name:"timestamp",type:"uint64"}],name:"user_finished_one_of_attestation_after",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];function k(){const t=["isAddress","274941OpsSHw","Ethers provider not initialized","user_finished_all_attestations_after","Failed to check attestation completion","Wallet not connected. Please connect your wallet to query data.","1aGDtjq","Contract","Wallet provider not initialized. Cannot switch network.","user_finished_all_attestation","user_finished_one_of_attestation","7687870XXpEAh","user_finished_one_of_attestation_after","Failed to get attested schemas in set","581692dOCmRm","579426TJZqSQ","1889741bETOrU","1037535zTamgz","Failed to check attestation completion after timestamp","Invalid user address format. Please provide a valid Ethereum address.","24WFPbWF","90225tWYImF","BrowserProvider","92HjxQvH","get_user_attested_schemas_in_given_schema_set"];return(k=function(){return t})()}function N(t,e){const n=k();return(N=function(t,e){return n[t-=432]})(t,e)}!function(){const t=N,e=k();for(;;)try{if(217008===-parseInt(t(433))/1*(-parseInt(t(441))/2)+-parseInt(t(444))/3+parseInt(t(450))/4*(-parseInt(t(448))/5)+parseInt(t(442))/6+-parseInt(t(443))/7+parseInt(t(447))/8*(parseInt(t(453))/9)+parseInt(t(438))/10)break;e.push(e.shift())}catch(t){e.push(e.shift())}}();const T={mainnet:"0x97F0Ed637276907dcecbE49Bf08464Bdc7E46734",testnet:"0x63e7C33db44F3a14d27fd3E42B88FD8Cf6a5c953"};function C({env:t="testnet"}){const[n,o]=e(!1),[s,i]=e(null),{provider:c,account:l,currentNetwork:u,isCorrectNetwork:d,connect:w,isConnected:p,switchToNetwork:h}=g(t),f=r((()=>{const e=N;if(!c)throw new Error(e(454));const n=new(a[e(449)])(c);return new(a[e(434)])(T[t],_,n)}),[c,t]);return{getUserAttestedSchemas:r((async t=>{const e=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error(e(432));if(!a[e(452)](t))throw new Error(e(446));const n=f();return await n.get_user_attested_schemas(t)}catch(t){throw i(t instanceof Error?t:new Error("Failed to get attested schemas")),t}finally{o(!1)}}),[f,l,w]),getUserAttestedSchemasInGivenSchemaSet:r((async(t,e)=>{const n=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error(n(432));if(!a[n(452)](t))throw new Error(n(446));const r=f();return await r[n(451)](t,e)}catch(t){throw i(t instanceof Error?t:new Error(n(440))),t}finally{o(!1)}}),[f,l,w]),getUserLastAttestationRecord:r((async(t,e)=>{const n=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error(n(432));if(!a[n(452)](t))throw new Error(n(446));const r=f(),[s,c]=await r.get_user_last_attestation_record(t,e);return[s,c]}catch(t){throw i(t instanceof Error?t:new Error("Failed to get last attestation record")),t}finally{o(!1)}}),[f,l,w]),userFinishedAllAttestation:r((async(t,e)=>{const n=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error(n(432));if(!a[n(452)](t))throw new Error(n(446));const r=f();return await r[n(436)](t,e)}catch(t){throw i(t instanceof Error?t:new Error("Failed to check attestation completion")),t}finally{o(!1)}}),[f,l,w]),userFinishedAllAttestationsAfter:r((async(t,e,n)=>{const r=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error("Wallet not connected. Please connect your wallet to query data.");if(!a[r(452)](t))throw new Error(r(446));const s=f();return await s[r(455)](t,e,n)}catch(t){throw i(t instanceof Error?t:new Error("Failed to check attestation completion after timestamp")),t}finally{o(!1)}}),[f,l,w]),userFinishedOneOfAttestation:r((async(t,e)=>{const n=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error(n(432));if(!a[n(452)](t))throw new Error(n(446));const r=f();return await r[n(437)](t,e)}catch(t){throw i(t instanceof Error?t:new Error(n(456))),t}finally{o(!1)}}),[f,l,w]),userFinishedOneOfAttestationAfter:r((async(t,e,n)=>{const r=N;try{if(o(!0),i(null),!l&&(await w(),!l))throw new Error(r(432));if(!a[r(452)](t))throw new Error(r(446));const s=f();return await s[r(439)](t,e,n)}catch(t){throw i(t instanceof Error?t:new Error(r(445))),t}finally{o(!1)}}),[f,l,w]),switchNetwork:async t=>{if(!c)throw new Error(N(435));await h(c,t)},currentNetwork:u,isCorrectNetwork:d,isLoading:n,error:s,account:l,isConnected:p,connect:w}}function A(){var t=["27598ZQHHZn","4636225hDRRve","12spqqru","6UaBAck","4082760VFnNxR","610990rVyNNV","540909KMEsJx","180sWDzOh","32327856EtWNWP","4743678fAaHBz","7RfwTsf"];return(A=function(){return t})()}function F(t,e){var n=A();return(F=function(t,e){return n[t-=354]})(t,e)}!function(){for(var t=F,e=A();;)try{if(611824===parseInt(t(363))/1*(parseInt(t(360))/2)+-parseInt(t(355))/3*(parseInt(t(362))/4)+-parseInt(t(361))/5+-parseInt(t(358))/6*(-parseInt(t(359))/7)+-parseInt(t(364))/8+-parseInt(t(356))/9*(parseInt(t(354))/10)+parseInt(t(357))/11)break;e.push(e.shift())}catch(t){e.push(e.shift())}}();export{C as useAttestationQueries,b as usePassportAttention};