gun-eth 1.4.21 → 1.4.23
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/gun-eth.cjs.js +1534 -68
- package/dist/gun-eth.cjs.js.map +1 -1
- package/dist/gun-eth.esm.js +1534 -68
- package/dist/gun-eth.esm.js.map +1 -1
- package/dist/gun-eth.min.js +1 -1
- package/dist/gun-eth.min.js.map +1 -1
- package/package.json +19 -21
- package/dist/gun-eth.js +0 -1382
- package/dist/gun-eth.js.map +0 -1
- package/src/abis/abis.js +0 -391
- package/src/config/contract-address.json +0 -4
- package/src/config/local.js +0 -29
- package/src/index.js +0 -953
package/dist/gun-eth.min.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("gun"),require("gun/sea.js"),require("ethers")):"function"==typeof define&&define.amd?define(["exports","gun","gun/sea.js","ethers"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GunEth={},e.Gun,e.SEA,e.ethers)}(this,(function(e,t,n,a){"use strict";var r="undefined"!=typeof document?document.currentScript:null,s={STEALTH_ANNOUNCER_ADDRESS:"",PROOF_OF_INTEGRITY_ADDRESS:""};let o={PROOF_OF_INTEGRITY_ADDRESS:"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",STEALTH_ANNOUNCER_ADDRESS:"0x5FbDB2315678afecb367f032d93F642f64180aa3"};if("undefined"==typeof window){const{fileURLToPath:e}=require("url"),{dirname:t}=require("path"),{readFileSync:n}=require("fs"),{join:a}=require("path");try{const s=e("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(s).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("gun-eth.min.js",document.baseURI).href),i=n(a(t(s),"contract-address.json"),"utf8");o=JSON.parse(i),console.log("Loaded contract addresses:",o)}catch(e){console.warn("Warning: contract-address.json not found or invalid")}}const i={CHAIN_ID:1337,PROOF_OF_INTEGRITY_ADDRESS:o.PROOF_OF_INTEGRITY_ADDRESS,STEALTH_ANNOUNCER_ADDRESS:o.STEALTH_ANNOUNCER_ADDRESS,RPC_URL:"http://127.0.0.1:8545",GUN_PEER:"http://localhost:8765/gun"},c={optimismSepolia:{STEALTH_ANNOUNCER_ADDRESS:"",PROOF_OF_INTEGRITY_ADDRESS:"",RPC_URL:"https://sepolia.optimism.io",CHAIN_ID:11155420},arbitrumSepolia:{STEALTH_ANNOUNCER_ADDRESS:"",PROOF_OF_INTEGRITY_ADDRESS:"",RPC_URL:"https://sepolia-rollup.arbitrum.io/rpc",CHAIN_ID:421614},localhost:{RPC_URL:"http://127.0.0.1:8545",CHAIN_ID:1337}};function u(e){let t;if("localhost"===e)try{return t={...c.localhost,...s},console.log("Using local addresses:",t),t}catch(e){throw console.warn("No local addresses found"),new Error("No local addresses found. Did you run local deployment?")}if(t=c[e],!t)throw new Error(`Chain ${e} not supported. Supported chains: ${Object.keys(c).join(", ")}`);return t}const d=[{inputs:[{internalType:"address",name:"_devAddress",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],name:"StealthPaymentAnnounced",type:"event"},{anonymous:!1,inputs:[{internalType:"address",name:"newAddress",type:"address"}],name:"DevAddressUpdated",type:"event"},{anonymous:!1,inputs:[{internalType:"uint256",name:"newFee",type:"uint256"}],name:"DevFeeUpdated",type:"event"},{inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"}],name:"announcePayment",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"devAddress",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"devFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getAnnouncementsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"fromIndex",type:"uint256"},{internalType:"uint256",name:"toIndex",type:"uint256"}],name:"getAnnouncementsInRange",outputs:[{components:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct StealthAnnouncer.StealthAnnouncement[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_newFee",type:"uint256"}],name:"updateDevFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newAddress",type:"address"}],name:"updateDevAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawStuckETH",outputs:[],stateMutability:"nonpayable",type:"function"}],l=[{inputs:[{internalType:"bytes[]",name:"nodeIds",type:"bytes[]"},{internalType:"bytes32[]",name:"contentHashes",type:"bytes32[]"}],name:"batchUpdateData",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes",name:"nodeId",type:"bytes"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"},{indexed:!1,internalType:"address",name:"updater",type:"address"}],name:"DataUpdated",type:"event"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"}],name:"getLatestRecord",outputs:[{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"updateData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"verifyData",outputs:[{internalType:"bool",name:"",type:"bool"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}],p=u("optimismSepolia"),y=p.STEALTH_ANNOUNCER_ADDRESS;let h;p.PROOF_OF_INTEGRITY_ADDRESS;let g="",f="";const m="Access GunDB with Ethereum";let w={PROOF_OF_INTEGRITY_ADDRESS:null,STEALTH_ANNOUNCER_ADDRESS:y};if("undefined"==typeof window){const{fileURLToPath:e}=require("url"),{dirname:t}=require("path"),{readFileSync:n}=require("fs"),a=require("path"),s=e("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(s).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("gun-eth.min.js",document.baseURI).href),o=t(s);try{const e=n(a.join(o,"contract-address.json"),"utf8");w=JSON.parse(e),console.log("Loaded contract addresses:",w)}catch(e){console.warn("Warning: contract-address.json not found or invalid")}}function S(){return a.ethers.hexlify(a.ethers.randomBytes(32)).slice(2)}function b(e){try{const t=a.ethers.hexlify(e),n=a.ethers.keccak256(t);return console.log("Generated password:",n),n}catch(e){return console.error("Error generating password:",e),null}}function E(e){const t="0x"+(e=>{const t="=".repeat((4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,a=atob(n);return Array.from(a,(e=>e.charCodeAt(0).toString(16).padStart(2,"0"))).join("")})(e),n=new a.ethers.Wallet(t);return{account:n,publicKey:n.address,privateKey:t}}const A=async()=>{if(g&&f){const e=new a.ethers.JsonRpcProvider(g,{chainId:i.CHAIN_ID,name:"localhost"});return new a.ethers.Wallet(f,e)}if("undefined"!=typeof window&&void 0!==window.ethereum){await window.ethereum.request({method:"eth_requestAccounts"});return new a.ethers.BrowserProvider(window.ethereum).getSigner()}throw new Error("No valid Ethereum provider found")};function T(e,t){try{const n=Buffer.from(e,"base64"),r=a.ethers.keccak256(a.ethers.concat([n,a.ethers.getBytes(t)])),s=new a.ethers.Wallet(r);return console.log("Debug deriveStealthAddress:",{sharedSecretHex:a.ethers.hexlify(n),spendingPublicKey:t,stealthPrivateKey:r,stealthAddress:s.address}),{stealthPrivateKey:r,stealthAddress:s.address,wallet:s}}catch(e){throw console.error("Error in deriveStealthAddress:",e),e}}t.chain.MESSAGE_TO_SIGN=m,t.chain.setSigner=function(e,t){return g=e,f=t,console.log("Standalone configuration set"),this},t.chain.getSigner=A(),t.chain.verifySignature=async function(e,t){try{return a.ethers.verifyMessage(e,t)}catch(e){return console.error("Error verifying signature:",e),null}},t.chain.generatePassword=function(e){return b(e)},t.chain.createSignature=async function(e){try{if(e!==m)throw new Error("Invalid message, valid message is: "+m);const t=await A(),n=await t.signMessage(e);return console.log("Signature created:",n),n}catch(e){return console.error("Error creating signature:",e),null}},t.chain.createAndStoreEncryptedPair=async function(e,t){try{const a=this,r=await n.pair(),s=await n.pair(),o=await n.pair(),i=b(t),c=await n.encrypt(JSON.stringify(r),i),u=await n.encrypt(JSON.stringify(s),i),d=await n.encrypt(JSON.stringify(o),i),l=E(s.priv),p=E(o.priv);a.get("gun-eth").get("users").get(e).put({pair:c,v_pair:u,s_pair:d,publicKeys:{viewingPublicKey:s.epub,viewingPublicKey:s.epub,spendingPublicKey:p.publicKey,ethViewingAddress:l.publicKey}}),console.log("Encrypted pairs and public keys stored for:",e)}catch(e){throw console.error("Error creating and storing encrypted pair:",e),e}},t.chain.getAndDecryptPair=async function(e,t){try{const a=this,r=await a.get("gun-eth").get("users").get(e).get("pair").then();if(!r)throw new Error("No encrypted data found for this address");const s=b(t),o=await n.decrypt(r,s);return console.log(o),o}catch(e){return console.error("Error retrieving and decrypting pair:",e),null}},t.chain.proof=function(e,t,n,r){if(console.log("Proof plugin called with:",{chain:e,nodeId:t,data:n}),"function"!=typeof r)return console.error("Callback must be a function"),this;try{const s=isLocalEnvironment()?"localhost":e,o=u(s);console.log(`Using ${s} configuration:`,o);new a.ethers.Contract(o.PROOF_OF_INTEGRITY_ADDRESS,l,signer);const i=async(e,t)=>{console.log("Verifying on chain:",{nodeId:e,contentHash:t});const n=await A(),r=new a.ethers.Contract(h,l,n),[s,o,i]=await r.verifyData(a.ethers.toUtf8Bytes(e),t);return console.log("Verification result:",{isValid:s,timestamp:o,updater:i}),{isValid:s,timestamp:o,updater:i}},c=async(e,t)=>{console.log("Writing on chain:",{nodeId:e,contentHash:t});const n=await A(),r=new a.ethers.Contract(h,l,n),s=await r.updateData(a.ethers.toUtf8Bytes(e),t);console.log("Transaction sent:",s.hash);const o=await s.wait();return console.log("Transaction confirmed:",o),s},d=async e=>{const t=await A(),n=new a.ethers.Contract(h,l,t),[r,s,o]=await n.getLatestRecord(a.ethers.toUtf8Bytes(e));return console.log("Latest record from blockchain:",{nodeId:e,contentHash:r,timestamp:s,updater:o}),{contentHash:r,timestamp:s,updater:o}};if(t&&!n)gun.get(t).once((async e=>{if(!e)return void(r&&r({err:"Node not found in GunDB"}));console.log("existingData",e);const n=e._contentHash;if(console.log("contentHash",n),n)try{const{isValid:e,timestamp:a,updater:s}=await i(t,n),o=await d(t);e?r&&r({ok:!0,message:"Data verified on blockchain",timestamp:a,updater:s,latestRecord:o}):r&&r({ok:!1,message:"Data not verified on blockchain",latestRecord:o})}catch(e){r&&r({err:e.message})}else r&&r({err:"No content hash found for this node"})}));else if(n&&!t){const e=S(),t=JSON.stringify(n),s=a.ethers.keccak256(a.ethers.toUtf8Bytes(t));gun.get(e).put({...n,_contentHash:s},(async t=>{if(console.log("ack",t),t.err)r&&r({err:"Error saving data to GunDB"});else try{const t=await c(e,s);r&&r({ok:!0,message:"Data written to GunDB and blockchain",nodeId:e,txHash:t.hash})}catch(e){r&&r({err:e.message})}}))}else r&&r({err:"Invalid input. Provide either nodeId or data, not both."});return gun}catch(e){return r({err:e.message}),this}},t.chain.gunToEthAccount=function(e){return E(e)},t.chain.generateStealthAddress=async function(e,t){try{const a=this,r=await a.get("gun-eth").get("users").get(e).get("publicKeys").then();if(!r||!r.viewingPublicKey||!r.spendingPublicKey)throw new Error("Recipient's public keys not found");const s=await this.verifySignature(m,t),o=b(t),i=await a.get("gun-eth").get("users").get(s).then();if(!i||!i.s_pair)throw new Error("Sender's keys not found");let c;try{const e=await n.decrypt(i.s_pair,o);c="string"==typeof e?JSON.parse(e):e}catch(e){throw console.error("Error decrypting spending pair:",e),new Error("Unable to decrypt spending pair")}const u=await n.secret(r.viewingPublicKey,c);if(!u)throw new Error("Unable to generate shared secret");console.log("Generate shared secret:",u);const{stealthAddress:d}=T(u,r.spendingPublicKey);return{stealthAddress:d,senderPublicKey:c.epub,spendingPublicKey:r.spendingPublicKey}}catch(e){throw console.error("Error generating stealth address:",e),e}},t.chain.publishStealthKeys=async function(e){try{const t=this,a=await this.verifySignature(m,e),r=b(e),s=await t.get("gun-eth").get("users").get(a).then();if(!s||!s.v_pair||!s.s_pair)throw new Error("Keys not found");const o=JSON.parse(await n.decrypt(s.v_pair,r)),i=JSON.parse(await n.decrypt(s.s_pair,r)),c=E(o.priv),u=E(i.priv);t.get("gun-eth").get("users").get(a).get("publicKeys").put({viewingPublicKey:c.publicKey,spendingPublicKey:u.publicKey}),console.log("Stealth public keys published successfully")}catch(e){throw console.error("Error publishing stealth keys:",e),e}},t.chain.recoverStealthFunds=async function(e,t,a,r){try{const s=this,o=b(a),i=await this.verifySignature(m,a),c=await s.get("gun-eth").get("users").get(i).then();if(!c||!c.v_pair||!c.s_pair)throw new Error("Keys not found");let u;try{const e=await n.decrypt(c.v_pair,o);u="string"==typeof e?JSON.parse(e):e}catch(e){throw console.error("Error decrypting keys:",e),new Error("Unable to decrypt keys")}const d=await n.secret(t,u);if(!d)throw new Error("Unable to generate shared secret");console.log("Recover shared secret:",d);const{wallet:l,stealthAddress:p}=T(d,r);if(p.toLowerCase()!==e.toLowerCase())throw console.error("Mismatch:",{recovered:p,expected:e,sharedSecret:d}),new Error("Recovered stealth address does not match");return{wallet:l,address:p}}catch(e){throw console.error("Error recovering stealth funds:",e),e}},t.chain.announceStealthPayment=async function(e,t,n,r,s={onChain:!1,chain:"optimismSepolia"}){try{const o=this,i=await this.verifySignature(m,r);if(s.onChain){const r=await A(),o=u(s.chain).STEALTH_ANNOUNCER_ADDRESS;console.log("Using contract address:",o);const i=new a.ethers.Contract(o,d,r),c=await i.devFee();console.log("Dev fee:",c.toString());const l=await i.announcePayment(t,n,e,{value:c});console.log("Transaction sent:",l.hash);const p=await l.wait();console.log("Transaction confirmed:",p.hash),console.log("Stealth payment announced on-chain (dev fee paid)")}else o.get("gun-eth").get("stealth-payments").set({stealthAddress:e,senderAddress:i,senderPublicKey:t,spendingPublicKey:n,timestamp:Date.now()}),console.log("Stealth payment announced off-chain")}catch(e){throw console.error("Error announcing stealth payment:",e),console.error("Error details:",e.stack),e}},t.chain.getStealthPayments=async function(e,t={source:"both"}){try{const n=[];if("onChain"===t.source||"both"===t.source){const t=await A(),r="development"===process.env.NODE_ENV?i.STEALTH_ANNOUNCER_ADDRESS:y,s=new a.ethers.Contract(r,d,t);try{const t=await s.getAnnouncementsCount(),a=Number(t.toString());if(console.log("Total on-chain announcements:",a),a>0){const t=100,r=a-1;for(let a=0;a<=r;a+=t){const o=Math.min(a+t-1,r),i=await s.getAnnouncementsInRange(a,o);for(const t of i)try{if(!(t&&t.stealthAddress&&t.senderPublicKey&&t.spendingPublicKey)){console.log("Invalid announcement:",t);continue}const a=await this.recoverStealthFunds(t.stealthAddress,t.senderPublicKey,e,t.spendingPublicKey);n.push({stealthAddress:t.stealthAddress,senderPublicKey:t.senderPublicKey,spendingPublicKey:t.spendingPublicKey,timestamp:Number(t.timestamp),source:"onChain",wallet:a})}catch(e){console.log(`Announcement not for us: ${t.stealthAddress}`);continue}}}}catch(e){console.error("Error retrieving on-chain announcements:",e)}}if("offChain"===t.source||"both"===t.source){const e=this,t=await new Promise((t=>{const n=[];e.get("gun-eth").get("stealth-payments").get(recipientAddress).map().once(((e,t)=>{e?.stealthAddress&&n.push({...e,id:t,source:"offChain"})})),setTimeout((()=>t(n)),2e3)}));n.push(...t)}return console.log(`Found ${n.length} stealth payments`),n}catch(e){throw console.error("Error retrieving stealth payments:",e),e}},t.chain.cleanStealthPayments=async function(e){try{const t=this,n=await t.get("gun-eth").get("stealth-payments").get(e).map().once().then();n&&Object.keys(n).forEach((async a=>{const r=n[a];r&&r.stealthAddress&&r.senderPublicKey&&r.spendingPublicKey||await t.get("gun-eth").get("stealth-payments").get(e).get(a).put(null)}))}catch(e){console.error("Error cleaning stealth payments:",e)}};class _{static generateRandomId=S;static generatePassword=b;static gunToEthAccount=E;static getSigner=A;static deriveStealthAddress=T;static chainMethods={setSigner:t.chain.setSigner,getSigner:t.chain.getSigner,verifySignature:t.chain.verifySignature,generatePassword:t.chain.generatePassword,createSignature:t.chain.createSignature,createAndStoreEncryptedPair:t.chain.createAndStoreEncryptedPair,getAndDecryptPair:t.chain.getAndDecryptPair,proof:t.chain.proof,gunToEthAccount:t.chain.gunToEthAccount,generateStealthAddress:t.chain.generateStealthAddress,publishStealthKeys:t.chain.publishStealthKeys,recoverStealthFunds:t.chain.recoverStealthFunds,announceStealthPayment:t.chain.announceStealthPayment,getStealthPayments:t.chain.getStealthPayments,cleanStealthPayments:t.chain.cleanStealthPayments};static MESSAGE_TO_SIGN=m;static PROOF_CONTRACT_ADDRESS=h;static LOCAL_CONFIG=i}e.default=t,e.GunEth=_,e.MESSAGE_TO_SIGN=m,e.deriveStealthAddress=T,e.generatePassword=b,e.generateRandomId=S,e.getSigner=A,e.gunToEthAccount=E,Object.defineProperty(e,"__esModule",{value:!0})}));
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("gun"),require("ethers")):"function"==typeof define&&define.amd?define(["exports","gun","ethers"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GunEth={},e.Gun,e.ethers)}(this,(function(e,t,n){"use strict";var r="undefined"!=typeof document?document.currentScript:null,a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i={exports:{}};!function(e){!function(){function t(e,n){return n?function(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}(e):e.slice?t[r(e)]:function(n,a){e(n={exports:{}}),t[r(a)]=n.exports};function r(e){return e.split("/").slice(-1).toString().replace(".js","")}}var n=e;t((function(e){"undefined"!=typeof self&&(e.window=self),"undefined"!=typeof window&&(e.window=window);var t=(e.window||e).SEA||{};(t.window=e.window)&&(t.window.SEA=t);try{undefined+""!=typeof n&&(n.exports=t)}catch(e){}e.exports=t}))(t,"./root"),t((function(e){var n=t("./root");try{n.window&&location.protocol.indexOf("s")<0&&location.host.indexOf("localhost")<0&&!/^127\.\d+\.\d+\.\d+$/.test(location.hostname)&&location.protocol.indexOf("file:")<0&&(console.warn("HTTPS needed for WebCrypto in SEA, redirecting..."),location.protocol="https:")}catch(e){}}))(t,"./https"),t((function(e){var n;if(n+""==typeof btoa){if(n+""==typeof Buffer)try{a.Buffer=t("buffer",1).Buffer}catch(e){console.log("Please `npm install buffer` or add it to your package.json !")}a.btoa=function(e){return Buffer.from(e,"binary").toString("base64")},a.atob=function(e){return Buffer.from(e,"base64").toString("binary")}}}))(t,"./base64"),t((function(e){function n(){}t("./base64"),Object.assign(n,{from:Array.from}),n.prototype=Object.create(Array.prototype),n.prototype.toString=function(e,t,n){e=e||"utf8",t=t||0;const r=this.length;if("hex"===e){const e=new Uint8Array(this);return[...Array((n&&n+1||r)-t).keys()].map((n=>e[n+t].toString(16).padStart(2,"0"))).join("")}return"utf8"===e?Array.from({length:(n||r)-t},((e,n)=>String.fromCharCode(this[n+t]))).join(""):"base64"===e?btoa(this):void 0},e.exports=n}))(t,"./array"),t((function(e){t("./base64");var n=t("./array");function r(...e){return console.warn("new SafeBuffer() is depreciated, please use SafeBuffer.from()"),r.from(...e)}r.prototype=Object.create(Array.prototype),Object.assign(r,{from(){if(!Object.keys(arguments).length||null==arguments[0])throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");const e=arguments[0];let t;if("string"==typeof e){const r=arguments[1]||"utf8";if("hex"===r){const r=e.match(/([\da-fA-F]{2})/g).map((e=>parseInt(e,16)));if(!r||!r.length)throw new TypeError("Invalid first argument for type 'hex'.");t=n.from(r)}else if("utf8"===r||"binary"===r){const r=e.length,a=new Uint16Array(r);Array.from({length:r},((t,n)=>a[n]=e.charCodeAt(n))),t=n.from(a)}else if("base64"===r){const r=atob(e),a=r.length,o=new Uint8Array(a);Array.from({length:a},((e,t)=>o[t]=r.charCodeAt(t))),t=n.from(o)}else"binary"===r?t=n.from(e):console.info("SafeBuffer.from unknown encoding: "+r);return t}e.byteLength;if(e.byteLength?e.byteLength:e.length){let t;return e instanceof ArrayBuffer&&(t=new Uint8Array(e)),n.from(t||e)}},alloc:(e,t=0)=>n.from(new Uint8Array(Array.from({length:e},(()=>t)))),allocUnsafe:e=>n.from(new Uint8Array(Array.from({length:e}))),concat(e){if(!Array.isArray(e))throw new TypeError("First argument must be Array containing ArrayBuffer or Uint8Array instances.");return n.from(e.reduce(((e,t)=>e.concat(Array.from(t))),[]))}}),r.prototype.from=r.from,r.prototype.toString=n.prototype.toString,e.exports=r}))(t,"./buffer"),t((function(e){const r=t("./root"),a={Buffer:t("./buffer")};var o={};if(JSON.parseAsync=JSON.parseAsync||function(e,t,n){try{t(undefined,JSON.parse(e,n))}catch(e){t(e)}},JSON.stringifyAsync=JSON.stringifyAsync||function(e,t,n,r){try{t(undefined,JSON.stringify(e,n,r))}catch(e){t(e)}},a.parse=function(e,t){return new Promise((function(n,r){JSON.parseAsync(e,(function(e,t){e?r(e):n(t)}),t)}))},a.stringify=function(e,t,n){return new Promise((function(r,a){JSON.stringifyAsync(e,(function(e,t){e?a(e):r(t)}),t,n)}))},r.window&&(a.crypto=r.window.crypto||r.window.msCrypto,a.subtle=(a.crypto||o).subtle||(a.crypto||o).webkitSubtle,a.TextEncoder=r.window.TextEncoder,a.TextDecoder=r.window.TextDecoder,a.random=e=>a.Buffer.from(a.crypto.getRandomValues(new Uint8Array(a.Buffer.alloc(e))))),!a.TextDecoder){const{TextEncoder:e,TextDecoder:r}=t((undefined+""==typeof n?".":"")+"./lib/text-encoding",1);a.TextDecoder=r,a.TextEncoder=e}if(!a.crypto)try{var i=t("crypto",1);Object.assign(a,{crypto:i,random:e=>a.Buffer.from(i.randomBytes(e))});const{Crypto:e}=t("@peculiar/webcrypto",1);a.ossl=a.subtle=new e({directory:"ossl"}).subtle}catch(e){console.log("Please `npm install @peculiar/webcrypto` or add it to your package.json !")}e.exports=a}))(t,"./shim"),t((function(e){var n=t("./root"),r=t("./shim"),a={pbkdf2:{hash:{name:"SHA-256"},iter:1e5,ks:64},ecdsa:{pair:{name:"ECDSA",namedCurve:"P-256"},sign:{name:"ECDSA",hash:{name:"SHA-256"}}},ecdh:{name:"ECDH",namedCurve:"P-256"},jwk:function(e,t){var n={kty:"EC",crv:"P-256",x:(e=e.split("."))[0],y:e[1],ext:!0};return n.key_ops=t?["sign"]:["verify"],t&&(n.d=t),n},keyToJwk:function(e){return{kty:"oct",k:e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,""),ext:!1,alg:"A256GCM"}},recall:{validity:43200,hook:function(e){return e}},check:function(e){return"string"==typeof e&&"SEA{"===e.slice(0,4)},parse:async function(e){try{var t="string"==typeof e;return t&&"SEA{"===e.slice(0,4)&&(e=e.slice(3)),t?await r.parse(e):e}catch(e){}return e}};n.opt=a,e.exports=a}))(t,"./settings"),t((function(e){var n=t("./shim");e.exports=async function(e,t){var r="string"==typeof e?e:await n.stringify(e),a=await n.subtle.digest({name:t||"SHA-256"},(new n.TextEncoder).encode(r));return n.Buffer.from(a)}}))(t,"./sha256"),t((function(e){const n=t("./shim"),r=n.subtle,a=n.ossl?n.ossl:r;e.exports=e=>a.digest({name:"SHA-1"},new ArrayBuffer(e))}))(t,"./sha1"),t((function(e){var n=t("./root"),r=t("./shim"),a=t("./settings"),o=t("./sha256");n.work=n.work||(async(e,t,i,s)=>{try{var c=(t||{}).epub||t;if(s=s||{},c instanceof Function&&(i=c,c=undefined),e="string"==typeof e?e:await r.stringify(e),"sha"===(s.name||"").toLowerCase().slice(0,3)){var u=r.Buffer.from(await o(e,s.name),"binary").toString(s.encode||"base64");if(i)try{i(u)}catch(e){console.log(e)}return u}c=c||r.random(9);var p=await(r.ossl||r.subtle).importKey("raw",(new r.TextEncoder).encode(e),{name:s.name||"PBKDF2"},!1,["deriveBits"]),l=await(r.ossl||r.subtle).deriveBits({name:s.name||"PBKDF2",iterations:s.iterations||a.pbkdf2.iter,salt:(new r.TextEncoder).encode(s.salt||c),hash:s.hash||a.pbkdf2.hash},p,s.length||8*a.pbkdf2.ks);e=r.random(e.length);var f=r.Buffer.from(l,"binary").toString(s.encode||"base64");if(i)try{i(f)}catch(e){console.log(e)}return f}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(i&&i())}}),e.exports=n.work}))(t,"./work"),t((function(e){var n=t("./root"),r=t("./shim");t("./settings"),n.name=n.name||(async(e,t)=>{try{if(e)try{e()}catch(e){console.log(e)}return}catch(t){if(console.log(t),n.err=t,n.throw)throw t;return void(e&&e())}}),n.pair=n.pair||(async(e,t)=>{try{var a=r.ossl||r.subtle,o=await r.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]).then((async e=>{var t={};t.priv=(await r.subtle.exportKey("jwk",e.privateKey)).d;var n=await r.subtle.exportKey("jwk",e.publicKey);return t.pub=n.x+"."+n.y,t}));try{var i=await a.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]).then((async e=>{var t={};t.epriv=(await a.exportKey("jwk",e.privateKey)).d;var n=await a.exportKey("jwk",e.publicKey);return t.epub=n.x+"."+n.y,t}))}catch(e){if(n.window)throw e;if("Error: ECDH is not a supported algorithm"!=e)throw e;console.log("Ignoring ECDH...")}i=i||{};var s={pub:o.pub,priv:o.priv,epub:i.epub,epriv:i.epriv};if(e)try{e(s)}catch(e){console.log(e)}return s}catch(t){if(console.log(t),n.err=t,n.throw)throw t;return void(e&&e())}}),e.exports=n.pair}))(t,"./pair"),t((function(e){var n,r=t("./root"),a=t("./shim"),o=t("./settings"),i=t("./sha256");r.sign=r.sign||(async(e,t,s,c)=>{try{if(c=c||{},!(t||c).priv){if(!r.I)throw"No signing key.";t=await r.I(null,{what:e,how:"sign",why:c.why})}if(n===e)throw"`undefined` not allowed.";var u=await o.parse(e),p=c.check=c.check||u;if(r.verify&&(r.opt.check(p)||p&&p.s&&p.m)&&n!==await r.verify(p,t)){var l=await o.parse(p);if(c.raw||(l="SEA"+await a.stringify(l)),s)try{s(l)}catch(e){console.log(e)}return l}var f=t.pub,y=t.priv,d=o.jwk(f,y),h=await i(u),g=await(a.ossl||a.subtle).importKey("jwk",d,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]).then((e=>(a.ossl||a.subtle).sign({name:"ECDSA",hash:{name:"SHA-256"}},e,new Uint8Array(h))));l={m:u,s:a.Buffer.from(g,"binary").toString(c.encode||"base64")};if(c.raw||(l="SEA"+await a.stringify(l)),s)try{s(l)}catch(e){console.log(e)}return l}catch(e){if(console.log(e),r.err=e,r.throw)throw e;return void(s&&s())}}),e.exports=r.sign}))(t,"./sign"),t((function(e){var n,r=t("./root"),a=t("./shim"),o=t("./settings"),i=t("./sha256");r.verify=r.verify||(async(e,t,s,c)=>{try{var u=await o.parse(e);if(!1===t){var p=await o.parse(u.m);if(s)try{s(p)}catch(e){console.log(e)}return p}c=c||{};var l,f,y,d=t.pub||t,h=r.opt.slow_leak?await r.opt.slow_leak(d):await(a.ossl||a.subtle).importKey("jwk",o.jwk(d),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),g=await i(u.m);try{if(l=a.Buffer.from(u.s,c.encode||"base64"),f=new Uint8Array(l),!(y=await(a.ossl||a.subtle).verify({name:"ECDSA",hash:{name:"SHA-256"}},h,f,new Uint8Array(g))))throw"Signature did not match."}catch(n){if(r.opt.fallback)return await r.opt.fall_verify(e,t,s,c)}var w=y?await o.parse(u.m):n;if(s)try{s(w)}catch(e){console.log(e)}return w}catch(e){if(console.log(e),r.err=e,r.throw)throw e;return void(s&&s())}}),e.exports=r.verify;var s={};r.opt.slow_leak=e=>{if(s[e])return s[e];var t=o.jwk(e);return s[e]=(a.ossl||a.subtle).importKey("jwk",t,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),s[e]};var c=r.opt;r.opt.fall_verify=async function(e,t,s,u,p){if(p===r.opt.fallback)throw"Signature did not match";p=p||1;var l=e||"";e=r.opt.unpack(e)||e;var f,y,d,h=await o.parse(e),g=t.pub||t,w=await r.opt.slow_leak(g),b=p<=r.opt.fallback?a.Buffer.from(await a.subtle.digest({name:"SHA-256"},(new a.TextEncoder).encode(await o.parse(h.m)))):await i(h.m);try{if(f=a.Buffer.from(h.s,u.encode||"base64"),y=new Uint8Array(f),!(d=await(a.ossl||a.subtle).verify({name:"ECDSA",hash:{name:"SHA-256"}},w,y,new Uint8Array(b))))throw"Signature did not match."}catch(e){try{f=a.Buffer.from(h.s,"utf8"),y=new Uint8Array(f),d=await(a.ossl||a.subtle).verify({name:"ECDSA",hash:{name:"SHA-256"}},w,y,new Uint8Array(b))}catch(e){if(!d)throw"Signature did not match."}}var m=d?await o.parse(h.m):n;if(c.fall_soul=l["#"],c.fall_key=l["."],c.fall_val=e,c.fall_state=l[">"],s)try{s(m)}catch(e){console.log(e)}return m},r.opt.fallback=2}))(t,"./verify"),t((function(e){var n=t("./shim"),r=t("./settings"),a=t("./sha256");e.exports=async(e,t,o)=>{const i=e+(t||n.random(8)).toString("utf8"),s=n.Buffer.from(await a(i),"binary"),c=r.keyToJwk(s);return await n.subtle.importKey("jwk",c,{name:"AES-GCM"},!1,["encrypt","decrypt"])}}))(t,"./aeskey"),t((function(e){var n=t("./root"),r=t("./shim");t("./settings");var a=t("./aeskey");n.encrypt=n.encrypt||(async(e,t,o,i)=>{try{i=i||{};var s=(t||i).epriv||t;if(undefined===e)throw"`undefined` not allowed.";if(!s){if(!n.I)throw"No encryption key.";s=(t=await n.I(null,{what:e,how:"encrypt",why:i.why})).epriv||t}var c="string"==typeof e?e:await r.stringify(e),u={s:r.random(9),iv:r.random(15)},p=await a(s,u.s,i).then((e=>r.subtle.encrypt({name:i.name||"AES-GCM",iv:new Uint8Array(u.iv)},e,(new r.TextEncoder).encode(c)))),l={ct:r.Buffer.from(p,"binary").toString(i.encode||"base64"),iv:u.iv.toString(i.encode||"base64"),s:u.s.toString(i.encode||"base64")};if(i.raw||(l="SEA"+await r.stringify(l)),o)try{o(l)}catch(e){console.log(e)}return l}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(o&&o())}}),e.exports=n.encrypt}))(t,"./encrypt"),t((function(e){var n=t("./root"),r=t("./shim"),a=t("./settings"),o=t("./aeskey");n.decrypt=n.decrypt||(async(e,t,i,s)=>{try{s=s||{};var c=(t||s).epriv||t;if(!c){if(!n.I)throw"No decryption key.";c=(t=await n.I(null,{what:e,how:"decrypt",why:s.why})).epriv||t}var u,p,l,f=await a.parse(e);try{u=r.Buffer.from(f.s,s.encode||"base64"),p=r.Buffer.from(f.iv,s.encode||"base64"),l=r.Buffer.from(f.ct,s.encode||"base64");var y=await o(c,u,s).then((e=>r.subtle.decrypt({name:s.name||"AES-GCM",iv:new Uint8Array(p),tagLength:128},e,new Uint8Array(l))))}catch(r){if("utf8"===s.encode)throw"Could not decrypt";if(n.opt.fallback)return s.encode="utf8",await n.decrypt(e,t,i,s)}var d=await a.parse(new r.TextDecoder("utf8").decode(y));if(i)try{i(d)}catch(e){console.log(e)}return d}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(i&&i())}}),e.exports=n.decrypt}))(t,"./decrypt"),t((function(e){var n=t("./root"),r=t("./shim");t("./settings"),n.secret=n.secret||(async(e,t,o,i)=>{try{if(i=i||{},!t||!t.epriv||!t.epub){if(!n.I)throw"No secret mix.";t=await n.I(null,{what:e,how:"secret",why:i.why})}var s=e.epub||e,c=t.epub,u=t.epriv,p=r.ossl||r.subtle,l=a(s),f=Object.assign({public:await p.importKey(...l,!0,[])},{name:"ECDH",namedCurve:"P-256"}),y=a(c,u),d=await p.importKey(...y,!1,["deriveBits"]).then((async e=>{var t=await p.deriveBits(f,e,256),n=new Uint8Array(t),r=await p.importKey("raw",n,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);return p.exportKey("jwk",r).then((({k:e})=>e))}));if(o)try{o(d)}catch(e){console.log(e)}return d}catch(e){if(console.log(e),n.err=e,n.throw)throw e;return void(o&&o())}});var a=(e,t)=>{var[n,r]=e.split("."),a=t?{d:t}:{};return["jwk",Object.assign(a,{x:n,y:r,kty:"EC",crv:"P-256",ext:!0}),{name:"ECDH",namedCurve:"P-256"}]};e.exports=n.secret}))(t,"./secret"),t((function(e){var n=t("./root");n.certify=n.certify||(async(e,t={},r,a,o={})=>{try{if(console.log("SEA.certify() is an early experimental community supported method that may change API behavior without warning in any future version."),e=(()=>{var t=[];if(e){if(("string"==typeof e||Array.isArray(e))&&e.indexOf("*")>-1)return"*";if("string"==typeof e)return e;if(Array.isArray(e)){if(1===e.length&&e[0])return"object"==typeof e[0]&&e[0].pub?e[0].pub:"string"==typeof e[0]?e[0]:null;e.map((e=>{"string"==typeof e?t.push(e):"object"==typeof e&&e.pub&&t.push(e.pub)}))}return"object"==typeof e&&e.pub?e.pub:t.length>0?t:null}})(),!e)return console.log("No certificant found.");const s=!o.expiry||"number"!=typeof o.expiry&&"string"!=typeof o.expiry?null:parseFloat(o.expiry),c=(t||{}).read?t.read:null,u=(t||{}).write?t.write:"string"==typeof t||Array.isArray(t)||t["+"]||t["#"]||t["."]||t["="]||t["*"]||t[">"]||t["<"]?t:null,p=(o||{}).block||(o||{}).blacklist||(o||{}).ban||{},l=p.read&&("string"==typeof p.read||(p.read||{})["#"])?p.read:null,f="string"==typeof p?p:p.write&&("string"==typeof p.write||p.write["#"])?p.write:null;if(!c&&!u)return console.log("No policy found.");const y=JSON.stringify({c:e,...s?{e:s}:{},...c?{r:c}:{},...u?{w:u}:{},...l?{rb:l}:{},...f?{wb:f}:{}});var i=await n.sign(y,r,null,{raw:1});if(o.raw||(i="SEA"+JSON.stringify(i)),a)try{a(i)}catch(e){console.log(e)}return i}catch(e){if(n.err=e,n.throw)throw e;return void(a&&a())}}),e.exports=n.certify}))(t,"./certify"),t((function(e){var n=t("./shim"),r=t("./root");r.work=t("./work"),r.sign=t("./sign"),r.verify=t("./verify"),r.encrypt=t("./encrypt"),r.decrypt=t("./decrypt"),r.certify=t("./certify"),r.random=r.random||n.random,r.Buffer=r.Buffer||t("./buffer"),r.keyid=r.keyid||(async e=>{try{const t=n.Buffer.concat(e.replace(/-/g,"+").replace(/_/g,"/").split(".").map((e=>n.Buffer.from(e,"base64")))),r=n.Buffer.concat([n.Buffer.from([153,t.length/256,t.length%256]),t]),a=await sha1hash(r),o=n.Buffer.from(a,"binary");return o.toString("hex",o.length-8)}catch(e){throw console.log(e),e}}),((r.window||{}).GUN||{}).SEA=r,e.exports=r}))(t,"./sea"),t((function(e){var r,a=t("./sea");function o(e){this._={$:this}}function i(){return r.state().toString(36).replace(".","")}r=a.window?a.window.GUN||{chain:{}}:t((undefined+""==typeof n?".":"")+"./gun",1),a.GUN=r,o.prototype=function(){function e(){}return e.prototype=r.chain,new e}(),o.prototype.constructor=o,r.chain.user=function(e){var t,n=this.back(-1);if(e)return e=a.opt.pub((e._||"")["#"])||e,n.get("~"+e);if(t=n.back("user"))return t;var r=n=n._,s=r.opt.uuid||i;return(r=(t=r.user=this.chain(new o))._).opt={},r.opt.uuid=function(e){var t=s(),r=n.user;return r&&(r=r.is)&&(r=r.pub)?(t="~"+r+"/"+t,e&&e.call&&e(null,t),t):t},t},r.User=o,o.GUN=r,o.SEA=r.SEA=a,e.exports=o}))(t,"./user"),t((function(e){var r;(""+r!=typeof GUN?GUN||{chain:{}}:t((""+r==typeof n?".":"")+"./gun",1)).chain.then=function(e,t){var n=this,r=new Promise((function(e,r){n.once(e,t)}));return e?r.then(e):r}}))(t,"./then"),t((function(e){var n=t("./user"),r=n.SEA,a=n.GUN,o=function(){};n.prototype.create=function(...e){var t,n="object"==typeof e[0]&&(e[0].pub||e[0].epub)?e[0]:"object"==typeof e[1]&&(e[1].pub||e[1].epub)?e[1]:null,i=n&&(n.pub||n.epub)?n.pub:"string"==typeof e[0]?e[0]:null,s=n&&(n.pub||n.epub)?n:i&&"string"==typeof e[1]?e[1]:null,c=e.filter((e=>"function"==typeof e))[0]||null,u=e&&e.length>1&&"object"==typeof e[e.length-1]?e[e.length-1]:{},p=this,l=p._,f=p.back(-1);if((c=c||o,!1!==(u=u||{}).check)&&(i||(t="No user."),(s||"").length<8&&(t="Password too short!"),t))return c({err:a.log(t)}),p;if(l.ing)return(c||o)({err:a.log("User is already being created or authenticated!"),wait:!0}),p;l.ing=!0;var y={a:function(e){if(y.pubs=e,e&&!u.already){var t={err:a.log("User already created!")};return l.ing=!1,(c||o)(t),void p.leave()}y.salt=String.random(64),r.work(s,y.salt,y.b)},b:function(e){y.proof=e,n?y.c(n):r.pair(y.c)},c:function(e){var t;y.pair=e||{},(t=l.root.user)&&(t._.sea=e,t.is={pub:e.pub,epub:e.epub,alias:i}),y.data={pub:e.pub},y.d()},d:function(){y.data.alias=i,y.e()},e:function(){y.data.epub=y.pair.epub,r.encrypt({priv:y.pair.priv,epriv:y.pair.epriv},y.proof,y.f,{raw:1})},f:function(e){y.data.auth=JSON.stringify({ek:e,s:y.salt}),y.g(y.data.auth)},g:function(e){var t;y.data.auth=y.data.auth||e,f.get(t="~"+y.pair.pub).put(y.data).on(y.h);var n={};n[t]={"#":t},f.get("~@"+i).put(n).get(t).on(y.i)},h:function(e,t,n,r){r.off(),y.h.ok=1,y.i()},i:function(e,t,r,a){a&&(y.i.ok=1,a.off()),y.h.ok&&y.i.ok&&(l.ing=!1,c({ok:0,pub:y.pair.pub}),o===c&&(n?p.auth(n):p.auth(i,s)))}};return f.get("~@"+i).once(y.a),p},n.prototype.leave=function(e,t){var n=this.back(-1)._.user;if(n&&(delete n.is,delete n._.is,delete n._.sea),r.window)try{var a={};delete(a=r.window.sessionStorage).recall,delete a.pair}catch(e){}return this}}))(t,"./create"),t((function(e){var n=t("./user"),r=n.SEA,a=n.GUN,o=function(){};function i(e){if("string"!=typeof e)return e;try{e=JSON.parse(e)}catch(t){e={}}return e}n.prototype.auth=function(...e){var t="object"==typeof e[0]&&(e[0].pub||e[0].epub)?e[0]:"object"==typeof e[1]&&(e[1].pub||e[1].epub)?e[1]:null,n=t||"string"!=typeof e[0]?null:e[0],s=!n&&(!t||t.priv&&t.epriv)||"string"!=typeof e[1]?null:e[1],c=e.filter((e=>"function"==typeof e))[0]||null,u=e&&e.length>1&&"object"==typeof e[e.length-1]?e[e.length-1]:{},p=this,l=p._,f=p.back(-1);if(l.ing)return(c||o)({err:a.log("User is already being created or authenticated!"),wait:!0}),p;l.ing=!0;var y,d={},h=9;return d.a=function(e){if(!e)return d.b();if(!e.pub){var t=[];return Object.keys(e).forEach((function(n){"_"!=n&&t.push(e[n])})),d.b(t)}if(d.name)return d.f(e);d.c((d.data=e).auth)},d.b=function(e){var t=(d.list=(d.list||[]).concat(e||[])).shift();if(y===t)return d.name?d.err("Your user account is not published for dApps to access, please consider syncing it online, or allowing local access by adding your device as a peer."):n&&h--?void f.get("~@"+n).once(d.a):d.err("Wrong user or password.");f.get(t).once(d.a)},d.c=function(e){return y===e?d.b():"string"==typeof e?d.c(i(e)):void r.work(s,(d.auth=e).s,d.d,d.enc)},d.d=function(e){r.decrypt(d.auth.ek,e,d.e,d.enc)},d.e=function(e){if(y===e)return d.enc?(d.enc=null,d.b()):(d.enc={encode:"utf8"},d.c(d.auth));d.half=e,d.f(d.data)},d.f=function(e){var t=d.half||{},n=d.data||{};d.g(d.lol={pub:e.pub||n.pub,epub:e.epub||n.epub,priv:e.priv||t.priv,epriv:e.epriv||t.epriv})},d.g=function(e){if(!e||!e.pub||!e.epub)return d.b();d.pair=e;var t=f._.user,h=t._;h.tag;var g=h.opt;(h=t._=f.get("~"+e.pub)._).opt=g,t.is={pub:e.pub,epub:e.epub,alias:n||e.pub},h.sea=d.pair,l.ing=!1;try{s&&y==(i(l.root.graph["~"+e.pub].auth)||"")[":"]&&(u.shuffle=u.change=s)}catch(e){}if(u.change?d.z():(c||o)(h),r.window&&(p.back("user")._.opt||u).remember)try{var w={};(w=r.window.sessionStorage).recall=!0,w.pair=JSON.stringify(e)}catch(e){}try{f._.tag.auth?f._.on("auth",h):setTimeout((function(){f._.on("auth",h)}),1)}catch(e){a.log("Your 'auth' callback crashed with:",e)}},d.h=function(e){return e?((n=e.alias)||(n=e.alias="~"+t.pub),e.auth?(t=null,void d.c((d.data=e).auth)):d.g(t)):d.b()},d.z=function(){d.salt=String.random(64),r.work(u.change,d.salt,d.y)},d.y=function(e){r.encrypt({priv:d.pair.priv,epriv:d.pair.epriv},e,d.x,{raw:1})},d.x=function(e){d.w(JSON.stringify({ek:e,s:d.salt}))},d.w=function(e){if(u.shuffle){console.log("migrate core account from UTF8 & shuffle");var t={};Object.keys(d.data).forEach((function(e){t[e]=d.data[e]})),delete t._,t.auth=e,f.get("~"+d.pair.pub).put(t)}f.get("~"+d.pair.pub).get("auth").put(e,c||o)},d.err=function(e){var t={err:a.log(e||"User cannot be found!")};l.ing=!1,(c||o)(t)},d.plugin=function(e){if(!(d.name=e))return d.err();var t=[e];"~"!==e[0]&&(t[1]="~"+e,t[2]="~@"+e),d.b(t)},t?t.priv&&t.epriv?d.g(t):f.get("~"+t.pub).once(d.h):n?f.get("~@"+n).once(d.a):n||s||r.name(d.plugin),p}}))(t,"./auth"),t((function(e){var n=t("./user"),r=n.SEA;n.GUN,n.prototype.recall=function(e,t){var n=this,a=n.back(-1);if((e=e||{})&&e.sessionStorage){if(r.window)try{var o;(o=r.window.sessionStorage)&&(a._.opt.remember=!0,(n.back("user")._.opt||e).remember=!0,(o.recall||o.pair)&&a.user().auth(JSON.parse(o.pair),t))}catch(e){}return n}return n}}))(t,"./recall"),t((function(e){var n=t("./user"),r=n.SEA,a=n.GUN,o=function(){};n.prototype.pair=function(){var e,t=this;try{e=new Proxy({DANGER:"☠"},{get:function(e,n,r){if(t.is&&(t._||"").sea)return t._.sea[n]}})}catch(e){}return e},n.prototype.delete=async function(e,t,n){console.log("user.delete() IS DEPRECATED AND WILL BE MOVED TO A MODULE!!!");var r=this;r.back(-1);var i=r.back("user");try{i.auth(e,t,(function(e){(i.is||{}).pub;i.map().once((function(){this.put(null)})),i.leave(),(n||o)({ok:0})}))}catch(e){a.log("User.delete failed! Error:",e)}return r},n.prototype.alive=async function(){console.log("user.alive() IS DEPRECATED!!!");const e=this.back(-1);try{return await authRecall(e),e._.user._}catch(e){const t="No session!";throw a.log(t),{err:t}}},n.prototype.trust=async function(e){console.log("`.trust` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!"),a.is(e)&&e.get("pub").get(((e,t)=>{console.log(e,t)})),e.get("trust").get(path).put(theirPubkey)},n.prototype.grant=function(e,t){console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");var n=this,a=n.back(-1).user(),o=a._.sea,i="";return n.back((function(e){e.is||(i+=e.get||"")})),async function(){var n,s=await a.get("grant").get(o.pub).get(i).then();(s=await r.decrypt(s,o))||(s=r.random(16).toString(),n=await r.encrypt(s,o),a.get("grant").get(o.pub).get(i).put(n));var c=e.get("pub").then(),u=e.get("epub").then();c=await c,u=await u;var p=await r.secret(u,o);n=await r.encrypt(s,p),a.get("grant").get(c).get(i).put(n,t)}(),n},n.prototype.secret=function(e,t){console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");var n=this,a=n.back(-1).user(),o=a.pair(),i="";return n.back((function(e){e.is||(i+=e.get||"")})),async function(){var s,c=await a.get("trust").get(o.pub).get(i).then();(c=await r.decrypt(c,o))||(c=r.random(16).toString(),s=await r.encrypt(c,o),a.get("trust").get(o.pub).get(i).put(s)),s=await r.encrypt(e,c),n.put(s,t)}(),n},e.exports=n}))(t,"./share"),t((function(e){var r,a=t("./sea"),o=t("./settings"),i=(a.window||"").GUN||t((""+r==typeof n?".":"")+"./gun",1);function s(e){var t,n=this,r=n.as,o=e.put,c=o["#"],u=o["."],p=o[":"],l=o[">"],f=e["#"];if(c&&u)if((e._||"").faith&&(r.opt||"").faith&&"function"==typeof e._)a.opt.pack(o,(function(t){a.verify(t,!1,(function(t){o["="]=a.opt.unpack(t),n.to.next(e)}))}));else{var y=function(t){r.on("in",{"@":f,err:e.err=t})};(e._||"").DBG&&((e._||"").DBG.c=+new Date),0<=c.indexOf("<?")&&(t=parseFloat(c.split("<?")[1]||""))&&l<i.state()-1e3*t?(t=e._)&&t.stun&&t.stun--:"~@"!==c?"~@"!==c.slice(0,2)?(t=a.opt.pub(c))?s.pub(n,e,p,u,c,r,y,r.user||"",t):0<=c.indexOf("#")?s.hash(n,e,p,u,c,r,y):s.any(n,e,p,u,c,r,y,r.user||""):s.pubs(n,e,p,u,c,r,y):s.alias(n,e,p,u,c,r,y)}}i.on("opt",(function(e){e.sea||(e.sea={own:{}},e.on("put",s,e)),this.to.next(e)})),s.hash=function(e,t,n,r,o,i,s){a.work(n,null,(function(n){return n&&n===r.split("#").slice(-1)[0]||n&&n===function(e){let t="";for(let n=0;n<e.length;n++)t+=n-1&1?"":String.fromCharCode(parseInt(e.substring(n-1,n+1),16));return btoa(t)}(r.split("#").slice(-1)[0])?e.to.next(t):void s("Data hash not same as hash!")}),{name:"SHA-256"})},s.alias=function(e,t,n,r,a,o,i){return n?"~@"+r===u(n)?e.to.next(t):void i("Alias not same!"):i("Data must exist!")},s.pubs=function(e,t,n,r,a,o,i){return n?r===u(n)?e.to.next(t):void i("Alias not same!"):i("Alias must exist!")},s.pub=async function(e,t,n,s,c,p,l,f,y){var d;const h=await o.parse(n)||{},g=(n,o,u)=>{if(n.m&&n.s&&o&&y)return a.verify(n,y,(n=>{if(r!==n&&r!==n.e&&t.put[">"]&&t.put[">"]>parseFloat(n.e))return l("Certificate expired.");if(r!==n&&n.c&&n.w&&(n.c===o||n.c.indexOf("*")>-1)){let t=c.indexOf("/")>-1?c.replace(c.substring(0,c.indexOf("/")+1),""):"";String.match=String.match||i.text.match;const r=Array.isArray(n.w)?n.w:"object"==typeof n.w||"string"==typeof n.w?[n.w]:[];for(const i of r)if(String.match(t,i["#"])&&String.match(s,i["."])||!i["."]&&String.match(t,i["#"])||!i["#"]&&String.match(s,i["."])||String.match(t?t+"/"+s:s,i["#"]||i)){if(i["+"]&&i["+"].indexOf("*")>-1&&t&&-1==t.indexOf(o)&&-1==s.indexOf(o))return l(`Path "${t}" or key "${s}" must contain string "${o}".`);if(n.wb&&("string"==typeof n.wb||(n.wb||{})["#"])){var a=e.as.root.$.back(-1);return"string"==typeof n.wb&&"~"!==n.wb.slice(0,1)&&(a=a.get("~"+y)),a.get(n.wb).get(o).once((e=>!e||1!==e&&!0!==e?u(n):l(`Certificant ${o} blocked.`)))}return u(n)}return l("Certificate verification fail.")}}))};if("pub"===s&&"~"+y===c)return n===y?e.to.next(t):l("Account not same!");(d=f.is)&&d.pub&&!h["*"]&&!h["+"]&&(y===d.pub||y!==d.pub&&((t._.msg||{}).opt||{}).cert)?a.opt.pack(t.put,(i=>{a.sign(i,f._.sea,(async function(i){if(r===i)return l(a.err||"Signature fail.");if(t.put[":"]={":":d=a.opt.unpack(i.m),"~":i.s},t.put["="]=d,y===f.is.pub)return(d=u(n))&&((p.sea.own[d]=p.sea.own[d]||{})[y]=1),void JSON.stringifyAsync(t.put[":"],(function(n,r){return n?l(n||"Stringify error."):(t.put[":"]=r,e.to.next(t))}));if(y!==f.is.pub&&((t._.msg||{}).opt||{}).cert){const n=await o.parse(t._.msg.opt.cert);n&&n.m&&n.s&&g(n,f.is.pub,(r=>{t.put[":"]["+"]=n,t.put[":"]["*"]=f.is.pub,JSON.stringifyAsync(t.put[":"],(function(n,r){return n?l(n||"Stringify error."):(t.put[":"]=r,e.to.next(t))}))}))}}),{raw:1})})):a.opt.pack(t.put,(n=>{a.verify(n,h["*"]||y,(function(n){var o;return n=a.opt.unpack(n),r===n?l("Unverified data."):((o=u(n))&&y===a.opt.pub(o)&&((p.sea.own[o]=p.sea.own[o]||{})[y]=1),h["+"]&&h["+"].m&&h["+"].s&&h["*"]?void g(h["+"],h["*"],(r=>(t.put["="]=n,e.to.next(t)))):(t.put["="]=n,e.to.next(t)))}))}))},s.any=function(e,t,n,r,a,o,i,s){if(o.opt.secure)return i("Soul missing public key at '"+r+"'.");o.on("secure",(function(t){if(this.off(),!o.opt.secure)return e.to.next(t);i("Data cannot be changed.")})).on.on("secure",t)};var c=i.valid,u=function(e,t){return"string"==typeof(t=c(e))&&t};(i.state||"").ify;var p=/[^\w_-]/;a.opt.pub=function(e){if(e&&(e=e.split("~"))&&(e=e[1])&&(e=e.split(p).slice(0,2))&&2==e.length&&"@"!==(e[0]||"")[0])return e=e.slice(0,2).join(".")},a.opt.stringy=function(e){},a.opt.pack=function(e,t,n,o,s){var c,u;if(a.opt.check(e))return t(e);e&&e["#"]&&e["."]&&e[">"]&&(c=e[":"],u=1),JSON.parseAsync(u?c:e,(function(a,c){var u=r!==(c||"")[":"]&&(c||"")["~"];t(u?{m:{"#":s||e["#"],".":n||e["."],":":(c||"")[":"],">":e[">"]||i.state.is(o,n)},s:u}:e)}))};var l=a.opt;a.opt.unpack=function(e,t,n){var o;if(r!==e){if(e&&r!==(o=e[":"]))return o;if(t=t||l.fall_key,!n&&l.fall_val&&((n={})[t]=l.fall_val),t&&n){if(e===n[t])return e;if(!a.opt.check(n[t]))return e;var s=n&&n._&&n._["#"]||l.fall_soul,c=i.state.is(n,t)||l.fall_state;return e&&4===e.length&&s===e[0]&&t===e[1]&&f(c)===f(e[3])?e[2]:c<a.opt.shuffle_attack?e:void 0}}},a.opt.shuffle_attack=15463296e5;var f=Math.floor}))(t,"./index")}()}(i);var s=o(i.exports);let c={PROOF_OF_INTEGRITY_ADDRESS:"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",STEALTH_ANNOUNCER_ADDRESS:"0x5FbDB2315678afecb367f032d93F642f64180aa3"};if("undefined"==typeof window)try{const{fileURLToPath:e}=require("url"),{dirname:t,join:n}=require("path"),{readFileSync:a}=require("fs"),o=e("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(o).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("gun-eth.min.js",document.baseURI).href),i=a(n(t(o),"contract-address.json"));c=JSON.parse(i),console.log("Loaded contract addresses:",c)}catch(e){console.warn("Warning: contract-address.json not found or invalid")}const u={CHAIN_ID:1337,PROOF_OF_INTEGRITY_ADDRESS:c.PROOF_OF_INTEGRITY_ADDRESS,STEALTH_ANNOUNCER_ADDRESS:c.STEALTH_ANNOUNCER_ADDRESS,RPC_URL:"http://127.0.0.1:8545",GUN_PEER:"http://localhost:8765/gun"},p=[{inputs:[{internalType:"address",name:"_devAddress",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],name:"StealthPaymentAnnounced",type:"event"},{anonymous:!1,inputs:[{internalType:"address",name:"newAddress",type:"address"}],name:"DevAddressUpdated",type:"event"},{anonymous:!1,inputs:[{internalType:"uint256",name:"newFee",type:"uint256"}],name:"DevFeeUpdated",type:"event"},{inputs:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"}],name:"announcePayment",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"devAddress",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"devFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getAnnouncementsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"fromIndex",type:"uint256"},{internalType:"uint256",name:"toIndex",type:"uint256"}],name:"getAnnouncementsInRange",outputs:[{components:[{internalType:"string",name:"senderPublicKey",type:"string"},{internalType:"string",name:"spendingPublicKey",type:"string"},{internalType:"address",name:"stealthAddress",type:"address"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct StealthAnnouncer.StealthAnnouncement[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_newFee",type:"uint256"}],name:"updateDevFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newAddress",type:"address"}],name:"updateDevAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawStuckETH",outputs:[],stateMutability:"nonpayable",type:"function"}],l=[{inputs:[{internalType:"bytes[]",name:"nodeIds",type:"bytes[]"},{internalType:"bytes32[]",name:"contentHashes",type:"bytes32[]"}],name:"batchUpdateData",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes",name:"nodeId",type:"bytes"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"},{indexed:!1,internalType:"address",name:"updater",type:"address"}],name:"DataUpdated",type:"event"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"}],name:"getLatestRecord",outputs:[{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"updateData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"nodeId",type:"bytes"},{internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"verifyData",outputs:[{internalType:"bool",name:"",type:"bool"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];let f,y="",d="";const h="Access GunDB with Ethereum";let g={PROOF_OF_INTEGRITY_ADDRESS:null,STEALTH_ANNOUNCER_ADDRESS:"..."};if("undefined"==typeof window){const{fileURLToPath:e}=require("url"),{dirname:t}=require("path"),{readFileSync:n}=require("fs"),a=require("path"),o=e("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(o).href:"undefined"==typeof document?location.href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("gun-eth.min.js",document.baseURI).href),i=t(o);try{const e=n(a.join(i,"contract-address.json"),"utf8");g=JSON.parse(e),console.log("Loaded contract addresses:",g)}catch(e){console.warn("Warning: contract-address.json not found or invalid")}}function w(){return n.ethers.hexlify(n.ethers.randomBytes(32)).slice(2)}function b(e){try{const t=n.ethers.hexlify(e),r=n.ethers.keccak256(t);return console.log("Generated password:",r),r}catch(e){return console.error("Error generating password:",e),null}}function m(e){const t="0x"+(e=>{const t="=".repeat((4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,r=atob(n);return Array.from(r,(e=>e.charCodeAt(0).toString(16).padStart(2,"0"))).join("")})(e),r=new n.ethers.Wallet(t);return{account:r,publicKey:r.address,privateKey:t}}const v=async()=>{if(y&&d){const e=new n.ethers.JsonRpcProvider(y,{chainId:u.CHAIN_ID,name:"localhost"});return new n.ethers.Wallet(d,e)}if("undefined"!=typeof window&&void 0!==window.ethereum){await window.ethereum.request({method:"eth_requestAccounts"});return new n.ethers.BrowserProvider(window.ethereum).getSigner()}throw new Error("No valid Ethereum provider found")};function S(e,t){try{const r=Buffer.from(e,"base64"),a=n.ethers.keccak256(n.ethers.concat([r,n.ethers.getBytes(t)])),o=new n.ethers.Wallet(a);return console.log("Debug deriveStealthAddress:",{sharedSecretHex:n.ethers.hexlify(r),spendingPublicKey:t,stealthPrivateKey:a,stealthAddress:o.address}),{stealthPrivateKey:a,stealthAddress:o.address,wallet:o}}catch(e){throw console.error("Error in deriveStealthAddress:",e),e}}t.chain.MESSAGE_TO_SIGN=h,t.chain.setSigner=function(e,t){return y=e,d=t,console.log("Standalone configuration set"),this},t.chain.getSigner=v(),t.chain.verifySignature=async function(e,t){try{return n.ethers.verifyMessage(e,t)}catch(e){return console.error("Error verifying signature:",e),null}},t.chain.generatePassword=function(e){return b(e)},t.chain.createSignature=async function(e){try{if(e!==h)throw new Error("Invalid message, valid message is: "+h);const t=await v(),n=await t.signMessage(e);return console.log("Signature created:",n),n}catch(e){return console.error("Error creating signature:",e),null}},t.chain.createAndStoreEncryptedPair=async function(e,t){try{const n=this,r=await s.pair(),a=await s.pair(),o=await s.pair(),i=b(t),c=await s.encrypt(JSON.stringify(r),i),u=await s.encrypt(JSON.stringify(a),i),p=await s.encrypt(JSON.stringify(o),i),l=m(a.priv),f=m(o.priv);n.get("gun-eth").get("users").get(e).put({pair:c,v_pair:u,s_pair:p,publicKeys:{viewingPublicKey:a.epub,viewingPublicKey:a.epub,spendingPublicKey:f.publicKey,ethViewingAddress:l.publicKey}}),console.log("Encrypted pairs and public keys stored for:",e)}catch(e){throw console.error("Error creating and storing encrypted pair:",e),e}},t.chain.getAndDecryptPair=async function(e,t){try{const n=this,r=await n.get("gun-eth").get("users").get(e).get("pair").then();if(!r)throw new Error("No encrypted data found for this address");const a=b(t),o=await s.decrypt(r,a);return console.log(o),o}catch(e){return console.error("Error retrieving and decrypting pair:",e),null}},t.chain.proof=function(e,t,r,a){if(console.log("Proof plugin called with:",{chain:e,nodeId:t,data:r}),"function"!=typeof a)return console.error("Callback must be a function"),this;try{const o=isLocalEnvironment()?"localhost":e,i=getAddressesForChain(o);console.log(`Using ${o} configuration:`,i);new n.ethers.Contract(i.PROOF_OF_INTEGRITY_ADDRESS,l,signer);const s=async(e,t)=>{console.log("Verifying on chain:",{nodeId:e,contentHash:t});const r=await v(),a=new n.ethers.Contract(f,l,r),[o,i,s]=await a.verifyData(n.ethers.toUtf8Bytes(e),t);return console.log("Verification result:",{isValid:o,timestamp:i,updater:s}),{isValid:o,timestamp:i,updater:s}},c=async(e,t)=>{console.log("Writing on chain:",{nodeId:e,contentHash:t});const r=await v(),a=new n.ethers.Contract(f,l,r),o=await a.updateData(n.ethers.toUtf8Bytes(e),t);console.log("Transaction sent:",o.hash);const i=await o.wait();return console.log("Transaction confirmed:",i),o},u=async e=>{const t=await v(),r=new n.ethers.Contract(f,l,t),[a,o,i]=await r.getLatestRecord(n.ethers.toUtf8Bytes(e));return console.log("Latest record from blockchain:",{nodeId:e,contentHash:a,timestamp:o,updater:i}),{contentHash:a,timestamp:o,updater:i}};if(t&&!r)gun.get(t).once((async e=>{if(!e)return void(a&&a({err:"Node not found in GunDB"}));console.log("existingData",e);const n=e._contentHash;if(console.log("contentHash",n),n)try{const{isValid:e,timestamp:r,updater:o}=await s(t,n),i=await u(t);e?a&&a({ok:!0,message:"Data verified on blockchain",timestamp:r,updater:o,latestRecord:i}):a&&a({ok:!1,message:"Data not verified on blockchain",latestRecord:i})}catch(e){a&&a({err:e.message})}else a&&a({err:"No content hash found for this node"})}));else if(r&&!t){const e=w(),t=JSON.stringify(r),o=n.ethers.keccak256(n.ethers.toUtf8Bytes(t));gun.get(e).put({...r,_contentHash:o},(async t=>{if(console.log("ack",t),t.err)a&&a({err:"Error saving data to GunDB"});else try{const t=await c(e,o);a&&a({ok:!0,message:"Data written to GunDB and blockchain",nodeId:e,txHash:t.hash})}catch(e){a&&a({err:e.message})}}))}else a&&a({err:"Invalid input. Provide either nodeId or data, not both."});return gun}catch(e){return a({err:e.message}),this}},t.chain.gunToEthAccount=function(e){return m(e)},t.chain.generateStealthAddress=async function(e,t){try{const n=this,r=await n.get("gun-eth").get("users").get(e).get("publicKeys").then();if(!r||!r.viewingPublicKey||!r.spendingPublicKey)throw new Error("Recipient's public keys not found");const a=await this.verifySignature(h,t),o=b(t),i=await n.get("gun-eth").get("users").get(a).then();if(!i||!i.s_pair)throw new Error("Sender's keys not found");let c;try{const e=await s.decrypt(i.s_pair,o);c="string"==typeof e?JSON.parse(e):e}catch(e){throw console.error("Error decrypting spending pair:",e),new Error("Unable to decrypt spending pair")}const u=await s.secret(r.viewingPublicKey,c);if(!u)throw new Error("Unable to generate shared secret");console.log("Generate shared secret:",u);const{stealthAddress:p}=S(u,r.spendingPublicKey);return{stealthAddress:p,senderPublicKey:c.epub,spendingPublicKey:r.spendingPublicKey}}catch(e){throw console.error("Error generating stealth address:",e),e}},t.chain.publishStealthKeys=async function(e){try{const t=this,n=await this.verifySignature(h,e),r=b(e),a=await t.get("gun-eth").get("users").get(n).then();if(!a||!a.v_pair||!a.s_pair)throw new Error("Keys not found");const o=JSON.parse(await s.decrypt(a.v_pair,r)),i=JSON.parse(await s.decrypt(a.s_pair,r)),c=m(o.priv),u=m(i.priv);t.get("gun-eth").get("users").get(n).get("publicKeys").put({viewingPublicKey:c.publicKey,spendingPublicKey:u.publicKey}),console.log("Stealth public keys published successfully")}catch(e){throw console.error("Error publishing stealth keys:",e),e}},t.chain.recoverStealthFunds=async function(e,t,n,r){try{const a=this,o=b(n),i=await this.verifySignature(h,n),c=await a.get("gun-eth").get("users").get(i).then();if(!c||!c.v_pair||!c.s_pair)throw new Error("Keys not found");let u;try{const e=await s.decrypt(c.v_pair,o);u="string"==typeof e?JSON.parse(e):e}catch(e){throw console.error("Error decrypting keys:",e),new Error("Unable to decrypt keys")}const p=await s.secret(t,u);if(!p)throw new Error("Unable to generate shared secret");console.log("Recover shared secret:",p);const{wallet:l,stealthAddress:f}=S(p,r);if(f.toLowerCase()!==e.toLowerCase())throw console.error("Mismatch:",{recovered:f,expected:e,sharedSecret:p}),new Error("Recovered stealth address does not match");return{wallet:l,address:f}}catch(e){throw console.error("Error recovering stealth funds:",e),e}},t.chain.announceStealthPayment=async function(e,t,r,a,o={onChain:!1,chain:"optimismSepolia"}){try{const i=this,s=await this.verifySignature(h,a);if(o.onChain){const a=await v(),i=getAddressesForChain(o.chain).STEALTH_ANNOUNCER_ADDRESS;console.log("Using contract address:",i);const s=new n.ethers.Contract(i,p,a),c=await s.devFee();console.log("Dev fee:",c.toString());const u=await s.announcePayment(t,r,e,{value:c});console.log("Transaction sent:",u.hash);const l=await u.wait();console.log("Transaction confirmed:",l.hash),console.log("Stealth payment announced on-chain (dev fee paid)")}else i.get("gun-eth").get("stealth-payments").set({stealthAddress:e,senderAddress:s,senderPublicKey:t,spendingPublicKey:r,timestamp:Date.now()}),console.log("Stealth payment announced off-chain")}catch(e){throw console.error("Error announcing stealth payment:",e),console.error("Error details:",e.stack),e}},t.chain.getStealthPayments=async function(e,t={source:"both"}){try{const r=[];if("onChain"===t.source||"both"===t.source){const t=await v(),a="development"===process.env.NODE_ENV?u.STEALTH_ANNOUNCER_ADDRESS:"...",o=new n.ethers.Contract(a,p,t);try{const t=await o.getAnnouncementsCount(),n=Number(t.toString());if(console.log("Total on-chain announcements:",n),n>0){const t=100,a=n-1;for(let n=0;n<=a;n+=t){const i=Math.min(n+t-1,a),s=await o.getAnnouncementsInRange(n,i);for(const t of s)try{if(!(t&&t.stealthAddress&&t.senderPublicKey&&t.spendingPublicKey)){console.log("Invalid announcement:",t);continue}const n=await this.recoverStealthFunds(t.stealthAddress,t.senderPublicKey,e,t.spendingPublicKey);r.push({stealthAddress:t.stealthAddress,senderPublicKey:t.senderPublicKey,spendingPublicKey:t.spendingPublicKey,timestamp:Number(t.timestamp),source:"onChain",wallet:n})}catch(e){console.log(`Announcement not for us: ${t.stealthAddress}`);continue}}}}catch(e){console.error("Error retrieving on-chain announcements:",e)}}if("offChain"===t.source||"both"===t.source){const e=this,t=await new Promise((t=>{const n=[];e.get("gun-eth").get("stealth-payments").get(recipientAddress).map().once(((e,t)=>{e?.stealthAddress&&n.push({...e,id:t,source:"offChain"})})),setTimeout((()=>t(n)),2e3)}));r.push(...t)}return console.log(`Found ${r.length} stealth payments`),r}catch(e){throw console.error("Error retrieving stealth payments:",e),e}},t.chain.cleanStealthPayments=async function(e){try{const t=this,n=await t.get("gun-eth").get("stealth-payments").get(e).map().once().then();n&&Object.keys(n).forEach((async r=>{const a=n[r];a&&a.stealthAddress&&a.senderPublicKey&&a.spendingPublicKey||await t.get("gun-eth").get("stealth-payments").get(e).get(r).put(null)}))}catch(e){console.error("Error cleaning stealth payments:",e)}};class A{static generateRandomId=w;static generatePassword=b;static gunToEthAccount=m;static getSigner=v;static deriveStealthAddress=S;static chainMethods={setSigner:t.chain.setSigner,getSigner:t.chain.getSigner,verifySignature:t.chain.verifySignature,generatePassword:t.chain.generatePassword,createSignature:t.chain.createSignature,createAndStoreEncryptedPair:t.chain.createAndStoreEncryptedPair,getAndDecryptPair:t.chain.getAndDecryptPair,proof:t.chain.proof,gunToEthAccount:t.chain.gunToEthAccount,generateStealthAddress:t.chain.generateStealthAddress,publishStealthKeys:t.chain.publishStealthKeys,recoverStealthFunds:t.chain.recoverStealthFunds,announceStealthPayment:t.chain.announceStealthPayment,getStealthPayments:t.chain.getStealthPayments,cleanStealthPayments:t.chain.cleanStealthPayments};static MESSAGE_TO_SIGN=h;static PROOF_CONTRACT_ADDRESS=f;static LOCAL_CONFIG=u}e.default=t,e.GunEth=A,e.MESSAGE_TO_SIGN=h,e.deriveStealthAddress=S,e.generatePassword=b,e.generateRandomId=w,e.getSigner=v,e.gunToEthAccount=m,Object.defineProperty(e,"__esModule",{value:!0})}));
|
2
2
|
//# sourceMappingURL=gun-eth.min.js.map
|