@fort-major/msq
Version:
Privacy-focused MetaMask snap for the Internet Computer (ICP)
1 lines • 1.23 MB
JavaScript
(()=>{var e={8050:(e,t,r)=>{"use strict";r.r(t),r.d(t,{CustomPath:()=>u,encodePath:()=>d,fetchNodeKeys:()=>f,request:()=>l});var n=r(1281),i=r(5349),a=r(2483),o=r(3238),s=r(2338),c=r(9837);class u{constructor(e,t,r){this.key=e,this.path=t,this.decodeStrategy=r}}const l=async e=>{const{agent:t,paths:r}=e,o=n.p.from(e.canisterId),s=[...new Set(r)],u=s.map((e=>d(e,o))),l=new Map,m=s.map(((e,r)=>(async()=>{var n;try{const e=await t.readState(o,{paths:[u[r]]}),n=await a.us.create({certificate:e.certificate,rootKey:t.rootKey,canisterId:o}),i=(r,n)=>{if("subnet"===n){return{path:n,data:f(e.certificate,o,t.rootKey)}}return{path:n,data:(0,a.Xr)(r.lookup(d(n,o)))}},{path:m,data:y}=i(n,s[r]);if(y)switch(m){case"time":l.set(m,(0,c.A)(y));break;case"controllers":l.set(m,g(y));break;case"module_hash":l.set(m,h(y));break;case"subnet":l.set(m,y);break;case"candid":l.set(m,(new TextDecoder).decode(y));break;default:if("string"!=typeof m&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":l.set(m.key,y);break;case"leb128":l.set(m.key,(0,c.b)(y));break;case"cbor":l.set(m.key,p(y));break;case"hex":l.set(m.key,h(y));break;case"utf-8":l.set(m.key,b(y))}}else console.warn(`Expected to find result for path ${m}, but instead found nothing.`),"string"==typeof m?l.set(m,null):l.set(m.key,null)}catch(t){if(null===(n=null==t?void 0:t.message)||void 0===n?void 0:n.includes("Invalid certificate"))throw new i.Y(t.message);"string"!=typeof e&&"key"in e&&"path"in e?l.set(e.key,null):l.set(e,null),console.group(),console.warn(`Expected to find result for path ${e}, but instead found nothing.`),console.warn(t),console.groupEnd()}})()));return await Promise.all(m),l},f=(e,t,r)=>{if(!t._isPrincipal)throw new Error("Invalid canisterId");const i=s.decode(new Uint8Array(e)),o=i.tree;let c,u=i.delegation;u&&u.subnet_id?c=n.p.fromUint8Array(new Uint8Array(u.subnet_id)):u||void 0===r?(c=n.p.selfAuthenticating(n.p.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),u={subnet_id:c.toUint8Array(),certificate:new ArrayBuffer(0)}):(c=n.p.selfAuthenticating(new Uint8Array(r)),u={subnet_id:c.toUint8Array(),certificate:new ArrayBuffer(0)});if(!(0,a.Gk)({canisterId:t,subnetId:c,tree:o}))throw new Error("Canister not in range");const l=(0,a.hV)(["subnet",null==u?void 0:u.subnet_id,"node"],o),f=(0,a.Bx)(l);f.length;const d=new Map;return f.forEach((e=>{Object.getPrototypeOf(new Uint8Array(e[1]));const t=n.p.from(new Uint8Array(e[1])).toText(),r=(0,a.hV)(["public_key"],e[2]);if(44!==r.byteLength)throw new Error("Invalid public key length");d.set(t,r)})),{subnetId:n.p.fromUint8Array(new Uint8Array(u.subnet_id)).toText(),nodeKeys:d}},d=(e,t)=>{const r=new TextEncoder,n=e=>new DataView(r.encode(e).buffer).buffer,i=new DataView(t.toUint8Array().buffer).buffer;switch(e){case"time":return[n("time")];case"controllers":return[n("canister"),i,n("controllers")];case"module_hash":return[n("canister"),i,n("module_hash")];case"subnet":return[n("subnet")];case"candid":return[n("canister"),i,n("metadata"),n("candid:service")];default:if("key"in e&&"path"in e){if("string"==typeof e.path||e.path instanceof ArrayBuffer){const t=e.path,r="string"==typeof t?n(t):t;return[n("canister"),i,n("metadata"),r]}return e.path}}throw new Error(`An unexpeected error was encountered while encoding your path for canister status. Please ensure that your path, ${e} was formatted correctly.`)},h=e=>(0,o.nj)(e),p=e=>s.decode(e),b=e=>(new TextDecoder).decode(e),g=e=>p(e).map((e=>n.p.fromUint8Array(new Uint8Array(e))))},2338:(e,t,r)=>{"use strict";r.r(t),r.d(t,{CborTag:()=>s,decode:()=>f,encode:()=>c});var n=r(7688),i=r(1752),a=(r.n(i),r(3238));const o=i.SelfDescribeCborSerializer.withDefaultEncoders(!0);var s;function c(e){return o.serialize(e)}function u(e){const t=e.byteLength;let r=BigInt(0);for(let n=0;n<t;n++)r=r*BigInt(256)+BigInt(e[n]);return r}o.addEncoder(new class{get name(){return"Principal"}get priority(){return 0}match(e){return e&&!0===e._isPrincipal}encode(e){return i.value.bytes(e.toUint8Array())}}),o.addEncoder(new class{get name(){return"Buffer"}get priority(){return 1}match(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}encode(e){return i.value.bytes(new Uint8Array(e))}}),o.addEncoder(new class{get name(){return"BigInt"}get priority(){return 1}match(e){return"bigint"==typeof e}encode(e){return e>BigInt(0)?i.value.tagged(2,i.value.bytes((0,a.aD)(e.toString(16)))):i.value.tagged(3,i.value.bytes((0,a.aD)((BigInt("-1")*e).toString(16))))}}),function(e){e[e.Uint64LittleEndian=71]="Uint64LittleEndian",e[e.Semantic=55799]="Semantic"}(s||(s={}));class l extends n.Decoder{createByteString(e){return(0,a.xW)(...e)}createByteStringFromHeap(e,t){return e===t?new ArrayBuffer(0):new Uint8Array(this._heap.slice(e,t))}}function f(e){const t=new Uint8Array(e);return new l({size:t.byteLength,tags:{2:e=>u(e),3:e=>-u(e),[s.Semantic]:e=>e}}).decodeFirst(t)}},2483:(e,t,r)=>{"use strict";r.d(t,{Bx:()=>x,Gk:()=>_,WS:()=>f,Xl:()=>d,Xr:()=>m,bK:()=>l,fp:()=>y,hV:()=>w,us:()=>p});var n=r(2338),i=r(5349),a=r(7745),o=r(3238),s=r(1281),c=r(6385),u=r(9837);class l extends i.Y{constructor(e){super(`Invalid certificate: ${e}`)}}const f={Empty:0,Fork:1,Labeled:2,Leaf:3,Pruned:4};function d(e){const t=e=>e.split("\n").map((e=>" "+e)).join("\n");switch(e[0]){case f.Empty:return"()";case f.Fork:if(e[1]instanceof Array&&e[2]instanceof ArrayBuffer){const r=d(e[1]),n=d(e[2]);return`sub(\n left:\n${t(r)}\n---\n right:\n${t(n)}\n)`}throw new Error("Invalid tree structure for fork");case f.Labeled:if(e[1]instanceof ArrayBuffer&&e[2]instanceof ArrayBuffer){const r=function(e){const t=new TextDecoder(void 0,{fatal:!0});try{return JSON.stringify(t.decode(e))}catch(t){return`data(...${e.byteLength} bytes)`}}(e[1]),n=d(e[2]);return`label(\n label:\n${t(r)}\n sub:\n${t(n)}\n)`}throw new Error("Invalid tree structure for labeled");case f.Leaf:if(!e[1])throw new Error("Invalid tree structure for leaf");return Array.isArray(e[1])?JSON.stringify(e[1]):`leaf(...${e[1].byteLength} bytes)`;case f.Pruned:if(!e[1])throw new Error("Invalid tree structure for pruned");return Array.isArray(e[1])?JSON.stringify(e[1]):`pruned(${(0,o.nj)(new Uint8Array(e[1]))}`;default:return`unknown(${JSON.stringify(e[0])})`}}function h(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),n=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==n[e])return!1;return!0}class p{constructor(e,t,r,i,a=5){this._rootKey=t,this._canisterId=r,this._blsVerify=i,this._maxAgeInMinutes=a,this.cert=n.decode(new Uint8Array(e))}static async create(e){const t=p.createUnverified(e);return await t.verify(),t}static createUnverified(e){let t=e.blsVerify;return t||(t=c.r),new p(e.certificate,e.rootKey,e.canisterId,t,e.maxAgeInMinutes)}lookup(e){return m(w(e,this.cert.tree))}lookup_label(e){return this.lookup([e])}async verify(){const e=await y(this.cert.tree),t=await this._checkDelegationAndGetKey(this.cert.delegation),r=this.cert.signature,n=function(e){const t=b.byteLength+g;if(e.byteLength!==t)throw new TypeError(`BLS DER-encoded public key must be ${t} bytes long`);const r=e.slice(0,b.byteLength);if(!h(r,b))throw new TypeError(`BLS DER-encoded public key is invalid. Expect the following prefix: ${b}, but get ${r}`);return e.slice(b.byteLength)}(t),i=(0,o.xW)(v("ic-state-root"),e);let a=!1;const s=this.lookup(["time"]);if(!s)throw new l("Certificate does not contain a time");const c=60*this._maxAgeInMinutes*1e3,f=Date.now(),d=f-c,p=f+3e5,m=(0,u.A)(s);if(m.getTime()<d)throw new l(`Certificate is signed more than ${this._maxAgeInMinutes} minutes in the past. Certificate time: `+m.toISOString()+" Current time: "+new Date(f).toISOString());if(m.getTime()>p)throw new l("Certificate is signed more than 5 minutes in the future. Certificate time: "+m.toISOString()+" Current time: "+new Date(f).toISOString());try{a=await this._blsVerify(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}catch(e){a=!1}if(!a)throw new l("Signature verification failed")}async _checkDelegationAndGetKey(e){if(!e)return this._rootKey;const t=await p.createUnverified({certificate:e.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,maxAgeInMinutes:1/0});if(t.cert.delegation)throw new l("Delegation certificates cannot be nested");await t.verify();if(!_({canisterId:this._canisterId,subnetId:s.p.fromUint8Array(new Uint8Array(e.subnet_id)),tree:t.cert.tree}))throw new l(`Canister ${this._canisterId} not in range of delegations for subnet 0x${(0,o.nj)(e.subnet_id)}`);const r=t.lookup(["subnet",e.subnet_id,"public_key"]);if(!r)throw new Error(`Could not find subnet key for subnet 0x${(0,o.nj)(e.subnet_id)}`);return r}}const b=(0,o.aD)("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),g=96;function m(e){return e instanceof ArrayBuffer?e:e instanceof Uint8Array?e.buffer:void 0}async function y(e){switch(e[0]){case f.Empty:return(0,a.tW)(v("ic-hashtree-empty"));case f.Pruned:return e[1];case f.Leaf:return(0,a.tW)((0,o.xW)(v("ic-hashtree-leaf"),e[1]));case f.Labeled:return(0,a.tW)((0,o.xW)(v("ic-hashtree-labeled"),e[1],await y(e[2])));case f.Fork:return(0,a.tW)((0,o.xW)(v("ic-hashtree-fork"),await y(e[1]),await y(e[2])));default:throw new Error("unreachable")}}function v(e){const t=new Uint8Array([e.length]),r=(new TextEncoder).encode(e);return(0,o.xW)(t,r)}function w(e,t){if(0===e.length)switch(t[0]){case f.Leaf:if(!t[1])throw new Error("Invalid tree structure for leaf");return t[1]instanceof ArrayBuffer?t[1]:t[1]instanceof Uint8Array?t[1].buffer:t[1];case f.Fork:default:return t}const r=function(e,t){if(0===t.length)return;for(const r of t)if(r[0]===f.Labeled){if(h(e,r[1]))return r[2]}}("string"==typeof e[0]?(new TextEncoder).encode(e[0]):e[0],x(t));if(r)return w(e.slice(1),r)}function x(e){switch(e[0]){case f.Empty:return[];case f.Fork:return x(e[1]).concat(x(e[2]));default:return[e]}}function _(e){const{canisterId:t,subnetId:r,tree:i}=e,a=w(["subnet",r.toUint8Array(),"canister_ranges"],i);if(!(a&&a instanceof ArrayBuffer))throw new Error(`Could not find canister ranges for subnet ${r}`);return n.decode(a).map((e=>[s.p.fromUint8Array(e[0]),s.p.fromUint8Array(e[1])])).some((e=>e[0].ltEq(t)&&e[1].gtEq(t)))}},5349:(e,t,r)=>{"use strict";r.d(t,{Y:()=>n});class n extends Error{constructor(e){super(e),this.message=e,Object.setPrototypeOf(this,n.prototype)}}},6344:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ACTOR_METHOD_WITH_HTTP_DETAILS:()=>Ot,Actor:()=>At,ActorCallError:()=>_t,AgentHTTPResponseError:()=>I,AnonymousIdentity:()=>p,CanisterStatus:()=>B,Cbor:()=>g,Certificate:()=>O.us,CertificateVerificationError:()=>O.bK,DER_COSE_OID:()=>Ae,ED25519_OID:()=>Ie,Ed25519PublicKey:()=>Pe,Expiry:()=>E,HttpAgent:()=>ot,IC_ROOT_KEY:()=>rt,IdentityInvalidError:()=>at,MANAGEMENT_CANISTER_ID:()=>nt,NodeId:()=>O.WS,ProxyAgent:()=>ut,ProxyMessageKind:()=>st,ProxyStubAgent:()=>ct,QueryCallRejectedError:()=>Et,ReplicaRejectCode:()=>a,RequestStatusResponseStatus:()=>Xe,SECP256K1_OID:()=>Be,SignIdentity:()=>h,SubmitRequestType:()=>w,UpdateCallRejectedError:()=>kt,blsVerify:()=>Pt.r,bufEquals:()=>l.HA,bufFromBufLike:()=>l.em,check_canister_ranges:()=>O.Gk,compare:()=>l.UD,concat:()=>l.xW,createAssetCanisterActor:()=>Mt,createIdentityDescriptor:()=>b,decodeLen:()=>Se,decodeLenBytes:()=>ke,encodeLen:()=>Ee,encodeLenBytes:()=>_e,fetchCandid:()=>Rt,flatten_forks:()=>O.Bx,fromHex:()=>l.aD,getDefaultAgent:()=>lt,getManagementCanister:()=>Nt,hash:()=>u.tW,hashOfMap:()=>u.uF,hashTreeToString:()=>O.Xl,hashValue:()=>u.gg,httpHeadersTransform:()=>A,lookupResultToBuffer:()=>O.Xr,lookup_path:()=>O.hV,makeExpiryTransform:()=>S,makeNonce:()=>x,makeNonceTransform:()=>k,polling:()=>i,randomNumber:()=>v,reconstruct:()=>O.fp,requestIdOf:()=>u.Gb,toHex:()=>l.nj,uint8ToBuf:()=>l.Nn,unwrapDER:()=>Te,verify:()=>Pt.M,wrapDER:()=>Oe});var n={};r.r(n),r.d(n,{backoff:()=>yt,chain:()=>vt,conditionalDelay:()=>pt,defaultStrategy:()=>dt,maxAttempts:()=>bt,once:()=>ht,throttle:()=>gt,timeout:()=>mt});var i={};r.r(i),r.d(i,{defaultStrategy:()=>dt,pollForResponse:()=>wt,strategy:()=>n});var a,o=r(6533);!function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"}(a||(a={}));var s=r(1281),c=r(5349),u=r(7745),l=r(3238),f=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r};const d=(new TextEncoder).encode("\nic-request");class h{getPrincipal(){return this._principal||(this._principal=s.p.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(e){const{body:t}=e,r=f(e,["body"]),n=await(0,u.Gb)(t);return Object.assign(Object.assign({},r),{body:{content:t,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign((0,l.xW)(d,n))}})}}class p{getPrincipal(){return s.p.anonymous()}async transformRequest(e){return Object.assign(Object.assign({},e),{body:{content:e.body}})}}function b(e){return"getPublicKey"in e?{type:"PublicKeyIdentity",publicKey:(0,l.nj)(e.getPublicKey().toDer())}:{type:"AnonymousIdentity"}}var g=r(2338),m=r(6881),y=r(1752);const v=()=>{if("undefined"!=typeof window&&window.crypto&&window.crypto.getRandomValues){const e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return"undefined"!=typeof crypto&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(4294967295*Math.random())};var w;function x(){const e=new ArrayBuffer(16),t=new DataView(e),r=v(),n=v(),i=v(),a=v();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,i),t.setUint32(12,a),e}!function(e){e.Call="call"}(w||(w={}));const _=BigInt(1e6);class E{constructor(e){const t=BigInt(Math.floor(Date.now()+e-6e4))*_/BigInt(1e9)/BigInt(60)*BigInt(60)*BigInt(1e9);this._value=t}toCBOR(){return y.value.u64(this._value.toString(16),16)}toHash(){return(0,m.kk)(this._value)}}function k(e=x){return async t=>{const r=t.request.headers;t.request.headers=r,"call"===t.endpoint&&(t.body.nonce=e())}}function S(e){return async t=>{t.body.ingress_expiry=new E(e)}}function A(e){const t=[];return e.forEach(((e,r)=>{t.push([r,e])})),t}class I extends c.Y{constructor(e,t){super(e),this.response=t,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}}var B=r(8050),O=r(2483),T=r(788);const N=BigInt(2**32-1),j=BigInt(32);function M(e,t=!1){return t?{h:Number(e&N),l:Number(e>>j&N)}:{h:0|Number(e>>j&N),l:0|Number(e&N)}}const R={fromBig:M,split:function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:a,l:o}=M(e[i],t);[r[i],n[i]]=[a,o]}return[r,n]},toBig:(e,t)=>BigInt(e>>>0)<<j|BigInt(t>>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,r)=>e<<r|t>>>32-r,rotlSL:(e,t,r)=>t<<r|e>>>32-r,rotlBH:(e,t,r)=>t<<r-32|e>>>64-r,rotlBL:(e,t,r)=>e<<r-32|t>>>64-r,add:function(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,add5H:(e,t,r,n,i,a)=>t+r+n+i+a+(e/2**32|0)|0,add5L:(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0)},P=R;var C=r(4328);const[U,L]=P.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))),z=new Uint32Array(80),D=new Uint32Array(80);class q extends T.ol{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:u,Fh:l,Fl:f,Gh:d,Gl:h,Hh:p,Hl:b}=this;return[e,t,r,n,i,a,o,s,c,u,l,f,d,h,p,b]}set(e,t,r,n,i,a,o,s,c,u,l,f,d,h,p,b){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|a,this.Dh=0|o,this.Dl=0|s,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|f,this.Gh=0|d,this.Gl=0|h,this.Hh=0|p,this.Hl=0|b}process(e,t){for(let r=0;r<16;r++,t+=4)z[r]=e.getUint32(t),D[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|z[e-15],r=0|D[e-15],n=P.rotrSH(t,r,1)^P.rotrSH(t,r,8)^P.shrSH(t,r,7),i=P.rotrSL(t,r,1)^P.rotrSL(t,r,8)^P.shrSL(t,r,7),a=0|z[e-2],o=0|D[e-2],s=P.rotrSH(a,o,19)^P.rotrBH(a,o,61)^P.shrSH(a,o,6),c=P.rotrSL(a,o,19)^P.rotrBL(a,o,61)^P.shrSL(a,o,6),u=P.add4L(i,c,D[e-7],D[e-16]),l=P.add4H(u,n,s,z[e-7],z[e-16]);z[e]=0|l,D[e]=0|u}let{Ah:r,Al:n,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:u,Eh:l,El:f,Fh:d,Fl:h,Gh:p,Gl:b,Hh:g,Hl:m}=this;for(let e=0;e<80;e++){const t=P.rotrSH(l,f,14)^P.rotrSH(l,f,18)^P.rotrBH(l,f,41),y=P.rotrSL(l,f,14)^P.rotrSL(l,f,18)^P.rotrBL(l,f,41),v=l&d^~l&p,w=f&h^~f&b,x=P.add5L(m,y,w,L[e],D[e]),_=P.add5H(x,g,t,v,U[e],z[e]),E=0|x,k=P.rotrSH(r,n,28)^P.rotrBH(r,n,34)^P.rotrBH(r,n,39),S=P.rotrSL(r,n,28)^P.rotrBL(r,n,34)^P.rotrBL(r,n,39),A=r&i^r&o^i&o,I=n&a^n&s^a&s;g=0|p,m=0|b,p=0|d,b=0|h,d=0|l,h=0|f,({h:l,l:f}=P.add(0|c,0|u,0|_,0|E)),c=0|o,u=0|s,o=0|i,s=0|a,i=0|r,a=0|n;const B=P.add3L(E,S,I);r=P.add3H(B,_,k,A),n=0|B}({h:r,l:n}=P.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:a}=P.add(0|this.Bh,0|this.Bl,0|i,0|a)),({h:o,l:s}=P.add(0|this.Ch,0|this.Cl,0|o,0|s)),({h:c,l:u}=P.add(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:f}=P.add(0|this.Eh,0|this.El,0|l,0|f)),({h:d,l:h}=P.add(0|this.Fh,0|this.Fl,0|d,0|h)),({h:p,l:b}=P.add(0|this.Gh,0|this.Gl,0|p,0|b)),({h:g,l:m}=P.add(0|this.Hh,0|this.Hl,0|g,0|m)),this.set(r,n,i,a,o,s,c,u,l,f,d,h,p,b,g,m)}roundClean(){z.fill(0),D.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const F=(0,C.ld)((()=>new q));var V=r(8769),H=r(7514),$=r(8732);const G=BigInt(0),Z=BigInt(1),W=BigInt(2),K=BigInt(8),J={zip215:!0};function Y(e){const t=function(e){const t=(0,$.h)(e);return H.Q5(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:i,hash:a,randomBytes:o,nByteLength:s,h:c}=t,u=W<<BigInt(8*s)-Z,l=r.create,f=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:G}}}),d=t.adjustScalarBytes||(e=>e),h=t.domain||((e,t,r)=>{if(t.length||r)throw new Error("Contexts/pre-hash are not supported");return e}),p=e=>"bigint"==typeof e&&G<e,b=(e,t)=>p(e)&&p(t)&&e<t,g=e=>e===G||b(e,u);function m(e,t){if(b(e,t))return e;throw new Error(`Expected valid scalar < ${t}, got ${typeof e} ${e}`)}function y(e){return e===G?e:m(e,n)}const v=new Map;function w(e){if(!(e instanceof x))throw new Error("ExtendedPoint expected")}class x{constructor(e,t,r,n){if(this.ex=e,this.ey=t,this.ez=r,this.et=n,!g(e))throw new Error("x required");if(!g(t))throw new Error("y required");if(!g(r))throw new Error("z required");if(!g(n))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof x)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};if(!g(t)||!g(r))throw new Error("invalid affine point");return new x(t,r,Z,l(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(x.fromAffine)}_setWindowSize(e){this._WINDOW_SIZE=e,v.delete(this)}assertValidity(){const{a:e,d:r}=t;if(this.is0())throw new Error("bad point: ZERO");const{ex:n,ey:i,ez:a,et:o}=this,s=l(n*n),c=l(i*i),u=l(a*a),f=l(u*u),d=l(s*e);if(l(u*l(d+c))!==l(f+l(r*l(s*c))))throw new Error("bad point: equation left != right (1)");if(l(n*i)!==l(a*o))throw new Error("bad point: equation left != right (2)")}equals(e){w(e);const{ex:t,ey:r,ez:n}=this,{ex:i,ey:a,ez:o}=e,s=l(t*o),c=l(i*n),u=l(r*o),f=l(a*n);return s===c&&u===f}is0(){return this.equals(x.ZERO)}negate(){return new x(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:i}=this,a=l(r*r),o=l(n*n),s=l(W*l(i*i)),c=l(e*a),u=r+n,f=l(l(u*u)-a-o),d=c+o,h=d-s,p=c-o,b=l(f*h),g=l(d*p),m=l(f*p),y=l(h*d);return new x(b,g,y,m)}add(e){w(e);const{a:r,d:n}=t,{ex:i,ey:a,ez:o,et:s}=this,{ex:c,ey:u,ez:f,et:d}=e;if(r===BigInt(-1)){const e=l((a-i)*(u+c)),t=l((a+i)*(u-c)),r=l(t-e);if(r===G)return this.double();const n=l(o*W*d),h=l(s*W*f),p=h+n,b=t+e,g=h-n,m=l(p*r),y=l(b*g),v=l(p*g),w=l(r*b);return new x(m,y,w,v)}const h=l(i*c),p=l(a*u),b=l(s*n*d),g=l(o*f),m=l((i+a)*(c+u)-h-p),y=g-b,v=g+b,_=l(p-r*h),E=l(m*y),k=l(v*_),S=l(m*_),A=l(y*v);return new x(E,k,A,S)}subtract(e){return this.add(e.negate())}wNAF(e){return k.wNAFCached(this,v,e,x.normalizeZ)}multiply(e){const{p:t,f:r}=this.wNAF(m(e,n));return x.normalizeZ([t,r])[0]}multiplyUnsafe(e){let t=y(e);return t===G?E:this.equals(E)||t===Z?this:this.equals(_)?this.wNAF(t).p:k.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return k.unsafeLadder(this,n).is0()}toAffine(e){const{ex:t,ey:n,ez:i}=this,a=this.is0();null==e&&(e=a?K:r.inv(i));const o=l(t*e),s=l(n*e),c=l(i*e);if(a)return{x:G,y:Z};if(c!==Z)throw new Error("invZ was invalid");return{x:o,y:s}}clearCofactor(){const{h:e}=t;return e===Z?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:i,a}=t,o=r.BYTES,s=(e=(0,H.qj)("pointHex",e,o)).slice(),c=e[o-1];s[o-1]=-129&c;const d=H.lX(s);d===G||m(d,n?u:r.ORDER);const h=l(d*d),p=l(h-Z),b=l(i*h-a);let{isValid:g,value:y}=f(p,b);if(!g)throw new Error("Point.fromHex: invalid y coordinate");const v=(y&Z)===Z,w=!!(128&c);if(!n&&y===G&&w)throw new Error("Point.fromHex: x=0 and x_0=1");return w!==v&&(y=l(-y)),x.fromAffine({x:y,y:d})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=H.z(t,r.BYTES);return n[n.length-1]|=e&Z?128:0,n}toHex(){return H.My(this.toRawBytes())}}x.BASE=new x(t.Gx,t.Gy,Z,l(t.Gx*t.Gy)),x.ZERO=new x(G,Z,Z,G);const{BASE:_,ZERO:E}=x,k=(0,$.A)(x,8*s);function S(e){return(0,V.zi)(e,n)}function A(e){return S(H.lX(e))}function I(e){const t=s;e=(0,H.qj)("private key",e,t);const r=(0,H.qj)("hashed private key",a(e),2*t),n=d(r.slice(0,t)),i=r.slice(t,2*t),o=A(n),c=_.multiply(o),u=c.toRawBytes();return{head:n,prefix:i,scalar:o,point:c,pointBytes:u}}function B(e=new Uint8Array,...t){const r=H.Id(...t);return A(a(h(r,(0,H.qj)("context",e),!!i)))}const O=J;_._setWindowSize(8);return{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,n={}){e=(0,H.qj)("message",e),i&&(e=i(e));const{prefix:a,scalar:o,pointBytes:c}=I(t),u=B(n.context,a,e),l=_.multiply(u).toRawBytes(),f=S(u+B(n.context,l,c,e)*o);y(f);const d=H.Id(l,H.z(f,r.BYTES));return(0,H.qj)("result",d,2*s)},verify:function(e,t,n,a=O){const{context:o,zip215:s}=a,c=r.BYTES;e=(0,H.qj)("signature",e,2*c),t=(0,H.qj)("message",t),i&&(t=i(t));const u=H.lX(e.slice(c,2*c));let l,f,d;try{l=x.fromHex(n,s),f=x.fromHex(e.slice(0,c),s),d=_.multiplyUnsafe(u)}catch(e){return!1}if(!s&&l.isSmallOrder())return!1;const h=B(o,f.toRawBytes(),l.toRawBytes(),t);return f.add(l.multiplyUnsafe(h)).subtract(d).clearCofactor().equals(x.ZERO)},ExtendedPoint:x,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(r.BYTES),precompute:(e=8,t=x.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}const X=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Q=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ee=(BigInt(0),BigInt(1)),te=BigInt(2),re=BigInt(5),ne=BigInt(10),ie=BigInt(20),ae=BigInt(40),oe=BigInt(80);function se(e){const t=X,r=e*e%t*e%t,n=(0,V.zH)(r,te,t)*r%t,i=(0,V.zH)(n,ee,t)*e%t,a=(0,V.zH)(i,re,t)*i%t,o=(0,V.zH)(a,ne,t)*a%t,s=(0,V.zH)(o,ie,t)*o%t,c=(0,V.zH)(s,ae,t)*s%t,u=(0,V.zH)(c,oe,t)*c%t,l=(0,V.zH)(u,oe,t)*c%t,f=(0,V.zH)(l,ne,t)*a%t;return{pow_p_5_8:(0,V.zH)(f,te,t)*e%t,b2:r}}function ce(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function ue(e,t){const r=X,n=(0,V.zi)(t*t*t,r),i=se(e*(0,V.zi)(n*n*t,r)).pow_p_5_8;let a=(0,V.zi)(e*n*i,r);const o=(0,V.zi)(t*a*a,r),s=a,c=(0,V.zi)(a*Q,r),u=o===e,l=o===(0,V.zi)(-e,r),f=o===(0,V.zi)(-e*Q,r);return u&&(a=s),(l||f)&&(a=c),(0,V.dQ)(a,r)&&(a=(0,V.zi)(-a,r)),{isValid:u||l,value:a}}const le=(0,V.D0)(X,void 0,!0),fe={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:le,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:F,randomBytes:C.po,adjustScalarBytes:ce,uvRatio:ue},de=Y(fe);function he(e,t,r){if(t.length>255)throw new Error("Context is too big");return(0,C.Id)((0,C.AI)("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,t.length]),t,e)}Y({...fe,domain:he}),Y({...fe,domain:he,prehash:F});const pe=(le.ORDER+BigInt(3))/BigInt(8);le.pow(te,pe),le.sqrt(le.neg(le.ONE)),le.ORDER,BigInt(5),BigInt(8),BigInt(486662);(0,V.Tv)(le,le.neg(BigInt(486664)));BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var be,ge,me,ye,ve=function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},we=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class xe{constructor(e={}){be.set(this,void 0),ge.set(this,void 0),this[me]=this.entries.bind(this),this[ye]="ExpirableMap";const{source:t=[],expirationTime:r=6e5}=e,n=Date.now();ve(this,be,new Map([...t].map((([e,t])=>[e,{value:t,timestamp:n}]))),"f"),ve(this,ge,r,"f")}prune(){const e=Date.now();for(const[t,r]of we(this,be,"f").entries())e-r.timestamp>we(this,ge,"f")&&we(this,be,"f").delete(t);return this}set(e,t){this.prune();const r={value:t,timestamp:Date.now()};return we(this,be,"f").set(e,r),this}get(e){const t=we(this,be,"f").get(e);if(void 0!==t){if(!(Date.now()-t.timestamp>we(this,ge,"f")))return t.value;we(this,be,"f").delete(e)}}clear(){we(this,be,"f").clear()}entries(){const e=we(this,be,"f").entries();return function*(){for(const[t,r]of e)yield[t,r.value]}()}values(){const e=we(this,be,"f").values();return function*(){for(const t of e)yield t.value}()}keys(){return we(this,be,"f").keys()}forEach(e,t){for(const[r,n]of we(this,be,"f").entries())e.call(t,n.value,r,this)}has(e){return we(this,be,"f").has(e)}delete(e){return we(this,be,"f").delete(e)}get size(){return we(this,be,"f").size}}be=new WeakMap,ge=new WeakMap,me=Symbol.iterator,ye=Symbol.toStringTag;const _e=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw new Error("Length too long (> 4 bytes)")},Ee=(e,t,r)=>{if(r<=127)return e[t]=r,1;if(r<=255)return e[t]=129,e[t+1]=r,2;if(r<=65535)return e[t]=130,e[t+1]=r>>8,e[t+2]=r,3;if(r<=16777215)return e[t]=131,e[t+1]=r>>16,e[t+2]=r>>8,e[t+3]=r,4;throw new Error("Length too long (> 4 bytes)")},ke=(e,t)=>{if(e[t]<128)return 1;if(128===e[t])throw new Error("Invalid length 0");if(129===e[t])return 2;if(130===e[t])return 3;if(131===e[t])return 4;throw new Error("Length too long (> 4 bytes)")},Se=(e,t)=>{const r=ke(e,t);if(1===r)return e[t];if(2===r)return e[t+1];if(3===r)return(e[t+1]<<8)+e[t+2];if(4===r)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw new Error("Length too long (> 4 bytes)")},Ae=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Ie=Uint8Array.from([48,5,6,3,43,101,112]),Be=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]);function Oe(e,t){const r=2+_e(e.byteLength+1),n=t.byteLength+r+e.byteLength;let i=0;const a=new Uint8Array(1+_e(n)+n);return a[i++]=48,i+=Ee(a,i,n),a.set(t,i),i+=t.byteLength,a[i++]=3,i+=Ee(a,i,e.byteLength+1),a[i++]=0,a.set(new Uint8Array(e),i),a}const Te=(e,t)=>{let r=0;const n=(e,t)=>{if(i[r++]!==e)throw new Error("Expected: "+t)},i=new Uint8Array(e);if(n(48,"sequence"),r+=ke(i,r),!(0,l.HA)(i.slice(r,r+t.byteLength),t))throw new Error("Not the expected OID.");r+=t.byteLength,n(3,"bit string");const a=Se(i,r)-1;r+=ke(i,r),n(0,"0 padding");const o=i.slice(r);if(a!==o.length)throw new Error(`DER payload mismatch: Expected length ${a} actual length ${o.length}`);return o};var Ne,je,Me=function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},Re=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class Pe{constructor(e){if(Ne.set(this,void 0),je.set(this,void 0),e.byteLength!==Pe.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");Me(this,Ne,e,"f"),Me(this,je,Pe.derEncode(e),"f")}static from(e){return this.fromDer(e.toDer())}static fromRaw(e){return new Pe(e)}static fromDer(e){return new Pe(this.derDecode(e))}static derEncode(e){return Oe(e,Ie).buffer}static derDecode(e){const t=Te(e,Ie);if(t.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return t}get rawKey(){return Re(this,Ne,"f")}get derKey(){return Re(this,je,"f")}toDer(){return this.derKey}toRaw(){return this.rawKey}}Ne=new WeakMap,je=new WeakMap,Pe.RAW_KEY_LENGTH=32;var Ce,Ue,Le,ze,De=r(9837),qe=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class Fe extends Function{constructor(){return super(),Ce.add(this),this.observers=[],new Proxy(this,{apply:(e,t,r)=>qe(e,Ce,"m",Ue).call(e,r[0],...r.slice(1))})}subscribe(e){this.observers.push(e)}unsubscribe(e){this.observers=this.observers.filter((t=>t!==e))}notify(e,...t){this.observers.forEach((r=>r(e,...t)))}}Ce=new WeakSet,Ue=function(e,...t){this.notify(e,...t)};class Ve extends Fe{constructor(){return super(),Le.add(this),new Proxy(this,{apply:(e,t,r)=>qe(e,Le,"m",ze).call(e,r[0],...r.slice(1))})}log(e,...t){this.notify({message:e,level:"info"},...t)}warn(e,...t){this.notify({message:e,level:"warn"},...t)}error(e,t,...r){this.notify({message:e,level:"error",error:t},...r)}}Le=new WeakSet,ze=function(e,...t){this.log(e,...t)};var He,$e,Ge,Ze,We,Ke,Je,Ye,Xe,Qe=function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},et=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};!function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"}(Xe||(Xe={}));const tt=3e5,rt="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae",nt="aaaaa-aa";class it extends c.Y{constructor(e){super(e),this.message=e}}class at extends c.Y{constructor(e){super(e),this.message=e}}class ot{constructor(e={}){var t;if(He.add(this),this.rootKey=(0,l.aD)(rt),this._timeDiffMsecs=0,this._rootKeyFetched=!1,this._isAgent=!0,$e.set(this,0),this.log=new Ve,Ge.set(this,[]),Ze.set(this,[]),We.set(this,new xe({expirationTime:3e5})),Ke.set(this,!0),Ye.set(this,((e,t)=>{if(!1===et(this,Ke,"f"))return e;if(!t)throw new O.bK("Invalid signature from replica signed query: no matching node key found.");const{status:r,signatures:n=[],requestId:i}=e,a=(new TextEncoder).encode("\vic-response");for(const o of n){const{timestamp:n,identity:c}=o,f=s.p.fromUint8Array(c).toText();let d;if("replied"===r){const{reply:t}=e;d=(0,u.uF)({status:r,reply:t,timestamp:BigInt(n),request_id:i})}else{if("rejected"!==r)throw new Error(`Unknown status: ${r}`);{const{reject_code:t,reject_message:a,error_code:o}=e;d=(0,u.uF)({status:r,reject_code:t,reject_message:a,error_code:o,timestamp:BigInt(n),request_id:i})}}const h=(0,l.xW)(a,new Uint8Array(d)),p=null==t?void 0:t.nodeKeys.get(f);if(!p)throw new O.bK("Invalid signature from replica signed query: no matching node key found.");const b=Pe.fromDer(p).rawKey;if(de.verify(o.signature,new Uint8Array(h),new Uint8Array(b)))return e;throw new O.bK(`Invalid signature from replica ${f} signed query.`)}return e})),e.source){if(!(e.source instanceof ot))throw new Error("An Agent's source can only be another HttpAgent");this._identity=e.source._identity,this._fetch=e.source._fetch,this._host=e.source._host,this._credentials=e.source._credentials}else this._fetch=e.fetch||function(){let e;if("undefined"!=typeof window){if(!window.fetch)throw new it("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.");e=window.fetch.bind(window)}else if(void 0!==r.g){if(!r.g.fetch)throw new it("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.");e=r.g.fetch.bind(r.g)}else"undefined"!=typeof self&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw new it("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.")}()||fetch.bind(r.g),this._fetchOptions=e.fetchOptions,this._callOptions=e.callOptions;if(void 0!==e.host)e.host.match(/^[a-z]+:/)||"undefined"==typeof window?this._host=new URL(e.host):this._host=new URL(window.location.protocol+"//"+e.host);else if(void 0!==e.source)this._host=e.source._host;else{const e="undefined"!=typeof window?window.location:void 0;e||(this._host=new URL("https://icp-api.io"),this.log.warn("Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning."));const t=["ic0.app","icp0.io","127.0.0.1","localhost"],r=[".github.dev",".gitpod.io"],n=null==e?void 0:e.hostname;let i;n&&"string"==typeof n&&(i=r.some((e=>n.endsWith(e)))?n:t.find((e=>n.endsWith(e)))),e&&i?this._host=new URL(`${e.protocol}//${i}${e.port?":"+e.port:""}`):(this._host=new URL("https://icp-api.io"),this.log.warn("Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning."))}if(void 0!==e.verifyQuerySignatures&&Qe(this,Ke,e.verifyQuerySignatures,"f"),this._retryTimes=null!==(t=e.retryTimes)&&void 0!==t?t:3,this._host.hostname.endsWith(".ic0.app")?this._host.hostname="ic0.app":this._host.hostname.endsWith(".icp0.io")?this._host.hostname="icp0.io":this._host.hostname.endsWith(".icp-api.io")&&(this._host.hostname="icp-api.io"),e.credentials){const{name:t,password:r}=e.credentials;this._credentials=`${t}${r?":"+r:""}`}this._identity=Promise.resolve(e.identity||new p),this.addTransform("update",k(x)),e.useQueryNonces&&this.addTransform("query",k(x)),e.logToConsole&&this.log.subscribe((e=>{"error"===e.level?console.error(e.message):"warn"===e.level?console.warn(e.message):console.log(e.message)}))}get waterMark(){return et(this,$e,"f")}isLocal(){const e=this._host.hostname;return"127.0.0.1"===e||e.endsWith("127.0.0.1")}addTransform(e,t,r=t.priority||0){if("update"===e){const e=et(this,Ze,"f").findIndex((e=>(e.priority||0)<r));et(this,Ze,"f").splice(e>=0?e:et(this,Ze,"f").length,0,Object.assign(t,{priority:r}))}else if("query"===e){const e=et(this,Ge,"f").findIndex((e=>(e.priority||0)<r));et(this,Ge,"f").splice(e>=0?e:et(this,Ge,"f").length,0,Object.assign(t,{priority:r}))}}async getPrincipal(){if(!this._identity)throw new at("This identity has expired due this application's security policy. Please refresh your authentication.");return(await this._identity).getPrincipal()}async call(e,t,r){const n=await(void 0!==r?await r:await this._identity);if(!n)throw new at("This identity has expired due this application's security policy. Please refresh your authentication.");const i=s.p.from(e),a=t.effectiveCanisterId?s.p.from(t.effectiveCanisterId):i,o=n.getPrincipal()||s.p.anonymous();let c=new E(tt);Math.abs(this._timeDiffMsecs)>3e4&&(c=new E(tt+this._timeDiffMsecs));const l={request_type:w.Call,canister_id:i,method_name:t.methodName,arg:t.arg,sender:o,ingress_expiry:c};let f=await this._transform({request:{body:null,method:"POST",headers:Object.assign({"Content-Type":"application/cbor"},this._credentials?{Authorization:"Basic "+btoa(this._credentials)}:{})},endpoint:"call",body:l});f=await n.transformRequest(f);const d=g.encode(f.body);this.log(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,f);const h=this._requestAndRetry((()=>this._fetch(""+new URL(`/api/v2/canister/${a.toText()}/call`,this._host),Object.assign(Object.assign(Object.assign({},this._callOptions),f.request),{body:d})))),[p,b]=await Promise.all([h,(0,u.Gb)(l)]),m=await p.arrayBuffer(),y=200===p.status&&m.byteLength>0?g.decode(m):null;return{requestId:b,response:{ok:p.ok,status:p.status,statusText:p.statusText,body:y,headers:A(p.headers)}}}async _requestAndRetry(e,t=0){let r;try{r=await e()}catch(r){if(this._retryTimes>t)return this.log.warn(`Caught exception while attempting to make request:\n ${r}\n Retrying request.`),await this._requestAndRetry(e,t+1);throw r}if(r.ok)return r;const n=await r.clone().text(),i=`Server returned an error:\n Code: ${r.status} (${r.statusText})\n Body: ${n}\n`;if(this._retryTimes>t)return this.log.warn(i+" Retrying request."),await this._requestAndRetry(e,t+1);throw new I(i,{ok:r.ok,status:r.status,statusText:r.statusText,headers:A(r.headers)})}async query(e,t,r){const n=t.effectiveCanisterId?s.p.from(t.effectiveCanisterId):s.p.from(e);this.log(`ecid ${n.toString()}`),this.log(`canisterId ${e.toString()}`);const[i,a]=await Promise.all([(async()=>{const i=await(void 0!==r?await r:await this._identity);if(!i)throw new at("This identity has expired due this application's security policy. Please refresh your authentication.");const a=s.p.from(e),o=(null==i?void 0:i.getPrincipal())||s.p.anonymous(),c={request_type:"query",canister_id:a,method_name:t.methodName,arg:t.arg,sender:o,ingress_expiry:new E(tt)},l=await(0,u.Gb)(c);let f=await this._transform({request:{method:"POST",headers:Object.assign({"Content-Type":"application/cbor"},this._credentials?{Authorization:"Basic "+btoa(this._credentials)}:{})},endpoint:"read",body:c});f=await(null==i?void 0:i.transformRequest(f));const d=g.encode(f.body),h={canister:a.toText(),ecid:n,transformedRequest:f,body:d,requestId:l};return await et(this,He,"m",Je).call(this,h)})(),(async()=>{if(!et(this,Ke,"f"))return;const e=et(this,We,"f").get(n.toString());return e||(await this.fetchSubnetKeys(n.toString()),et(this,We,"f").get(n.toString()))})()]);if(this.log("Query response:",i),!et(this,Ke,"f"))return i;try{return et(this,Ye,"f").call(this,i,a)}catch(t){this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),et(this,We,"f").delete(e.toString()),await this.fetchSubnetKeys(n.toString());const r=et(this,We,"f").get(e.toString());if(!r)throw new O.bK("Invalid signature from replica signed query: no matching node key found.");return et(this,Ye,"f").call(this,i,r)}}async createReadStateRequest(e,t){const r=await(void 0!==t?await t:await this._identity);if(!r)throw new at("This identity has expired due this application's security policy. Please refresh your authentication.");const n=(null==r?void 0:r.getPrincipal())||s.p.anonymous(),i=await this._transform({request:{method:"POST",headers:Object.assign({"Content-Type":"application/cbor"},this._credentials?{Authorization:"Basic "+btoa(this._credentials)}:{})},endpoint:"read_state",body:{request_type:"read_state",paths:e.paths,sender:n,ingress_expiry:new E(tt)}});return null==r?void 0:r.transformRequest(i)}async readState(e,t,r,n){const i="string"==typeof e?s.p.fromText(e):e,a=null!=n?n:await this.createReadStateRequest(t,r),o=g.encode(a.body);this.log(`fetching "/api/v2/canister/${i}/read_state" with request:`,a);const c=await this._requestAndRetry((()=>this._fetch(""+new URL(`/api/v2/canister/${i}/read_state`,this._host),Object.assign(Object.assign(Object.assign({},this._fetchOptions),a.request),{body:o}))));if(!c.ok)throw new Error(`Server returned an error:\n Code: ${c.status} (${c.statusText})\n Body: ${await c.text()}\n`);const u=g.decode(await c.arrayBuffer());this.log("Read state response:",u);const l=await this.parseTimeFromResponse(u);return l>0&&(this.log("Read state response time:",l),Qe(this,$e,l,"f")),u}async parseTimeFromResponse(e){let t;if(e.certificate){const r=g.decode(e.certificate);if(!r||!("tree"in r))throw new Error("Could not decode time from response");t=r.tree;const n=(0,O.hV)(["time"],t);if(!n)throw new Error("Time was not found in the response or was not in its expected format.");if(!(n instanceof ArrayBuffer||ArrayBuffer.isView(n)))throw new Error("Time was not found in the response or was not in its expected format.");const i=(0,De.A)((0,l.em)(n));return this.log("Time from response:",i),this.log("Time from response in milliseconds:",Number(i)),Number(i)}return this.log.warn("No certificate found in response"),0}async syncTime(e){const t=await Promise.resolve().then(r.bind(r,8050)),n=Date.now();try{e||this.log("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");const r=(await t.request({canisterId:null!=e?e:s.p.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),agent:this,paths:["time"]})).get("time");r&&(this._timeDiffMsecs=Number(r)-Number(n))}catch(e){this.log.error("Caught exception while attempting to sync time",e)}}async status(){const e=this._credentials?{Authorization:"Basic "+btoa(this._credentials)}:{};this.log('fetching "/api/v2/status"');const t=await this._requestAndRetry((()=>this._fetch(""+new URL("/api/v2/status",this._host),Object.assign({headers:e},this._fetchOptions))));return g.decode(await t.arrayBuffer())}async fetchRootKey(){return this._rootKeyFetched||(this.rootKey=(await this.status()).root_key,this._rootKeyFetched=!0),this.rootKey}invalidateIdentity(){this._identity=null}replaceIdentity(e){this._identity=Promise.resolve(e)}async fetchSubnetKeys(e){const t=s.p.from(e),r=(await(0,B.request)({canisterId:t,paths:["subnet"],agent:this})).get("subnet");if(r&&"object"==typeof r&&"nodeKeys"in r)return et(this,We,"f").set(t.toText(),r),r}_transform(e){let t=Promise.resolve(e);if("call"===e.endpoint)for(const e of et(this,Ze,"f"))t=t.then((t=>e(t).then((e=>e||t))));else for(const e of et(this,Ge,"f"))t=t.then((t=>e(t).then((e=>e||t))));return t}}var st;$e=new WeakMap,Ge=new WeakMap,Ze=new WeakMap,We=new WeakMap,Ke=new WeakMap,Ye=new WeakMap,He=new WeakSet,Je=async function e(t,r=0){var n,i;const{ecid:a,transformedRequest:o,body:s,requestId:u}=t;let l;try{const e=await this._fetch(""+new URL(`/api/v2/canister/${a.toString()}/query`,this._host),Object.assign(Object.assign(Object.assign({},this._fetchOptions),o.request),{body:s}));if(200!==e.status)throw new I(`Server returned an error:\n Code: ${e.status} (${e.statusText})\n Body: ${await e.text()}\n`,{ok:e.ok,status:e.status,statusText:e.statusText,headers:A(e.headers)});{const t=g.decode(await e.arrayBuffer());l=Object.assign(Object.assign({},t),{httpDetails:{ok:e.ok,status:e.status,statusText:e.statusText,headers:A(e.headers)},requestId:u})}}catch(n){if(r<this._retryTimes)return this.log.warn(`Caught exception while attempting to make query:\n ${n}\n Retrying query.`),await et(this,He,"m",e).call(this,t,r+1);throw n}const f=null===(i=null===(n=l.signatures)||void 0===n?void 0:n[0])||void 0===i?void 0:i.timestamp;if(!et(this,Ke,"f"))return l;if(!f)throw new Error("Timestamp not found in query response. This suggests a malformed or malicious response.");const d=Number(BigInt(f)/BigInt(1e6));if(this.log("watermark and timestamp",{waterMark:this.waterMark,timestamp:d}),Number(this.waterMark)>d){const n=new c.Y("Timestamp is below the watermark. Retrying query.");if(this.log.error("Timestamp is below",n,{timestamp:f,waterMark:this.waterMark}),r<this._retryTimes)return await et(this,He,"m",e).call(this,t,r+1);throw new c.Y(`Timestamp failed to pass the watermark after retrying the configured ${this._retryTimes} times. We cannot guarantee the integrity of the response since it could be a replay attack.`)}return l},function(e){e.Error="err",e.GetPrincipal="gp",e.GetPrincipalResponse="gpr",e.Query="q",e.QueryResponse="qr",e.Call="c",e.CallResponse="cr",e.ReadState="rs",e.ReadStateResponse="rsr",e.Status="s",e.StatusResponse="sr"}(st||(st={}));class ct{constructor(e,t){this._frontend=e,this._agent=t}onmessage(e){switch(e.type){case st.GetPrincipal:this._agent.getPrincipal().then((t=>{this._frontend({id:e.id,type:st.GetPrincipalResponse,response:t.toText()})}));break;case st.Query:this._agent.query(...e.args).then((t=>{this._frontend({id:e.id,type:st.QueryResponse,response:t})}));break;case st.Call:this._agent.call(...e.args).then((t=>{this._frontend({id:e.id,type:st.CallResponse,response:t})}));break;case st.ReadState:this._agent.readState(...e.args).then((t=>{this._frontend({id:e.id,type:st.ReadStateResponse,response:t})}));break;case st.Status:this._agent.status().then((t=>{this._frontend({id:e.id,type:st.StatusResponse,response:t})}));break;default:throw new Error(`Invalid message received: ${JSON.stringify(e)}`)}}}class ut{constructor(e){this._backend=e,this._nextId=0,this._pendingCalls=new Map,this.rootKey=null}onmessage(e){const t=e.id,r=this._pendingCalls.get(t);if(!r)throw new Error("A proxy get the same message twice...");this._pendingCalls.delete(t);const[n,i]=r;switch(e.type){case st.Error:return i(e.error);case st.GetPrincipalResponse:case st.CallResponse:case st.QueryResponse:case st.ReadStateResponse:case st.StatusResponse:return n(e.response);default:throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(e)}`)}}async getPrincipal(){return this._sendAndWait({id:this._nextId++,type:st.GetPrincipal}).then((e=>{if("string"!=typeof e)throw new Error("Invalid principal received.");return s.p.fromText(e)}))}readState(e,t){return this._sendAndWait({id:this._nextId++,type:st.ReadState,args:[e.toString(),t]})}call(e,t){return this._sendAndWait({id:this._nextId++,type:st.Call,args:[e.toString(),t]})}status(){return this._sendAndWait({id:this._nextId++,ty