/* esm.sh - @dfinity/agent@1.4.0 */
import*as __0$ from"/buffer@^6.0.3?target=es2022";import*as __1$ from"/@noble/curves@^1.4.0/bls12-381?target=es2022";import*as __2$ from"/borc@^2.1.1?target=es2022";import*as __3$ from"/simple-cbor@^0.4.1?target=es2022";import*as __4$ from"/@dfinity/candid@1.4.0/X-ZEBkZmluaXR5L3ByaW5jaXBhbEAxLjQuMA/es2022/candid.mjs";import*as __5$ from"/@noble/hashes@^1.3.1/sha256?target=es2022";import*as __6$ from"/@dfinity/principal@1.4.0/es2022/principal.mjs";import*as __7$ from"/@noble/curves@^1.4.0/ed25519?target=es2022";var require=n=>{const e=m=>typeof m.default<"u"?m.default:m,c=m=>Object.assign({__esModule:true},m);switch(n){case"buffer/":return e(__0$);case"@noble/curves/bls12-381":return e(__1$);case"borc":return e(__2$);case"simple-cbor":return c(__3$);case"@dfinity/candid":return c(__4$);case"@noble/hashes/sha256":return e(__5$);case"@dfinity/principal":return c(__6$);case"@noble/curves/ed25519":return e(__7$);default:console.error('module "'+n+'" not found');return null;}};
var ri=Object.create;var Er=Object.defineProperty;var ni=Object.getOwnPropertyDescriptor;var ii=Object.getOwnPropertyNames;var si=Object.getPrototypeOf,ai=Object.prototype.hasOwnProperty;var E=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var oi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ii(t))!ai.call(e,i)&&i!==r&&Er(e,i,{get:()=>t[i],enumerable:!(n=ni(t,i))||n.enumerable});return e};var ci=(e,t,r)=>(r=e!=null?ri(si(e)):{},oi(t||!e||!e.__esModule?Er(r,"default",{value:e,enumerable:!0}):r,e));var Tr=g(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.ReplicaRejectCode=void 0;var ui;(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"})(ui=xe.ReplicaRejectCode||(xe.ReplicaRejectCode={}))});var me=g(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.AgentError=void 0;var Bt=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};Ye.AgentError=Bt});var H=g(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.bufFromBufLike=q.uint8ToBuf=q.bufEquals=q.compare=q.fromHex=q.toHex=q.concat=void 0;function li(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.byteLength,0)),r=0;for(let n of e)t.set(new Uint8Array(n),r),r+=n.byteLength;return t.buffer}q.concat=li;function di(e){return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}q.toHex=di;var fi=new RegExp(/^[0-9a-fA-F]+$/);function hi(e){if(!fi.test(e))throw new Error("Invalid hexadecimal string.");let t=[...e].reduce((r,n,i)=>(r[i/2|0]=(r[i/2|0]||"")+n,r),[]).map(r=>Number.parseInt(r,16));return new Uint8Array(t).buffer}q.fromHex=hi;function Ar(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;let r=new Uint8Array(e),n=new Uint8Array(t);for(let i=0;i<r.length;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}q.compare=Ar;function _i(e,t){return Ar(e,t)===0}q.bufEquals=_i;function Je(e){return new DataView(e.buffer,e.byteOffset,e.byteLength).buffer}q.uint8ToBuf=Je;function Pr(e){return e instanceof Uint8Array?Je(e):e instanceof ArrayBuffer?e:Array.isArray(e)?Je(new Uint8Array(e)):"buffer"in e?Pr(e.buffer):Je(new Uint8Array(e))}q.bufFromBufLike=Pr});var Me=g(U=>{"use strict";var pi=U&&U.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(U,"__esModule",{value:!0});U.hashOfMap=U.requestIdOf=U.hashValue=U.hash=void 0;var Rr=E("@dfinity/candid"),yi=pi(E("borc")),gi=E("@noble/hashes/sha256"),je=H();function ie(e){return(0,je.uint8ToBuf)(gi.sha256.create().update(new Uint8Array(e)).digest())}U.hash=ie;function Ne(e){if(e instanceof yi.default.Tagged)return Ne(e.value);if(typeof e=="string")return Sr(e);if(typeof e=="number")return ie((0,Rr.lebEncode)(e));if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return ie(e);if(Array.isArray(e)){let t=e.map(Ne);return ie((0,je.concat)(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return ie(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return Ne(e.toHash());if(typeof e=="object")return Ft(e);if(typeof e=="bigint")return ie((0,Rr.lebEncode)(e))}throw Object.assign(new Error(`Attempt to hash a value of unsupported type: ${e}`),{value:e})}U.hashValue=Ne;var Sr=e=>{let t=new TextEncoder().encode(e);return ie(t)};function wi(e){return Ft(e)}U.requestIdOf=wi;function Ft(e){let n=Object.entries(e).filter(([,a])=>a!==void 0).map(([a,d])=>{let c=Sr(a),l=Ne(d);return[c,l]}).sort(([a],[d])=>(0,je.compare)(a,d)),i=(0,je.concat)(...n.map(a=>(0,je.concat)(...a)));return ie(i)}U.hashOfMap=Ft});var Ut=g(Y=>{"use strict";var bi=Y&&Y.__rest||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(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,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};Object.defineProperty(Y,"__esModule",{value:!0});Y.createIdentityDescriptor=Y.AnonymousIdentity=Y.SignIdentity=void 0;var qr=E("@dfinity/principal"),mi=Me(),xr=H(),vi=new TextEncoder().encode(`
ic-request`),Vt=class{getPrincipal(){return this._principal||(this._principal=qr.Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r}=t,n=bi(t,["body"]),i=await(0,mi.requestIdOf)(r);return Object.assign(Object.assign({},n),{body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign((0,xr.concat)(vi,i))}})}};Y.SignIdentity=Vt;var Ht=class{getPrincipal(){return qr.Principal.anonymous()}async transformRequest(t){return Object.assign(Object.assign({},t),{body:{content:t.body}})}};Y.AnonymousIdentity=Ht;function Oi(e){return"getPublicKey"in e?{type:"PublicKeyIdentity",publicKey:(0,xr.toHex)(e.getPublicKey().toDer())}:{type:"AnonymousIdentity"}}Y.createIdentityDescriptor=Oi});var ke=g(R=>{"use strict";var Ei=R&&R.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ti=R&&R.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Ai=R&&R.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Ei(t,e,r);return Ti(t,e),t},Pi=R&&R.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(R,"__esModule",{value:!0});R.decode=R.encode=R.CborTag=void 0;var Ri=Pi(E("borc")),ve=Ai(E("simple-cbor")),Si=E("simple-cbor"),Xe=H(),$t=class{get name(){return"Principal"}get priority(){return 0}match(t){return t&&t._isPrincipal===!0}encode(t){return ve.value.bytes(t.toUint8Array())}},Kt=class{get name(){return"Buffer"}get priority(){return 1}match(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)}encode(t){return ve.value.bytes(new Uint8Array(t))}},Wt=class{get name(){return"BigInt"}get priority(){return 1}match(t){return typeof t=="bigint"}encode(t){return t>BigInt(0)?ve.value.tagged(2,ve.value.bytes((0,Xe.fromHex)(t.toString(16)))):ve.value.tagged(3,ve.value.bytes((0,Xe.fromHex)((BigInt("-1")*t).toString(16))))}},Ze=Si.SelfDescribeCborSerializer.withDefaultEncoders(!0);Ze.addEncoder(new $t);Ze.addEncoder(new Kt);Ze.addEncoder(new Wt);var Nr;(function(e){e[e.Uint64LittleEndian=71]="Uint64LittleEndian",e[e.Semantic=55799]="Semantic"})(Nr=R.CborTag||(R.CborTag={}));function qi(e){return Ze.serialize(e)}R.encode=qi;function jr(e){let t=e.byteLength,r=BigInt(0);for(let n=0;n<t;n++)r=r*BigInt(256)+BigInt(e[n]);return r}var Gt=class extends Ri.default.Decoder{createByteString(t){return(0,Xe.concat)(...t)}createByteStringFromHeap(t,r){return t===r?new ArrayBuffer(0):new Uint8Array(this._heap.slice(t,r))}};function xi(e){let t=new Uint8Array(e),r=new Gt({size:t.byteLength,tags:{2:n=>jr(n),3:n=>-jr(n),[Nr.Semantic]:n=>n}});try{return r.decodeFirst(t)}catch(n){throw new Error(`Failed to decode CBOR: ${n}, input: ${(0,Xe.toHex)(t)}`)}}R.decode=xi});var zt=g(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.randomNumber=void 0;var ji=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};Ie.randomNumber=ji});var Ce=g(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.makeNonce=fe.SubmitRequestType=void 0;var De=zt(),Ni;(function(e){e.Call="call"})(Ni=fe.SubmitRequestType||(fe.SubmitRequestType={}));function Mi(){let e=new ArrayBuffer(16),t=new DataView(e),r=(0,De.randomNumber)(),n=(0,De.randomNumber)(),i=(0,De.randomNumber)(),s=(0,De.randomNumber)();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,i),t.setUint32(12,s),e}fe.makeNonce=Mi});var et=g(x=>{"use strict";var ki=x&&x.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ci=x&&x.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Bi=x&&x.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ki(t,e,r);return Ci(t,e),t};Object.defineProperty(x,"__esModule",{value:!0});x.httpHeadersTransform=x.makeExpiryTransform=x.makeNonceTransform=x.Expiry=void 0;var Fi=E("@dfinity/candid"),Vi=Bi(E("simple-cbor")),Hi=Ce(),Ui=BigInt(1e6),$i=60*1e3,Le=class{constructor(t){let s=BigInt(Math.floor(Date.now()+t-$i))*Ui/BigInt(1e9)/BigInt(60)*BigInt(60)*BigInt(1e9);this._value=s}toCBOR(){return Vi.value.u64(this._value.toString(16),16)}toHash(){return(0,Fi.lebEncode)(this._value)}};x.Expiry=Le;function Ki(e=Hi.makeNonce){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint==="call"&&(t.body.nonce=e())}}x.makeNonceTransform=Ki;function Wi(e){return async t=>{t.body.ingress_expiry=new Le(e)}}x.makeExpiryTransform=Wi;function Gi(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}x.httpHeadersTransform=Gi});var Yt=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.AgentHTTPResponseError=void 0;var zi=me(),Qt=class extends zi.AgentError{constructor(t,r){super(t),this.response=r,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}};tt.AgentHTTPResponseError=Qt});var Xt=g(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.blsVerify=Be.verify=void 0;var Qi=E("@noble/curves/bls12-381"),Jt=H();function Yi(e,t,r){let n=typeof e=="string"?e:(0,Jt.toHex)(e),i=typeof t=="string"?t:(0,Jt.toHex)(t),s=typeof r=="string"?r:(0,Jt.toHex)(r);return Qi.bls12_381.verifyShortSignature(i,s,n)}Be.blsVerify=Yi});var rt=g(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.decodeTime=he.decodeLeb128=void 0;var Mr=E("@dfinity/candid"),Ji=e=>(0,Mr.lebDecode)(new Mr.PipeArrayBuffer(e));he.decodeLeb128=Ji;var Xi=e=>{let t=(0,he.decodeLeb128)(e);return new Date(Number(t)/1e6)};he.decodeTime=Xi});var $e=g(y=>{"use strict";var Zi=y&&y.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Ii=y&&y.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),kr=y&&y.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Zi(t,e,r);return Ii(t,e),t};Object.defineProperty(y,"__esModule",{value:!0});y.check_canister_ranges=y.find_label=y.flatten_forks=y.lookup_path=y.LookupStatus=y.reconstruct=y.lookupResultToBuffer=y.Certificate=y.hashTreeToString=y.NodeType=y.CertificateVerificationError=void 0;var Cr=kr(ke()),Di=me(),nt=Me(),G=H(),Zt=E("@dfinity/principal"),Li=kr(Xt()),es=rt(),te=class extends Di.AgentError{constructor(t){super(`Invalid certificate: ${t}`)}};y.CertificateVerificationError=te;var S;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(S=y.NodeType||(y.NodeType={}));function it(e){let t=n=>n.split(`
`).map(i=>"  "+i).join(`
`);function r(n){let i=new TextDecoder(void 0,{fatal:!0});try{return JSON.stringify(i.decode(n))}catch{return`data(...${n.byteLength} bytes)`}}switch(e[0]){case S.Empty:return"()";case S.Fork:if(e[1]instanceof Array&&e[2]instanceof ArrayBuffer){let n=it(e[1]),i=it(e[2]);return`sub(
 left:
${t(n)}
---
 right:
${t(i)}
)`}else throw new Error("Invalid tree structure for fork");case S.Labeled:if(e[1]instanceof ArrayBuffer&&e[2]instanceof ArrayBuffer){let n=r(e[1]),i=it(e[2]);return`label(
 label:
${t(n)}
 sub:
${t(i)}
)`}else throw new Error("Invalid tree structure for labeled");case S.Leaf:{if(e[1]){if(Array.isArray(e[1]))return JSON.stringify(e[1])}else throw new Error("Invalid tree structure for leaf");return`leaf(...${e[1].byteLength} bytes)`}case S.Pruned:{if(e[1]){if(Array.isArray(e[1]))return JSON.stringify(e[1])}else throw new Error("Invalid tree structure for pruned");return`pruned(${(0,G.toHex)(new Uint8Array(e[1]))}`}default:return`unknown(${JSON.stringify(e[0])})`}}y.hashTreeToString=it;function ts(e,t){let r=new Uint8Array(e),n=new Uint8Array(t);for(let i=0;i<r.length;i++)if(r[i]>n[i])return!0;return!1}var It=class e{constructor(t,r,n,i,s=5){this._rootKey=r,this._canisterId=n,this._blsVerify=i,this._maxAgeInMinutes=s,this.cert=Cr.decode(new Uint8Array(t))}static async create(t){let r=e.createUnverified(t);return await r.verify(),r}static createUnverified(t){let r=t.blsVerify;return r||(r=Li.blsVerify),new e(t.certificate,t.rootKey,t.canisterId,r,t.maxAgeInMinutes)}lookup(t){return st(t,this.cert.tree)}lookup_label(t){return this.lookup([t])}async verify(){let t=await He(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,i=ns(r),s=(0,G.concat)(Ve("ic-state-root"),t),a=!1,d=Dt(this.lookup(["time"]));if(!d)throw new te("Certificate does not contain a time");let c=300*1e3,l=this._maxAgeInMinutes*60*1e3,u=Date.now(),h=u-l,v=u+c,p=(0,es.decodeTime)(d);if(p.getTime()<h)throw new te(`Certificate is signed more than ${this._maxAgeInMinutes} minutes in the past. Certificate time: `+p.toISOString()+" Current time: "+new Date(u).toISOString());if(p.getTime()>v)throw new te("Certificate is signed more than 5 minutes in the future. Certificate time: "+p.toISOString()+" Current time: "+new Date(u).toISOString());try{a=await this._blsVerify(new Uint8Array(i),new Uint8Array(n),new Uint8Array(s))}catch{a=!1}if(!a)throw new te("Signature verification failed")}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=await e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,maxAgeInMinutes:1/0});if(r.cert.delegation)throw new te("Delegation certificates cannot be nested");if(await r.verify(),!Br({canisterId:this._canisterId,subnetId:Zt.Principal.fromUint8Array(new Uint8Array(t.subnet_id)),tree:r.cert.tree}))throw new te(`Canister ${this._canisterId} not in range of delegations for subnet 0x${(0,G.toHex)(t.subnet_id)}`);let i=Dt(r.lookup(["subnet",t.subnet_id,"public_key"]));if(!i)throw new Error(`Could not find subnet key for subnet 0x${(0,G.toHex)(t.subnet_id)}`);return i}};y.Certificate=It;var Fe=(0,G.fromHex)("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),rs=96;function ns(e){let t=Fe.byteLength+rs;if(e.byteLength!==t)throw new TypeError(`BLS DER-encoded public key must be ${t} bytes long`);let r=e.slice(0,Fe.byteLength);if(!(0,G.bufEquals)(r,Fe))throw new TypeError(`BLS DER-encoded public key is invalid. Expect the following prefix: ${Fe}, but get ${r}`);return e.slice(Fe.byteLength)}function Dt(e){if(e.status===k.Found){if(e.value instanceof ArrayBuffer)return e.value;if(e.value instanceof Uint8Array)return e.value.buffer}}y.lookupResultToBuffer=Dt;async function He(e){switch(e[0]){case S.Empty:return(0,nt.hash)(Ve("ic-hashtree-empty"));case S.Pruned:return e[1];case S.Leaf:return(0,nt.hash)((0,G.concat)(Ve("ic-hashtree-leaf"),e[1]));case S.Labeled:return(0,nt.hash)((0,G.concat)(Ve("ic-hashtree-labeled"),e[1],await He(e[2])));case S.Fork:return(0,nt.hash)((0,G.concat)(Ve("ic-hashtree-fork"),await He(e[1]),await He(e[2])));default:throw new Error("unreachable")}}y.reconstruct=He;function Ve(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return(0,G.concat)(t,r)}var k;(function(e){e.Unknown="unknown",e.Absent="absent",e.Found="found"})(k=y.LookupStatus||(y.LookupStatus={}));var re;(function(e){e.Less="less",e.Greater="greater"})(re||(re={}));function st(e,t){if(e.length===0)switch(t[0]){case S.Leaf:{if(!t[1])throw new Error("Invalid tree structure for leaf");return t[1]instanceof ArrayBuffer?{status:k.Found,value:t[1]}:t[1]instanceof Uint8Array?{status:k.Found,value:t[1].buffer}:{status:k.Found,value:t[1]}}default:return{status:k.Found,value:t}}let r=typeof e[0]=="string"?new TextEncoder().encode(e[0]):e[0],n=Ue(r,t);switch(n.status){case k.Found:return st(e.slice(1),n.value);case re.Greater:case re.Less:return{status:k.Absent};default:return n}}y.lookup_path=st;function Lt(e){switch(e[0]){case S.Empty:return[];case S.Fork:return Lt(e[1]).concat(Lt(e[2]));default:return[e]}}y.flatten_forks=Lt;function Ue(e,t){switch(t[0]){case S.Labeled:return ts(e,t[1])?{status:re.Greater}:(0,G.bufEquals)(e,t[1])?{status:k.Found,value:t[2]}:{status:re.Less};case S.Fork:let r=Ue(e,t[1]);switch(r.status){case re.Greater:{let n=Ue(e,t[2]);return n.status===re.Less?{status:k.Absent}:n}case k.Unknown:{let n=Ue(e,t[2]);return n.status===re.Less?{status:k.Unknown}:n}default:return r}case S.Pruned:return{status:k.Unknown};default:return{status:k.Absent}}}y.find_label=Ue;function Br(e){let{canisterId:t,subnetId:r,tree:n}=e,i=st(["subnet",r.toUint8Array(),"canister_ranges"],n);if(i.status!==k.Found||!(i.value instanceof ArrayBuffer))throw new Error(`Could not find canister ranges for subnet ${r}`);return Cr.decode(i.value).map(c=>[Zt.Principal.fromUint8Array(c[0]),Zt.Principal.fromUint8Array(c[1])]).some(c=>c[0].ltEq(t)&&c[1].gtEq(t))}y.check_canister_ranges=Br});var Ke=g(T=>{"use strict";var is=T&&T.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),ss=T&&T.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),as=T&&T.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&is(t,e,r);return ss(t,e),t};Object.defineProperty(T,"__esModule",{value:!0});T.encodePath=T.fetchNodeKeys=T.request=T.CustomPath=void 0;var se=E("@dfinity/principal"),os=me(),ae=$e(),cs=H(),Hr=as(ke()),Fr=rt(),er=class{constructor(t,r,n){this.key=t,this.path=r,this.decodeStrategy=n}};T.CustomPath=er;var us=async e=>{let{agent:t,paths:r}=e,n=se.Principal.from(e.canisterId),i=[...new Set(r)],s=i.map(c=>(0,T.encodePath)(c,n)),a=new Map,d=i.map((c,l)=>(async()=>{var u;try{let h=await t.readState(n,{paths:[s[l]]}),v=await ae.Certificate.create({certificate:h.certificate,rootKey:t.rootKey,canisterId:n}),p=(V,M)=>{if(M==="subnet"){let Q=(0,T.fetchNodeKeys)(h.certificate,n,t.rootKey);return{path:M,data:Q}}else return{path:M,data:(0,ae.lookupResultToBuffer)(V.lookup((0,T.encodePath)(M,n)))}},{path:o,data:f}=p(v,i[l]);if(!f)console.warn(`Expected to find result for path ${o}, but instead found nothing.`),typeof o=="string"?a.set(o,null):a.set(o.key,null);else switch(o){case"time":{a.set(o,(0,Fr.decodeTime)(f));break}case"controllers":{a.set(o,hs(f));break}case"module_hash":{a.set(o,Vr(f));break}case"subnet":{a.set(o,f);break}case"candid":{a.set(o,new TextDecoder().decode(f));break}default:if(typeof o!="string"&&"key"in o&&"path"in o)switch(o.decodeStrategy){case"raw":a.set(o.key,f);break;case"leb128":{a.set(o.key,(0,Fr.decodeLeb128)(f));break}case"cbor":{a.set(o.key,Ur(f));break}case"hex":{a.set(o.key,Vr(f));break}case"utf-8":a.set(o.key,fs(f))}}}catch(h){if(!((u=h?.message)===null||u===void 0)&&u.includes("Invalid certificate"))throw new os.AgentError(h.message);typeof c!="string"&&"key"in c&&"path"in c?a.set(c.key,null):a.set(c,null),console.group(),console.warn(`Expected to find result for path ${c}, but instead found nothing.`),console.warn(h),console.groupEnd()}})());return await Promise.all(d),a};T.request=us;var ls=(e,t,r)=>{if(!t._isPrincipal)throw new Error("Invalid canisterId");let n=Hr.decode(new Uint8Array(e)),i=n.tree,s=n.delegation,a;if(s&&s.subnet_id?a=se.Principal.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof r<"u"?(a=se.Principal.selfAuthenticating(new Uint8Array(r)),s={subnet_id:a.toUint8Array(),certificate:new ArrayBuffer(0)}):(a=se.Principal.selfAuthenticating(se.Principal.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:a.toUint8Array(),certificate:new ArrayBuffer(0)}),!(0,ae.check_canister_ranges)({canisterId:t,subnetId:a,tree:i}))throw new Error("Canister not in range");let c=(0,ae.lookup_path)(["subnet",s.subnet_id,"node"],i);if(c.status!==ae.LookupStatus.Found)throw new Error("Node not found");if(c.value instanceof ArrayBuffer)throw new Error("Invalid node tree");let l=(0,ae.flatten_forks)(c.value),u=new Map;return l.forEach(h=>{let v=se.Principal.from(new Uint8Array(h[1])).toText(),p=(0,ae.lookup_path)(["public_key"],h[2]);if(p.status!==ae.LookupStatus.Found)throw new Error("Public key not found");let o=p.value;if(o.byteLength!==44)throw new Error("Invalid public key length");u.set(v,o)}),{subnetId:se.Principal.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:u}};T.fetchNodeKeys=ls;var ds=(e,t)=>{let r=new TextEncoder,n=s=>new DataView(r.encode(s).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(typeof e.path=="string"||e.path instanceof ArrayBuffer){let s=e.path,a=typeof s=="string"?n(s):s;return[n("canister"),i,n("metadata"),a]}else 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.`)};T.encodePath=ds;var Vr=e=>(0,cs.toHex)(e),Ur=e=>Hr.decode(e),fs=e=>new TextDecoder().decode(e),hs=e=>Ur(e).map(r=>se.Principal.fromUint8Array(new Uint8Array(r)))});var Gr=g(oe=>{"use strict";var $r=oe&&oe.__classPrivateFieldSet||function(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},C=oe&&oe.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},j,We,Kr,Wr;Object.defineProperty(oe,"__esModule",{value:!0});oe.ExpirableMap=void 0;var tr=class{constructor(t={}){j.set(this,void 0),We.set(this,void 0),this[Kr]=this.entries.bind(this),this[Wr]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=t,i=Date.now();$r(this,j,new Map([...r].map(([s,a])=>[s,{value:a,timestamp:i}])),"f"),$r(this,We,n,"f")}prune(){let t=Date.now();for(let[r,n]of C(this,j,"f").entries())t-n.timestamp>C(this,We,"f")&&C(this,j,"f").delete(r);return this}set(t,r){this.prune();let n={value:r,timestamp:Date.now()};return C(this,j,"f").set(t,n),this}get(t){let r=C(this,j,"f").get(t);if(r!==void 0){if(Date.now()-r.timestamp>C(this,We,"f")){C(this,j,"f").delete(t);return}return r.value}}clear(){C(this,j,"f").clear()}entries(){let t=C(this,j,"f").entries();return function*(){for(let[n,i]of t)yield[n,i.value]}()}values(){let t=C(this,j,"f").values();return function*(){for(let n of t)yield n.value}()}keys(){return C(this,j,"f").keys()}forEach(t,r){for(let[n,i]of C(this,j,"f").entries())t.call(r,i.value,n,this)}has(t){return C(this,j,"f").has(t)}delete(t){return C(this,j,"f").delete(t)}get size(){return C(this,j,"f").size}};oe.ExpirableMap=tr;j=new WeakMap,We=new WeakMap,Kr=Symbol.iterator,Wr=Symbol.toStringTag});var rr=g(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.unwrapDER=m.wrapDER=m.SECP256K1_OID=m.ED25519_OID=m.DER_COSE_OID=m.decodeLen=m.decodeLenBytes=m.encodeLen=m.encodeLenBytes=void 0;var _s=H(),ps=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)")};m.encodeLenBytes=ps;var ys=(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)")};m.encodeLen=ys;var gs=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw new Error("Invalid length 0");if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw new Error("Length too long (> 4 bytes)")};m.decodeLenBytes=gs;var ws=(e,t)=>{let r=(0,m.decodeLenBytes)(e,t);if(r===1)return e[t];if(r===2)return e[t+1];if(r===3)return(e[t+1]<<8)+e[t+2];if(r===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw new Error("Length too long (> 4 bytes)")};m.decodeLen=ws;m.DER_COSE_OID=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]);m.ED25519_OID=Uint8Array.from([48,5,6,3,43,101,112]);m.SECP256K1_OID=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]);function bs(e,t){let r=2+(0,m.encodeLenBytes)(e.byteLength+1),n=t.byteLength+r+e.byteLength,i=0,s=new Uint8Array(1+(0,m.encodeLenBytes)(n)+n);return s[i++]=48,i+=(0,m.encodeLen)(s,i,n),s.set(t,i),i+=t.byteLength,s[i++]=3,i+=(0,m.encodeLen)(s,i,e.byteLength+1),s[i++]=0,s.set(new Uint8Array(e),i),s}m.wrapDER=bs;var ms=(e,t)=>{let r=0,n=(d,c)=>{if(i[r++]!==d)throw new Error("Expected: "+c)},i=new Uint8Array(e);if(n(48,"sequence"),r+=(0,m.decodeLenBytes)(i,r),!(0,_s.bufEquals)(i.slice(r,r+t.byteLength),t))throw new Error("Not the expected OID.");r+=t.byteLength,n(3,"bit string");let s=(0,m.decodeLen)(i,r)-1;r+=(0,m.decodeLenBytes)(i,r),n(0,"0 padding");let a=i.slice(r);if(s!==a.length)throw new Error(`DER payload mismatch: Expected length ${s} actual length ${a.length}`);return a};m.unwrapDER=ms});var nr=g(ce=>{"use strict";var zr=ce&&ce.__classPrivateFieldSet||function(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},Qr=ce&&ce.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},ot,ct;Object.defineProperty(ce,"__esModule",{value:!0});ce.Ed25519PublicKey=void 0;var at=rr(),ut=class e{constructor(t){if(ot.set(this,void 0),ct.set(this,void 0),t.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");zr(this,ot,t,"f"),zr(this,ct,e.derEncode(t),"f")}static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static derEncode(t){return(0,at.wrapDER)(t,at.ED25519_OID).buffer}static derDecode(t){let r=(0,at.unwrapDER)(t,at.ED25519_OID);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}get rawKey(){return Qr(this,ot,"f")}get derKey(){return Qr(this,ct,"f")}toDer(){return this.derKey}toRaw(){return this.rawKey}};ce.Ed25519PublicKey=ut;ot=new WeakMap,ct=new WeakMap;ut.RAW_KEY_LENGTH=32});var Yr=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.ObservableLog=Oe.Observable=void 0;var lt=class{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(r=>r!==t)}notify(t,...r){this.observers.forEach(n=>n(t,...r))}};Oe.Observable=lt;var ir=class extends lt{constructor(){super()}print(t,...r){this.notify({message:t,level:"info"},...r)}warn(t,...r){this.notify({message:t,level:"warn"},...r)}error(t,r,...n){this.notify({message:t,level:"error",error:r},...n)}};Oe.ObservableLog=ir});var en=g(Z=>{"use strict";var J=Z&&Z.__classPrivateFieldSet||function(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},N=Z&&Z.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},X,dt,ft,ht,_t,pt,yt,gt,Ee;Object.defineProperty(Z,"__esModule",{value:!0});Z.exponentialBackoff=Z.ExponentialBackoff=void 0;var Jr=.5,Xr=1.5,Zr=500,Ir=6e4,Dr=9e5,Lr=10,Te=class e{constructor(t=e.default){X.set(this,void 0),dt.set(this,void 0),ft.set(this,void 0),ht.set(this,void 0),_t.set(this,void 0),pt.set(this,void 0),yt.set(this,void 0),gt.set(this,void 0),Ee.set(this,0);let{initialInterval:r=Zr,randomizationFactor:n=Jr,multiplier:i=Xr,maxInterval:s=Ir,maxElapsedTime:a=Dr,maxIterations:d=Lr,date:c=Date}=t;J(this,X,r,"f"),J(this,dt,n,"f"),J(this,ft,i,"f"),J(this,ht,s,"f"),J(this,gt,c,"f"),J(this,_t,c.now(),"f"),J(this,pt,a,"f"),J(this,yt,d,"f")}get ellapsedTimeInMsec(){return N(this,gt,"f").now()-N(this,_t,"f")}get currentInterval(){return N(this,X,"f")}get count(){return N(this,Ee,"f")}get randomValueFromInterval(){let t=N(this,dt,"f")*N(this,X,"f"),r=N(this,X,"f")-t,n=N(this,X,"f")+t;return Math.random()*(n-r)+r}incrementCurrentInterval(){var t;return J(this,X,Math.min(N(this,X,"f")*N(this,ft,"f"),N(this,ht,"f")),"f"),J(this,Ee,(t=N(this,Ee,"f"),t++,t),"f"),N(this,X,"f")}next(){return this.ellapsedTimeInMsec>=N(this,pt,"f")||N(this,Ee,"f")>=N(this,yt,"f")?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};Z.ExponentialBackoff=Te;X=new WeakMap,dt=new WeakMap,ft=new WeakMap,ht=new WeakMap,_t=new WeakMap,pt=new WeakMap,yt=new WeakMap,gt=new WeakMap,Ee=new WeakMap;Te.default={initialInterval:Zr,randomizationFactor:Jr,multiplier:Xr,maxInterval:Ir,maxElapsedTime:Dr,maxIterations:Lr,date:Date};function*vs(e=Te.default){let t=new Te(e),r=t.next();for(;r;)yield r,r=t.next()}Z.exponentialBackoff=vs});var cr=g(b=>{"use strict";var rn=b&&b.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Os=b&&b.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),nn=b&&b.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&rn(t,e,r);return Os(t,e),t},Es=b&&b.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&rn(t,e,r)},wt=b&&b.__classPrivateFieldSet||function(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},_=b&&b.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},D,z,_e,vt,Pe,Re,pe,ye,sn,Ot,Et;Object.defineProperty(b,"__esModule",{value:!0});b.HttpAgent=b.IdentityInvalidError=b.MANAGEMENT_CANISTER_ID=b.IC_ROOT_KEY=b.RequestStatusResponseStatus=b.makeNonce=void 0;var $=E("@dfinity/principal"),Se=me(),Ts=Ut(),ue=nn(ke()),bt=Me(),sr=H(),I=et(),ar=Ce(),tn=Yt(),As=Ke(),Ae=$e(),Ps=E("@noble/curves/ed25519"),Rs=Gr(),Ss=nr(),qs=rt(),xs=Yr(),js=en();Es(et(),b);var Ns=Ce();Object.defineProperty(b,"makeNonce",{enumerable:!0,get:function(){return Ns.makeNonce}});var Ms;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(Ms=b.RequestStatusResponseStatus||(b.RequestStatusResponseStatus={}));var mt=300*1e3;b.IC_ROOT_KEY="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";b.MANAGEMENT_CANISTER_ID="aaaaa-aa";var ks="ic0.app",Cs=".ic0.app",Bs="icp0.io",Fs=".icp0.io",Vs="icp-api.io",Hs=".icp-api.io",Ge=class extends Se.AgentError{constructor(t){super(t),this.message=t}},ge=class extends Se.AgentError{constructor(t){super(t),this.message=t}};b.IdentityInvalidError=ge;function Us(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw new Ge("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.");else if(typeof globalThis<"u")if(globalThis.fetch)e=globalThis.fetch.bind(globalThis);else throw new Ge("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.");else typeof self<"u"&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw new Ge("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.")}var or=class e{constructor(t={}){var r;if(D.add(this),this.rootKey=(0,sr.fromHex)(b.IC_ROOT_KEY),this._timeDiffMsecs=0,this._rootKeyFetched=!1,z.set(this,void 0),_e.set(this,void 0),this._isAgent=!0,vt.set(this,0),this.log=new xs.ObservableLog,Pe.set(this,[]),Re.set(this,[]),pe.set(this,new Rs.ExpirableMap({expirationTime:300*1e3})),ye.set(this,!0),Et.set(this,(i,s)=>{if(_(this,ye,"f")===!1)return i;if(!s)throw new Ae.CertificateVerificationError("Invalid signature from replica signed query: no matching node key found.");let{status:a,signatures:d=[],requestId:c}=i,l=new TextEncoder().encode("\vic-response");for(let u of d){let{timestamp:h,identity:v}=u,p=$.Principal.fromUint8Array(v).toText(),o;if(a==="replied"){let{reply:le}=i;o=(0,bt.hashOfMap)({status:a,reply:le,timestamp:BigInt(h),request_id:c})}else if(a==="rejected"){let{reject_code:le,reject_message:de,error_code:be}=i;o=(0,bt.hashOfMap)({status:a,reject_code:le,reject_message:de,error_code:be,timestamp:BigInt(h),request_id:c})}else throw new Error(`Unknown status: ${a}`);let f=(0,sr.concat)(l,new Uint8Array(o)),V=s?.nodeKeys.get(p);if(!V)throw new Ae.CertificateVerificationError("Invalid signature from replica signed query: no matching node key found.");let M=Ss.Ed25519PublicKey.fromDer(V).rawKey;if(Ps.ed25519.verify(u.signature,new Uint8Array(f),new Uint8Array(M)))return i;throw new Ae.CertificateVerificationError(`Invalid signature from replica ${p} signed query.`)}return i}),t.source){if(!(t.source instanceof e))throw new Error("An Agent's source can only be another HttpAgent");this._identity=t.source._identity,this._fetch=t.source._fetch,this._host=t.source._host,this._credentials=t.source._credentials}else this._fetch=t.fetch||Us()||fetch.bind(globalThis),this._fetchOptions=t.fetchOptions,this._callOptions=t.callOptions;if(t.host!==void 0)!t.host.match(/^[a-z]+:/)&&typeof window<"u"?this._host=new URL(window.location.protocol+"//"+t.host):this._host=new URL(t.host);else if(t.source!==void 0)this._host=t.source._host;else{let i=typeof window<"u"?window.location:void 0;i||(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."));let s=["ic0.app","icp0.io","127.0.0.1","localhost"],a=[".github.dev",".gitpod.io"],d=i?.hostname,c;d&&typeof d=="string"&&(a.some(l=>d.endsWith(l))?c=d:c=s.find(l=>d.endsWith(l))),i&&c?this._host=new URL(`${i.protocol}//${c}${i.port?":"+i.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."))}t.verifyQuerySignatures!==void 0&&wt(this,ye,t.verifyQuerySignatures,"f"),wt(this,z,(r=t.retryTimes)!==null&&r!==void 0?r:3,"f");let n=()=>new js.ExponentialBackoff({maxIterations:_(this,z,"f")});if(wt(this,_e,t.backoffStrategy||n,"f"),this._host.hostname.endsWith(Cs)?this._host.hostname=ks:this._host.hostname.endsWith(Fs)?this._host.hostname=Bs:this._host.hostname.endsWith(Hs)&&(this._host.hostname=Vs),t.credentials){let{name:i,password:s}=t.credentials;this._credentials=`${i}${s?":"+s:""}`}this._identity=Promise.resolve(t.identity||new Ts.AnonymousIdentity),this.addTransform("update",(0,I.makeNonceTransform)(ar.makeNonce)),t.useQueryNonces&&this.addTransform("query",(0,I.makeNonceTransform)(ar.makeNonce)),t.logToConsole&&this.log.subscribe(i=>{i.level==="error"?console.error(i.message):i.level==="warn"?console.warn(i.message):console.log(i.message)})}get waterMark(){return _(this,vt,"f")}isLocal(){let t=this._host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,r,n=r.priority||0){if(t==="update"){let i=_(this,Re,"f").findIndex(s=>(s.priority||0)<n);_(this,Re,"f").splice(i>=0?i:_(this,Re,"f").length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let i=_(this,Pe,"f").findIndex(s=>(s.priority||0)<n);_(this,Pe,"f").splice(i>=0?i:_(this,Pe,"f").length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this._identity)throw new ge("This identity has expired due this application's security policy. Please refresh your authentication.");return(await this._identity).getPrincipal()}async call(t,r,n){let i=await(n!==void 0?await n:await this._identity);if(!i)throw new ge("This identity has expired due this application's security policy. Please refresh your authentication.");let s=$.Principal.from(t),a=r.effectiveCanisterId?$.Principal.from(r.effectiveCanisterId):s,d=i.getPrincipal()||$.Principal.anonymous(),c=new I.Expiry(mt);Math.abs(this._timeDiffMsecs)>1e3*30&&(c=new I.Expiry(mt+this._timeDiffMsecs));let l={request_type:ar.SubmitRequestType.Call,canister_id:s,method_name:r.methodName,arg:r.arg,sender:d,ingress_expiry:c},u=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});u=await i.transformRequest(u);let h=ue.encode(u.body);this.log.print(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,u);let v=_(this,_e,"f").call(this),p=_(this,D,"m",Ot).call(this,{request:()=>this._fetch(""+new URL(`/api/v2/canister/${a.toText()}/call`,this._host),Object.assign(Object.assign(Object.assign({},this._callOptions),u.request),{body:h})),backoff:v,tries:0}),[o,f]=await Promise.all([p,(0,bt.requestIdOf)(l)]),V=await o.arrayBuffer(),M=o.status===200&&V.byteLength>0?ue.decode(V):null;return{requestId:f,response:{ok:o.ok,status:o.status,statusText:o.statusText,body:M,headers:(0,I.httpHeadersTransform)(o.headers)}}}async query(t,r,n){let i=_(this,_e,"f").call(this),s=r.effectiveCanisterId?$.Principal.from(r.effectiveCanisterId):$.Principal.from(t);this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${t.toString()}`);let a=async()=>{let u=await(n!==void 0?await n:await this._identity);if(!u)throw new ge("This identity has expired due this application's security policy. Please refresh your authentication.");let h=$.Principal.from(t),v=u?.getPrincipal()||$.Principal.anonymous(),p={request_type:"query",canister_id:h,method_name:r.methodName,arg:r.arg,sender:v,ingress_expiry:new I.Expiry(mt)},o=await(0,bt.requestIdOf)(p),f=await this._transform({request:{method:"POST",headers:Object.assign({"Content-Type":"application/cbor"},this._credentials?{Authorization:"Basic "+btoa(this._credentials)}:{})},endpoint:"read",body:p});f=await u?.transformRequest(f);let V=ue.encode(f.body),M={canister:h.toText(),ecid:s,transformedRequest:f,body:V,requestId:o,backoff:i,tries:0};return await _(this,D,"m",sn).call(this,M)},d=async()=>{if(!_(this,ye,"f"))return;let u=_(this,pe,"f").get(s.toString());return u||(await this.fetchSubnetKeys(s.toString()),_(this,pe,"f").get(s.toString()))},[c,l]=await Promise.all([a(),d()]);if(this.log.print("Query response:",c),!_(this,ye,"f"))return c;try{return _(this,Et,"f").call(this,c,l)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),_(this,pe,"f").delete(t.toString()),await this.fetchSubnetKeys(s.toString());let h=_(this,pe,"f").get(t.toString());if(!h)throw new Ae.CertificateVerificationError("Invalid signature from replica signed query: no matching node key found.");return _(this,Et,"f").call(this,c,h)}}async createReadStateRequest(t,r){let n=await(r!==void 0?await r:await this._identity);if(!n)throw new ge("This identity has expired due this application's security policy. Please refresh your authentication.");let i=n?.getPrincipal()||$.Principal.anonymous(),s=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:t.paths,sender:i,ingress_expiry:new I.Expiry(mt)}});return n?.transformRequest(s)}async readState(t,r,n,i){let s=typeof t=="string"?$.Principal.fromText(t):t,a=i??await this.createReadStateRequest(r,n),d=ue.encode(a.body);this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,a);let c=_(this,_e,"f").call(this),l=await _(this,D,"m",Ot).call(this,{request:()=>this._fetch(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this._host),Object.assign(Object.assign(Object.assign({},this._fetchOptions),a.request),{body:d})),backoff:c,tries:0});if(!l.ok)throw new Error(`Server returned an error:
  Code: ${l.status} (${l.statusText})
  Body: ${await l.text()}
`);let u=ue.decode(await l.arrayBuffer());this.log.print("Read state response:",u);let h=await this.parseTimeFromResponse(u);return h>0&&(this.log.print("Read state response time:",h),wt(this,vt,h,"f")),u}async parseTimeFromResponse(t){let r;if(t.certificate){let n=ue.decode(t.certificate);if(n&&"tree"in n)r=n.tree;else throw new Error("Could not decode time from response");let i=(0,Ae.lookup_path)(["time"],r);if(i.status!==Ae.LookupStatus.Found)throw new Error("Time was not found in the response or was not in its expected format.");if(!(i.value instanceof ArrayBuffer)&&!ArrayBuffer.isView(i))throw new Error("Time was not found in the response or was not in its expected format.");let s=(0,qs.decodeTime)((0,sr.bufFromBufLike)(i.value));return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",Number(s)),Number(s)}else this.log.warn("No certificate found in response");return 0}async syncTime(t){let r=await Promise.resolve().then(()=>nn(Ke())),n=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let s=(await r.request({canisterId:t??$.Principal.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),agent:this,paths:["time"]})).get("time");s&&(this._timeDiffMsecs=Number(s)-Number(n))}catch(i){this.log.error("Caught exception while attempting to sync time",i)}}async status(){let t=this._credentials?{Authorization:"Basic "+btoa(this._credentials)}:{};this.log.print('fetching "/api/v2/status"');let r=_(this,_e,"f").call(this),n=await _(this,D,"m",Ot).call(this,{backoff:r,request:()=>this._fetch(""+new URL("/api/v2/status",this._host),Object.assign({headers:t},this._fetchOptions)),tries:0});return ue.decode(await n.arrayBuffer())}async fetchRootKey(){return this._rootKeyFetched||(this.rootKey=(await this.status()).root_key,this._rootKeyFetched=!0),this.rootKey}invalidateIdentity(){this._identity=null}replaceIdentity(t){this._identity=Promise.resolve(t)}async fetchSubnetKeys(t){let r=$.Principal.from(t),i=(await(0,As.request)({canisterId:r,paths:["subnet"],agent:this})).get("subnet");if(i&&typeof i=="object"&&"nodeKeys"in i)return _(this,pe,"f").set(r.toText(),i),i}_transform(t){let r=Promise.resolve(t);if(t.endpoint==="call")for(let n of _(this,Re,"f"))r=r.then(i=>n(i).then(s=>s||i));else for(let n of _(this,Pe,"f"))r=r.then(i=>n(i).then(s=>s||i));return r}};b.HttpAgent=or;z=new WeakMap,_e=new WeakMap,vt=new WeakMap,Pe=new WeakMap,Re=new WeakMap,pe=new WeakMap,ye=new WeakMap,Et=new WeakMap,D=new WeakSet,sn=async function e(t){var r,n;let{ecid:i,transformedRequest:s,body:a,requestId:d,backoff:c,tries:l}=t,u=l===0?0:c.next();if(this.log.print(`fetching "/api/v2/canister/${i.toString()}/query" with tries:`,{tries:l,backoff:c,delay:u}),u===null)throw new Se.AgentError(`Timestamp failed to pass the watermark after retrying the configured ${_(this,z,"f")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);u>0&&await new Promise(o=>setTimeout(o,u));let h;try{this.log.print(`fetching "/api/v2/canister/${i.toString()}/query" with request:`,s);let o=await this._fetch(""+new URL(`/api/v2/canister/${i.toString()}/query`,this._host),Object.assign(Object.assign(Object.assign({},this._fetchOptions),s.request),{body:a}));if(o.status===200){let f=ue.decode(await o.arrayBuffer());h=Object.assign(Object.assign({},f),{httpDetails:{ok:o.ok,status:o.status,statusText:o.statusText,headers:(0,I.httpHeadersTransform)(o.headers)},requestId:d})}else throw new tn.AgentHTTPResponseError(`Gateway returned an error:
  Code: ${o.status} (${o.statusText})
  Body: ${await o.text()}
`,{ok:o.ok,status:o.status,statusText:o.statusText,headers:(0,I.httpHeadersTransform)(o.headers)})}catch(o){if(l<_(this,z,"f"))return this.log.warn(`Caught exception while attempting to make query:
  ${o}
  Retrying query.`),await _(this,D,"m",e).call(this,Object.assign(Object.assign({},t),{tries:l+1}));throw o}let v=(n=(r=h.signatures)===null||r===void 0?void 0:r[0])===null||n===void 0?void 0:n.timestamp;if(!_(this,ye,"f"))return h;if(!v)throw new Error("Timestamp not found in query response. This suggests a malformed or malicious response.");let p=Number(BigInt(v)/BigInt(1e6));if(this.log.print("watermark and timestamp",{waterMark:this.waterMark,timestamp:p}),Number(this.waterMark)>p){let o=new Se.AgentError("Timestamp is below the watermark. Retrying query.");if(this.log.error("Timestamp is below",o,{timestamp:v,waterMark:this.waterMark}),l<_(this,z,"f"))return await _(this,D,"m",e).call(this,Object.assign(Object.assign({},t),{tries:l+1}));throw new Se.AgentError(`Timestamp failed to pass the watermark after retrying the configured ${_(this,z,"f")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`)}return h},Ot=async function e(t){let{request:r,backoff:n,tries:i}=t,s=i===0?0:n.next();if(s===null)throw new Se.AgentError(`Timestamp failed to pass the watermark after retrying the configured ${_(this,z,"f")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);s>0&&await new Promise(l=>setTimeout(l,s));let a;try{a=await r()}catch(l){if(_(this,z,"f")>i)return this.log.warn(`Caught exception while attempting to make request:
  ${l}
  Retrying request.`),await _(this,D,"m",e).call(this,{request:r,backoff:n,tries:i+1});throw l}if(a.ok)return a;let d=await a.clone().text(),c=`Server returned an error:
  Code: ${a.status} (${a.statusText})
  Body: ${d}
`;if(i<_(this,z,"f"))return await _(this,D,"m",e).call(this,{request:r,backoff:n,tries:i+1});throw new tn.AgentHTTPResponseError(c,{ok:a.ok,status:a.status,statusText:a.statusText,headers:(0,I.httpHeadersTransform)(a.headers)})}});var an=g(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.ProxyAgent=ne.ProxyStubAgent=ne.ProxyMessageKind=void 0;var $s=E("@dfinity/principal"),O;(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"})(O=ne.ProxyMessageKind||(ne.ProxyMessageKind={}));var ur=class{constructor(t,r){this._frontend=t,this._agent=r}onmessage(t){switch(t.type){case O.GetPrincipal:this._agent.getPrincipal().then(r=>{this._frontend({id:t.id,type:O.GetPrincipalResponse,response:r.toText()})});break;case O.Query:this._agent.query(...t.args).then(r=>{this._frontend({id:t.id,type:O.QueryResponse,response:r})});break;case O.Call:this._agent.call(...t.args).then(r=>{this._frontend({id:t.id,type:O.CallResponse,response:r})});break;case O.ReadState:this._agent.readState(...t.args).then(r=>{this._frontend({id:t.id,type:O.ReadStateResponse,response:r})});break;case O.Status:this._agent.status().then(r=>{this._frontend({id:t.id,type:O.StatusResponse,response:r})});break;default:throw new Error(`Invalid message received: ${JSON.stringify(t)}`)}}};ne.ProxyStubAgent=ur;var lr=class{constructor(t){this._backend=t,this._nextId=0,this._pendingCalls=new Map,this.rootKey=null}onmessage(t){let r=t.id,n=this._pendingCalls.get(r);if(!n)throw new Error("A proxy get the same message twice...");this._pendingCalls.delete(r);let[i,s]=n;switch(t.type){case O.Error:return s(t.error);case O.GetPrincipalResponse:case O.CallResponse:case O.QueryResponse:case O.ReadStateResponse:case O.StatusResponse:return i(t.response);default:throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(t)}`)}}async getPrincipal(){return this._sendAndWait({id:this._nextId++,type:O.GetPrincipal}).then(t=>{if(typeof t!="string")throw new Error("Invalid principal received.");return $s.Principal.fromText(t)})}readState(t,r){return this._sendAndWait({id:this._nextId++,type:O.ReadState,args:[t.toString(),r]})}call(t,r){return this._sendAndWait({id:this._nextId++,type:O.Call,args:[t.toString(),r]})}status(){return this._sendAndWait({id:this._nextId++,type:O.Status})}query(t,r){return this._sendAndWait({id:this._nextId++,type:O.Query,args:[t.toString(),r]})}async _sendAndWait(t){return new Promise((r,n)=>{this._pendingCalls.set(t.id,[r,n]),this._backend(t)})}async fetchRootKey(){let t=(await this.status()).root_key;return this.rootKey=t,t}};ne.ProxyAgent=lr});var At=g(K=>{"use strict";var Ks=K&&K.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Tt=K&&K.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Ks(t,e,r)};Object.defineProperty(K,"__esModule",{value:!0});K.getDefaultAgent=void 0;Tt(Tr(),K);Tt(cr(),K);Tt(Yt(),K);Tt(an(),K);function Ws(){let e=typeof window>"u"?typeof globalThis>"u"?typeof self>"u"?void 0:self.ic.agent:globalThis.ic.agent:window.ic.agent;if(!e)throw new Error("No Agent could be found.");return e}K.getDefaultAgent=Ws});var dr=g(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.chain=P.backoff=P.timeout=P.throttle=P.maxAttempts=P.conditionalDelay=P.once=P.defaultStrategy=void 0;var on=H(),Gs=300*1e3;function zs(){return fn(un(cn(),1e3),dn(1e3,1.2),ln(Gs))}P.defaultStrategy=zs;function cn(){let e=!0;return async()=>e?(e=!1,!0):!1}P.once=cn;function un(e,t){return async(r,n,i)=>{if(await e(r,n,i))return new Promise(s=>setTimeout(s,t))}}P.conditionalDelay=un;function Qs(e){let t=e;return async(r,n,i)=>{if(--t<=0)throw new Error(`Failed to retrieve a reply for request after ${e} attempts:
  Request ID: ${(0,on.toHex)(n)}
  Request status: ${i}
`)}}P.maxAttempts=Qs;function Ys(e){return()=>new Promise(t=>setTimeout(t,e))}P.throttle=Ys;function ln(e){let t=Date.now()+e;return async(r,n,i)=>{if(Date.now()>t)throw new Error(`Request timed out after ${e} msec:
  Request ID: ${(0,on.toHex)(n)}
  Request status: ${i}
`)}}P.timeout=ln;function dn(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}P.backoff=dn;function fn(...e){return async(t,r,n)=>{for(let i of e)await i(t,r,n)}}P.chain=fn});var fr=g(B=>{"use strict";var Js=B&&B.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Xs=B&&B.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Zs=B&&B.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Js(t,e,r);return Xs(t,e),t};Object.defineProperty(B,"__esModule",{value:!0});B.pollForResponse=B.defaultStrategy=B.strategy=void 0;var we=At(),ze=$e(),hn=H();B.strategy=Zs(dr());var Is=dr();Object.defineProperty(B,"defaultStrategy",{enumerable:!0,get:function(){return Is.defaultStrategy}});async function _n(e,t,r,n,i,s){var a;let d=[new TextEncoder().encode("request_status"),r],c=i??await((a=e.createReadStateRequest)===null||a===void 0?void 0:a.call(e,{paths:[d]})),l=await e.readState(t,{paths:[d]},void 0,c);if(e.rootKey==null)throw new Error("Agent root key not initialized before polling");let u=await ze.Certificate.create({certificate:l.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:s}),h=(0,ze.lookupResultToBuffer)(u.lookup([...d,new TextEncoder().encode("status")])),v;switch(typeof h>"u"?v=we.RequestStatusResponseStatus.Unknown:v=new TextDecoder().decode(h),v){case we.RequestStatusResponseStatus.Replied:return(0,ze.lookupResultToBuffer)(u.lookup([...d,"reply"]));case we.RequestStatusResponseStatus.Received:case we.RequestStatusResponseStatus.Unknown:case we.RequestStatusResponseStatus.Processing:return await n(t,r,v),_n(e,t,r,n,c);case we.RequestStatusResponseStatus.Rejected:{let p=new Uint8Array((0,ze.lookupResultToBuffer)(u.lookup([...d,"reject_code"])))[0],o=new TextDecoder().decode((0,ze.lookupResultToBuffer)(u.lookup([...d,"reject_message"])));throw new Error(`Call was rejected:
  Request ID: ${(0,hn.toHex)(r)}
  Reject code: ${p}
  Reject text: ${o}
`)}case we.RequestStatusResponseStatus.Done:throw new Error(`Call was marked as done but we never saw the reply:
  Request ID: ${(0,hn.toHex)(r)}
`)}throw new Error("unreachable")}B.pollForResponse=_n});var pn=g(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.default=({IDL:e})=>{let t=e.Variant({mainnet:e.Null,testnet:e.Null}),r=e.Text,n=e.Record({network:t,address:r,min_confirmations:e.Opt(e.Nat32)}),i=e.Nat64,s=i,a=e.Record({network:t}),d=e.Nat64,c=e.Vec(d),l=e.Record({network:t,filter:e.Opt(e.Variant({page:e.Vec(e.Nat8),min_confirmations:e.Nat32})),address:r}),u=e.Vec(e.Nat8),h=e.Record({txid:e.Vec(e.Nat8),vout:e.Nat32}),v=e.Record({height:e.Nat32,value:i,outpoint:h}),p=e.Record({next_page:e.Opt(e.Vec(e.Nat8)),tip_height:e.Nat32,tip_block_hash:u,utxos:e.Vec(v)}),o=e.Record({transaction:e.Vec(e.Nat8),network:t}),f=e.Principal,V=e.Record({canister_id:f,num_requested_changes:e.Opt(e.Nat64)}),M=e.Variant({from_user:e.Record({user_id:e.Principal}),from_canister:e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal})}),Q=e.Variant({creation:e.Record({controllers:e.Vec(e.Principal)}),code_deployment:e.Record({mode:e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),module_hash:e.Vec(e.Nat8)}),controllers_change:e.Record({controllers:e.Vec(e.Principal)}),code_uninstall:e.Null}),le=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:M,details:Q}),de=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(le),total_num_changes:e.Nat64}),be=e.Record({canister_id:f}),br=e.Variant({controllers:e.Null,public:e.Null}),En=e.Record({freezing_threshold:e.Nat,controllers:e.Vec(e.Principal),reserved_cycles_limit:e.Nat,log_visibility:br,wasm_memory_limit:e.Nat,memory_allocation:e.Nat,compute_allocation:e.Nat}),Tn=e.Record({status:e.Variant({stopped:e.Null,stopping:e.Null,running:e.Null}),memory_size:e.Nat,cycles:e.Nat,settings:En,query_stats:e.Record({response_payload_bytes_total:e.Nat,num_instructions_total:e.Nat,num_calls_total:e.Nat,request_payload_bytes_total:e.Nat}),idle_cycles_burned_per_day:e.Nat,module_hash:e.Opt(e.Vec(e.Nat8)),reserved_cycles:e.Nat}),An=e.Record({canister_id:f}),Mt=e.Record({freezing_threshold:e.Opt(e.Nat),controllers:e.Opt(e.Vec(e.Principal)),reserved_cycles_limit:e.Opt(e.Nat),log_visibility:e.Opt(br),wasm_memory_limit:e.Opt(e.Nat),memory_allocation:e.Opt(e.Nat),compute_allocation:e.Opt(e.Nat)}),Pn=e.Record({settings:e.Opt(Mt),sender_canister_version:e.Opt(e.Nat64)}),Rn=e.Record({canister_id:f}),Sn=e.Record({canister_id:f}),qn=e.Record({canister_id:f}),mr=e.Variant({secp256k1:e.Null}),xn=e.Record({key_id:e.Record({name:e.Text,curve:mr}),canister_id:e.Opt(f),derivation_path:e.Vec(e.Vec(e.Nat8))}),jn=e.Record({public_key:e.Vec(e.Nat8),chain_code:e.Vec(e.Nat8)}),Nn=e.Record({canister_id:f}),Mn=e.Record({idx:e.Nat64,timestamp_nanos:e.Nat64,content:e.Vec(e.Nat8)}),kn=e.Record({canister_log_records:e.Vec(Mn)}),vr=e.Record({value:e.Text,name:e.Text}),kt=e.Record({status:e.Nat,body:e.Vec(e.Nat8),headers:e.Vec(vr)}),Cn=e.Record({url:e.Text,method:e.Variant({get:e.Null,head:e.Null,post:e.Null}),max_response_bytes:e.Opt(e.Nat64),body:e.Opt(e.Vec(e.Nat8)),transform:e.Opt(e.Record({function:e.Func([e.Record({context:e.Vec(e.Nat8),response:kt})],[kt],["query"]),context:e.Vec(e.Nat8)})),headers:e.Vec(vr)}),Or=e.Variant({reinstall:e.Null,upgrade:e.Opt(e.Record({wasm_memory_persistence:e.Opt(e.Variant({keep:e.Null,replace:e.Null})),skip_pre_upgrade:e.Opt(e.Bool)})),install:e.Null}),Ct=e.Record({hash:e.Vec(e.Nat8)}),Bn=e.Record({arg:e.Vec(e.Nat8),wasm_module_hash:e.Vec(e.Nat8),mode:Or,chunk_hashes_list:e.Vec(Ct),target_canister:f,store_canister:e.Opt(f),sender_canister_version:e.Opt(e.Nat64)}),Fn=e.Vec(e.Nat8),Vn=e.Record({arg:e.Vec(e.Nat8),wasm_module:Fn,mode:Or,canister_id:f,sender_canister_version:e.Opt(e.Nat64)}),Hn=e.Record({start_at_timestamp_nanos:e.Nat64,subnet_id:e.Principal}),Un=e.Record({num_block_failures_total:e.Nat64,node_id:e.Principal,num_blocks_proposed_total:e.Nat64}),$n=e.Vec(e.Record({timestamp_nanos:e.Nat64,node_metrics:e.Vec(Un)})),Kn=e.Record({settings:e.Opt(Mt),specified_id:e.Opt(f),amount:e.Opt(e.Nat),sender_canister_version:e.Opt(e.Nat64)}),Wn=e.Record({canister_id:f}),Gn=e.Record({canister_id:f,amount:e.Nat}),zn=e.Vec(e.Nat8),Qn=e.Record({key_id:e.Record({name:e.Text,curve:mr}),derivation_path:e.Vec(e.Vec(e.Nat8)),message_hash:e.Vec(e.Nat8)}),Yn=e.Record({signature:e.Vec(e.Nat8)}),Jn=e.Record({canister_id:f}),Xn=e.Record({canister_id:f}),Zn=e.Record({canister_id:f}),In=e.Vec(Ct),Dn=e.Record({canister_id:f,sender_canister_version:e.Opt(e.Nat64)}),Ln=e.Record({canister_id:e.Principal,settings:Mt,sender_canister_version:e.Opt(e.Nat64)}),ei=e.Record({chunk:e.Vec(e.Nat8),canister_id:e.Principal}),ti=Ct;return e.Service({bitcoin_get_balance:e.Func([n],[s],[]),bitcoin_get_current_fee_percentiles:e.Func([a],[c],[]),bitcoin_get_utxos:e.Func([l],[p],[]),bitcoin_send_transaction:e.Func([o],[],[]),canister_info:e.Func([V],[de],[]),canister_status:e.Func([be],[Tn],[]),clear_chunk_store:e.Func([An],[],[]),create_canister:e.Func([Pn],[Rn],[]),delete_canister:e.Func([Sn],[],[]),deposit_cycles:e.Func([qn],[],[]),ecdsa_public_key:e.Func([xn],[jn],[]),fetch_canister_logs:e.Func([Nn],[kn],["query"]),http_request:e.Func([Cn],[kt],[]),install_chunked_code:e.Func([Bn],[],[]),install_code:e.Func([Vn],[],[]),node_metrics_history:e.Func([Hn],[$n],[]),provisional_create_canister_with_cycles:e.Func([Kn],[Wn],[]),provisional_top_up_canister:e.Func([Gn],[],[]),raw_rand:e.Func([],[zn],[]),sign_with_ecdsa:e.Func([Qn],[Yn],[]),start_canister:e.Func([Jn],[],[]),stop_canister:e.Func([Xn],[],[]),stored_chunks:e.Func([Zn],[In],[]),uninstall_code:e.Func([Dn],[],[]),update_settings:e.Func([Ln],[],[]),upload_chunk:e.Func([ei],[ti],[])})}});var jt=g(A=>{"use strict";var Ds=A&&A.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(A,"__esModule",{value:!0});A.getManagementCanister=A.ACTOR_METHOD_WITH_HTTP_DETAILS=A.Actor=A.UpdateCallRejectedError=A.QueryCallRejectedError=A.ActorCallError=void 0;var Ls=E("buffer/"),_r=At(),pr=me(),Rt=E("@dfinity/candid"),yn=fr(),L=E("@dfinity/principal"),ea=H(),ta=Ds(pn()),Qe=class extends pr.AgentError{constructor(t,r,n,i){super(["Call failed:",`  Canister: ${t.toText()}`,`  Method: ${r} (${n})`,...Object.getOwnPropertyNames(i).map(s=>`  "${s}": ${JSON.stringify(i[s])}`)].join(`
`)),this.canisterId=t,this.methodName=r,this.type=n,this.props=i}};A.ActorCallError=Qe;var St=class extends Qe{constructor(t,r,n){var i;super(t,r,"query",{Status:n.status,Code:(i=_r.ReplicaRejectCode[n.reject_code])!==null&&i!==void 0?i:`Unknown Code "${n.reject_code}"`,Message:n.reject_message}),this.result=n}};A.QueryCallRejectedError=St;var qt=class extends Qe{constructor(t,r,n,i){super(t,r,"update",Object.assign({"Request ID":(0,ea.toHex)(n)},i.body?Object.assign(Object.assign({},i.body.error_code?{"Error code":i.body.error_code}:{}),{"Reject code":String(i.body.reject_code),"Reject message":i.body.reject_message}):{"HTTP status code":i.status.toString(),"HTTP status text":i.statusText})),this.requestId=n,this.response=i}};A.UpdateCallRejectedError=qt;var W=Symbol.for("ic-agent-metadata"),xt=class e{constructor(t){this[W]=Object.freeze(t)}static agentOf(t){return t[W].config.agent}static interfaceOf(t){return t[W].service}static canisterIdOf(t){return L.Principal.from(t[W].config.canisterId)}static async install(t,r){let n=t.mode===void 0?{install:null}:t.mode,i=t.arg?[...new Uint8Array(t.arg)]:[],s=[...new Uint8Array(t.module)],a=typeof r.canisterId=="string"?L.Principal.fromText(r.canisterId):r.canisterId;await yr(r).install_code({mode:n,arg:i,wasm_module:s,canister_id:a,sender_canister_version:[]})}static async createCanister(t,r){function n(s){return[{controllers:s.controllers?[s.controllers]:[],compute_allocation:s.compute_allocation?[s.compute_allocation]:[],freezing_threshold:s.freezing_threshold?[s.freezing_threshold]:[],memory_allocation:s.memory_allocation?[s.memory_allocation]:[],reserved_cycles_limit:[],log_visibility:[],wasm_memory_limit:[]}]}let{canister_id:i}=await yr(t||{}).provisional_create_canister_with_cycles({amount:[],settings:n(r||{}),specified_id:[],sender_canister_version:[]});return i}static async createAndInstallCanister(t,r,n){let i=await this.createCanister(n);return await this.install(Object.assign({},r),Object.assign(Object.assign({},n),{canisterId:i})),this.createActor(t,Object.assign(Object.assign({},n),{canisterId:i}))}static createActorClass(t,r){let n=t({IDL:Rt.IDL});class i extends e{constructor(a){if(!a.canisterId)throw new pr.AgentError(`Canister ID is required, but received ${typeof a.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`);let d=typeof a.canisterId=="string"?L.Principal.fromText(a.canisterId):a.canisterId;super({config:Object.assign(Object.assign(Object.assign({},gn),a),{canisterId:d}),service:n});for(let[c,l]of n._fields)r?.httpDetails&&l.annotations.push(A.ACTOR_METHOD_WITH_HTTP_DETAILS),this[c]=ra(this,c,l,a.blsVerify)}}return i}static createActor(t,r){if(!r.canisterId)throw new pr.AgentError(`Canister ID is required, but received ${typeof r.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`);return new(this.createActorClass(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}};A.Actor=xt;function Pt(e,t){let r=Rt.IDL.decode(e,Ls.Buffer.from(t));switch(r.length){case 0:return;case 1:return r[0];default:return r}}var gn={pollingStrategyFactory:yn.strategy.defaultStrategy};A.ACTOR_METHOD_WITH_HTTP_DETAILS="http-details";function ra(e,t,r,n){let i;r.annotations.includes("query")||r.annotations.includes("composite_query")?i=async(a,...d)=>{var c,l;a=Object.assign(Object.assign({},a),(l=(c=e[W].config).queryTransform)===null||l===void 0?void 0:l.call(c,t,d,Object.assign(Object.assign({},e[W].config),a)));let u=a.agent||e[W].config.agent||(0,_r.getDefaultAgent)(),h=L.Principal.from(a.canisterId||e[W].config.canisterId),v=Rt.IDL.encode(r.argTypes,d),p=await u.query(h,{methodName:t,arg:v,effectiveCanisterId:a.effectiveCanisterId});switch(p.status){case"rejected":throw new St(h,t,p);case"replied":return r.annotations.includes(A.ACTOR_METHOD_WITH_HTTP_DETAILS)?{httpDetails:p.httpDetails,result:Pt(r.retTypes,p.reply.arg)}:Pt(r.retTypes,p.reply.arg)}}:i=async(a,...d)=>{var c,l;a=Object.assign(Object.assign({},a),(l=(c=e[W].config).callTransform)===null||l===void 0?void 0:l.call(c,t,d,Object.assign(Object.assign({},e[W].config),a)));let u=a.agent||e[W].config.agent||(0,_r.getDefaultAgent)(),{canisterId:h,effectiveCanisterId:v,pollingStrategyFactory:p}=Object.assign(Object.assign(Object.assign({},gn),e[W].config),a),o=L.Principal.from(h),f=v!==void 0?L.Principal.from(v):o,V=Rt.IDL.encode(r.argTypes,d),{requestId:M,response:Q}=await u.call(o,{methodName:t,arg:V,effectiveCanisterId:f});if(!Q.ok||Q.body)throw new qt(o,t,M,Q);let le=p(),de=await(0,yn.pollForResponse)(u,f,M,le,n),be=r.annotations.includes(A.ACTOR_METHOD_WITH_HTTP_DETAILS);if(de!==void 0)return be?{httpDetails:Q,result:Pt(r.retTypes,de)}:Pt(r.retTypes,de);if(r.retTypes.length===0)return be?{httpDetails:Q,result:void 0}:void 0;throw new Error(`Call was returned undefined, but type [${r.retTypes.join(",")}].`)};let s=(...a)=>i({},...a);return s.withOptions=a=>(...d)=>i(a,...d),s}function yr(e){function t(r,n){if(e.effectiveCanisterId)return{effectiveCanisterId:L.Principal.from(e.effectiveCanisterId)};let i=n[0],s=L.Principal.fromHex("");return i&&typeof i=="object"&&i.canister_id&&(s=L.Principal.from(i.canister_id)),{effectiveCanisterId:s}}return xt.createActor(ta.default,Object.assign(Object.assign(Object.assign({},e),{canisterId:L.Principal.fromHex("")}),{callTransform:t,queryTransform:t}))}A.getManagementCanister=yr});var wn=g(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.default=({IDL:e})=>e.Service({retrieve:e.Func([e.Text],[e.Vec(e.Nat8)],["query"]),store:e.Func([e.Text,e.Vec(e.Nat8)],[],[])})});var bn=g(qe=>{"use strict";var na=qe&&qe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(qe,"__esModule",{value:!0});qe.createAssetCanisterActor=void 0;var ia=jt(),sa=na(wn());function aa(e){return ia.Actor.createActor(sa.default,e)}qe.createAssetCanisterActor=aa});var mn=g(ee=>{"use strict";var oa=ee&&ee.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),ca=ee&&ee.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ua=ee&&ee.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&oa(t,e,r);return ca(t,e),t};Object.defineProperty(ee,"__esModule",{value:!0});ee.fetchCandid=void 0;var la=E("@dfinity/principal"),da=ua(Ke()),fa=cr(),ha=jt();async function _a(e,t){t||(t=new fa.HttpAgent,t.isLocal()&&t.fetchRootKey());let n=(await da.request({agent:t,canisterId:la.Principal.fromText(e),paths:["candid"]})).get("candid");if(n)return n;let i=({IDL:a})=>a.Service({__get_candid_interface_tmp_hack:a.Func([],[a.Text],["query"])});return await ha.Actor.createActor(i,{agent:t,canisterId:e}).__get_candid_interface_tmp_hack()}ee.fetchCandid=_a});var On=g(w=>{"use strict";var vn=w&&w.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),pa=w&&w.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),F=w&&w.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&vn(t,e,r)},wr=w&&w.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&vn(t,e,r);return pa(t,e),t};Object.defineProperty(w,"__esModule",{value:!0});w.Cbor=w.CanisterStatus=w.polling=void 0;F(jt(),w);F(At(),w);F(et(),w);F(Ce(),w);F(Ut(),w);F(bn(),w);F($e(),w);F(rr(),w);F(mn(),w);F(nr(),w);F(Me(),w);F(Xt(),w);F(H(),w);F(zt(),w);w.polling=wr(fr());w.CanisterStatus=wr(Ke());w.Cbor=wr(ke())});var Nt=ci(On()),{__esModule:Ya,Cbor:Ja,CanisterStatus:Xa,polling:Za,randomNumber:Ia,bufFromBufLike:Da,uint8ToBuf:La,bufEquals:eo,compare:to,fromHex:ro,toHex:no,concat:io,blsVerify:so,verify:ao,hashOfMap:oo,requestIdOf:co,hashValue:uo,hash:lo,Ed25519PublicKey:fo,fetchCandid:ho,unwrapDER:_o,wrapDER:po,SECP256K1_OID:yo,ED25519_OID:go,DER_COSE_OID:wo,decodeLen:bo,decodeLenBytes:mo,encodeLen:vo,encodeLenBytes:Oo,check_canister_ranges:Eo,find_label:To,flatten_forks:Ao,lookup_path:Po,LookupStatus:Ro,reconstruct:So,lookupResultToBuffer:qo,Certificate:xo,hashTreeToString:jo,NodeType:No,CertificateVerificationError:Mo,createAssetCanisterActor:ko,createIdentityDescriptor:Co,AnonymousIdentity:Bo,SignIdentity:Fo,makeNonce:Vo,SubmitRequestType:Ho,httpHeadersTransform:Uo,makeExpiryTransform:$o,makeNonceTransform:Ko,Expiry:Wo,getDefaultAgent:Go,ProxyAgent:zo,ProxyStubAgent:Qo,ProxyMessageKind:Yo,AgentHTTPResponseError:Jo,HttpAgent:Xo,IdentityInvalidError:Zo,MANAGEMENT_CANISTER_ID:Io,IC_ROOT_KEY:Do,RequestStatusResponseStatus:Lo,ReplicaRejectCode:ec,getManagementCanister:tc,ACTOR_METHOD_WITH_HTTP_DETAILS:rc,Actor:nc,UpdateCallRejectedError:ic,QueryCallRejectedError:sc,ActorCallError:ac}=Nt,oc=Nt.default??Nt;export{rc as ACTOR_METHOD_WITH_HTTP_DETAILS,nc as Actor,ac as ActorCallError,Jo as AgentHTTPResponseError,Bo as AnonymousIdentity,Xa as CanisterStatus,Ja as Cbor,xo as Certificate,Mo as CertificateVerificationError,wo as DER_COSE_OID,go as ED25519_OID,fo as Ed25519PublicKey,Wo as Expiry,Xo as HttpAgent,Do as IC_ROOT_KEY,Zo as IdentityInvalidError,Ro as LookupStatus,Io as MANAGEMENT_CANISTER_ID,No as NodeType,zo as ProxyAgent,Yo as ProxyMessageKind,Qo as ProxyStubAgent,sc as QueryCallRejectedError,ec as ReplicaRejectCode,Lo as RequestStatusResponseStatus,yo as SECP256K1_OID,Fo as SignIdentity,Ho as SubmitRequestType,ic as UpdateCallRejectedError,Ya as __esModule,so as blsVerify,eo as bufEquals,Da as bufFromBufLike,Eo as check_canister_ranges,to as compare,io as concat,ko as createAssetCanisterActor,Co as createIdentityDescriptor,bo as decodeLen,mo as decodeLenBytes,oc as default,vo as encodeLen,Oo as encodeLenBytes,ho as fetchCandid,To as find_label,Ao as flatten_forks,ro as fromHex,Go as getDefaultAgent,tc as getManagementCanister,lo as hash,oo as hashOfMap,jo as hashTreeToString,uo as hashValue,Uo as httpHeadersTransform,qo as lookupResultToBuffer,Po as lookup_path,$o as makeExpiryTransform,Vo as makeNonce,Ko as makeNonceTransform,Za as polling,Ia as randomNumber,So as reconstruct,co as requestIdOf,no as toHex,La as uint8ToBuf,_o as unwrapDER,ao as verify,po as wrapDER};
//# sourceMappingURL=agent.mjs.map