@ic-pay/icpay-widget 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,7 +51,7 @@ ${e(i)}
51
51
  Request ID: ${zt(t)}
52
52
  `)}throw new Error("unreachable")}var PA=ye(()=>{"use strict";Dw();q0();bo();MA();MA();MA()});var fk,pk=ye(()=>{"use strict";fk=({IDL:r})=>{let e=r.Variant({mainnet:r.Null,testnet:r.Null}),t=r.Text,n=r.Record({network:e,address:t,min_confirmations:r.Opt(r.Nat32)}),i=r.Nat64,s=i,o=r.Nat32,a=r.Record({start_height:o,end_height:r.Opt(o),network:e}),c=r.Vec(r.Nat8),l=r.Record({tip_height:o,block_headers:r.Vec(c)}),u=r.Record({network:e}),h=r.Nat64,p=r.Vec(h),w=r.Record({network:e,filter:r.Opt(r.Variant({page:r.Vec(r.Nat8),min_confirmations:r.Nat32})),address:t}),y=r.Vec(r.Nat8),v=r.Record({txid:r.Vec(r.Nat8),vout:r.Nat32}),C=r.Record({height:r.Nat32,value:i,outpoint:v}),N=r.Record({next_page:r.Opt(r.Vec(r.Nat8)),tip_height:o,tip_block_hash:y,utxos:r.Vec(C)}),O=r.Record({transaction:r.Vec(r.Nat8),network:e}),L=r.Principal,j=r.Record({canister_id:L,num_requested_changes:r.Opt(r.Nat64)}),q=r.Variant({from_user:r.Record({user_id:r.Principal}),from_canister:r.Record({canister_version:r.Opt(r.Nat64),canister_id:r.Principal})}),D=r.Vec(r.Nat8),F=r.Variant({creation:r.Record({controllers:r.Vec(r.Principal)}),code_deployment:r.Record({mode:r.Variant({reinstall:r.Null,upgrade:r.Null,install:r.Null}),module_hash:r.Vec(r.Nat8)}),load_snapshot:r.Record({canister_version:r.Nat64,taken_at_timestamp:r.Nat64,snapshot_id:D}),controllers_change:r.Record({controllers:r.Vec(r.Principal)}),code_uninstall:r.Null}),P=r.Record({timestamp_nanos:r.Nat64,canister_version:r.Nat64,origin:q,details:F}),S=r.Record({controllers:r.Vec(r.Principal),module_hash:r.Opt(r.Vec(r.Nat8)),recent_changes:r.Vec(P),total_num_changes:r.Nat64}),z=r.Record({canister_id:L}),B=r.Variant({controllers:r.Null,public:r.Null,allowed_viewers:r.Vec(r.Principal)}),g=r.Record({freezing_threshold:r.Nat,controllers:r.Vec(r.Principal),reserved_cycles_limit:r.Nat,log_visibility:B,wasm_memory_limit:r.Nat,memory_allocation:r.Nat,compute_allocation:r.Nat}),m=r.Record({status:r.Variant({stopped:r.Null,stopping:r.Null,running:r.Null}),memory_size:r.Nat,cycles:r.Nat,settings:g,query_stats:r.Record({response_payload_bytes_total:r.Nat,num_instructions_total:r.Nat,num_calls_total:r.Nat,request_payload_bytes_total:r.Nat}),idle_cycles_burned_per_day:r.Nat,module_hash:r.Opt(r.Vec(r.Nat8)),reserved_cycles:r.Nat}),d=r.Record({canister_id:L}),f=r.Record({freezing_threshold:r.Opt(r.Nat),controllers:r.Opt(r.Vec(r.Principal)),reserved_cycles_limit:r.Opt(r.Nat),log_visibility:r.Opt(B),wasm_memory_limit:r.Opt(r.Nat),memory_allocation:r.Opt(r.Nat),compute_allocation:r.Opt(r.Nat)}),b=r.Record({settings:r.Opt(f),sender_canister_version:r.Opt(r.Nat64)}),_=r.Record({canister_id:L}),T=r.Record({canister_id:L}),I=r.Record({canister_id:L,snapshot_id:D}),A=r.Record({canister_id:L}),U=r.Variant({secp256k1:r.Null}),M=r.Record({key_id:r.Record({name:r.Text,curve:U}),canister_id:r.Opt(L),derivation_path:r.Vec(r.Vec(r.Nat8))}),R=r.Record({public_key:r.Vec(r.Nat8),chain_code:r.Vec(r.Nat8)}),H=r.Record({canister_id:L}),V=r.Record({idx:r.Nat64,timestamp_nanos:r.Nat64,content:r.Vec(r.Nat8)}),G=r.Record({canister_log_records:r.Vec(V)}),X=r.Record({value:r.Text,name:r.Text}),se=r.Record({status:r.Nat,body:r.Vec(r.Nat8),headers:r.Vec(X)}),W=r.Record({url:r.Text,method:r.Variant({get:r.Null,head:r.Null,post:r.Null}),max_response_bytes:r.Opt(r.Nat64),body:r.Opt(r.Vec(r.Nat8)),transform:r.Opt(r.Record({function:r.Func([r.Record({context:r.Vec(r.Nat8),response:se})],[se],["query"]),context:r.Vec(r.Nat8)})),headers:r.Vec(X)}),Q=r.Variant({reinstall:r.Null,upgrade:r.Opt(r.Record({wasm_memory_persistence:r.Opt(r.Variant({keep:r.Null,replace:r.Null})),skip_pre_upgrade:r.Opt(r.Bool)})),install:r.Null}),Y=r.Record({hash:r.Vec(r.Nat8)}),ne=r.Record({arg:r.Vec(r.Nat8),wasm_module_hash:r.Vec(r.Nat8),mode:Q,chunk_hashes_list:r.Vec(Y),target_canister:L,store_canister:r.Opt(L),sender_canister_version:r.Opt(r.Nat64)}),J=r.Vec(r.Nat8),re=r.Record({arg:r.Vec(r.Nat8),wasm_module:J,mode:Q,canister_id:L,sender_canister_version:r.Opt(r.Nat64)}),oe=r.Record({canister_id:L}),ie=r.Record({id:D,total_size:r.Nat64,taken_at_timestamp:r.Nat64}),le=r.Vec(ie),de=r.Record({canister_id:L,sender_canister_version:r.Opt(r.Nat64),snapshot_id:D}),fe=r.Record({start_at_timestamp_nanos:r.Nat64,subnet_id:r.Principal}),Ee=r.Record({num_block_failures_total:r.Nat64,node_id:r.Principal,num_blocks_proposed_total:r.Nat64}),xe=r.Vec(r.Record({timestamp_nanos:r.Nat64,node_metrics:r.Vec(Ee)})),_e=r.Record({settings:r.Opt(f),specified_id:r.Opt(L),amount:r.Opt(r.Nat),sender_canister_version:r.Opt(r.Nat64)}),Qe=r.Record({canister_id:L}),De=r.Record({canister_id:L,amount:r.Nat}),Ye=r.Vec(r.Nat8),Ze=r.Variant({ed25519:r.Null,bip340secp256k1:r.Null}),E=r.Record({key_id:r.Record({algorithm:Ze,name:r.Text}),canister_id:r.Opt(L),derivation_path:r.Vec(r.Vec(r.Nat8))}),x=r.Record({public_key:r.Vec(r.Nat8),chain_code:r.Vec(r.Nat8)}),k=r.Record({key_id:r.Record({name:r.Text,curve:U}),derivation_path:r.Vec(r.Vec(r.Nat8)),message_hash:r.Vec(r.Nat8)}),$=r.Record({signature:r.Vec(r.Nat8)}),K=r.Variant({bip341:r.Record({merkle_root_hash:r.Vec(r.Nat8)})}),Z=r.Record({aux:r.Opt(K),key_id:r.Record({algorithm:Ze,name:r.Text}),derivation_path:r.Vec(r.Vec(r.Nat8)),message:r.Vec(r.Nat8)}),ee=r.Record({signature:r.Vec(r.Nat8)}),Ne=r.Record({canister_id:L}),ke=r.Record({canister_id:L}),Ie=r.Record({canister_id:L}),We=r.Vec(Y),Ge=r.Record({subnet_id:r.Principal}),Xe=r.Record({replica_version:r.Text}),pr=r.Record({replace_snapshot:r.Opt(D),canister_id:L}),Er=ie,St=r.Record({canister_id:L,sender_canister_version:r.Opt(r.Nat64)}),fr=r.Record({canister_id:r.Principal,settings:f,sender_canister_version:r.Opt(r.Nat64)}),nr=r.Record({chunk:r.Vec(r.Nat8),canister_id:r.Principal}),wt=Y;return r.Service({bitcoin_get_balance:r.Func([n],[s],[]),bitcoin_get_block_headers:r.Func([a],[l],[]),bitcoin_get_current_fee_percentiles:r.Func([u],[p],[]),bitcoin_get_utxos:r.Func([w],[N],[]),bitcoin_send_transaction:r.Func([O],[],[]),canister_info:r.Func([j],[S],[]),canister_status:r.Func([z],[m],[]),clear_chunk_store:r.Func([d],[],[]),create_canister:r.Func([b],[_],[]),delete_canister:r.Func([T],[],[]),delete_canister_snapshot:r.Func([I],[],[]),deposit_cycles:r.Func([A],[],[]),ecdsa_public_key:r.Func([M],[R],[]),fetch_canister_logs:r.Func([H],[G],["query"]),http_request:r.Func([W],[se],[]),install_chunked_code:r.Func([ne],[],[]),install_code:r.Func([re],[],[]),list_canister_snapshots:r.Func([oe],[le],[]),load_canister_snapshot:r.Func([de],[],[]),node_metrics_history:r.Func([fe],[xe],[]),provisional_create_canister_with_cycles:r.Func([_e],[Qe],[]),provisional_top_up_canister:r.Func([De],[],[]),raw_rand:r.Func([],[Ye],[]),schnorr_public_key:r.Func([E],[x],[]),sign_with_ecdsa:r.Func([k],[$],[]),sign_with_schnorr:r.Func([Z],[ee],[]),start_canister:r.Func([Ne],[],[]),stop_canister:r.Func([ke],[],[]),stored_chunks:r.Func([Ie],[We],[]),subnet_info:r.Func([Ge],[Xe],[]),take_canister_snapshot:r.Func([pr],[Er],[]),uninstall_code:r.Func([St],[],[]),update_settings:r.Func([fr],[],[]),upload_chunk:r.Func([nr],[wt],[])})}});function J0(r,e){let t=Oh.decode(r,gk.Buffer.from(e));switch(t.length){case 0:return;case 1:return t[0];default:return t}}function Lne(r,e,t,n){let i;t.annotations.includes("query")||t.annotations.includes("composite_query")?i=async(o,...a)=>{var c,l;o=Object.assign(Object.assign({},o),(l=(c=r[Ia].config).queryTransform)===null||l===void 0?void 0:l.call(c,e,a,Object.assign(Object.assign({},r[Ia].config),o)));let u=o.agent||r[Ia].config.agent||OA(),h=Ve.from(o.canisterId||r[Ia].config.canisterId),p=Oh.encode(t.argTypes,a),w=await u.query(h,{methodName:e,arg:p,effectiveCanisterId:o.effectiveCanisterId}),y=Object.assign(Object.assign({},w.httpDetails),{requestDetails:w.requestDetails});switch(w.status){case"rejected":throw new BA(h,e,w);case"replied":return t.annotations.includes(RA)?{httpDetails:y,result:J0(t.retTypes,w.reply.arg)}:J0(t.retTypes,w.reply.arg)}}:i=async(o,...a)=>{var c,l;o=Object.assign(Object.assign({},o),(l=(c=r[Ia].config).callTransform)===null||l===void 0?void 0:l.call(c,e,a,Object.assign(Object.assign({},r[Ia].config),o)));let u=o.agent||r[Ia].config.agent||OA(),{canisterId:h,effectiveCanisterId:p,pollingStrategyFactory:w}=Object.assign(Object.assign(Object.assign({},mk),r[Ia].config),o),y=Ve.from(h),v=p!==void 0?Ve.from(p):y,C=Oh.encode(t.argTypes,a),{requestId:N,response:O,requestDetails:L}=await u.call(y,{methodName:e,arg:C,effectiveCanisterId:v}),j,q;if(O.body&&O.body.certificate){if(u.rootKey==null)throw new Error("Agent is missing root key");let S=O.body.certificate;q=await Ca.create({certificate:nl(S),rootKey:u.rootKey,canisterId:Ve.from(h),blsVerify:n});let z=[new TextEncoder().encode("request_status"),N];switch(new TextDecoder().decode(Ni(q.lookup([...z,"status"])))){case"replied":j=Ni(q.lookup([...z,"reply"]));break;case"rejected":{let g=new Uint8Array(Ni(q.lookup([...z,"reject_code"])))[0],m=new TextDecoder().decode(Ni(q.lookup([...z,"reject_message"]))),d=Ni(q.lookup([...z,"error_code"])),f=d?new TextDecoder().decode(d):void 0;throw new Jw(y,e,N,O,g,m,f)}}}else if(O.body&&"reject_message"in O.body){let{reject_code:S,reject_message:z,error_code:B}=O.body;throw new Jw(y,e,N,O,S,z,B)}if(O.status===202){let S=w(),z=await Zw(u,v,N,S,n);q=z.certificate,j=z.reply}let D=t.annotations.includes(RA),F=t.annotations.includes(g9),P=Object.assign(Object.assign({},O),{requestDetails:L});if(j!==void 0)return D&&F?{httpDetails:P,certificate:q,result:J0(t.retTypes,j)}:F?{certificate:q,result:J0(t.retTypes,j)}:D?{httpDetails:P,result:J0(t.retTypes,j)}:J0(t.retTypes,j);if(t.retTypes.length===0)return D?{httpDetails:O,result:void 0}:void 0;throw new Error(`Call was returned undefined, but type [${t.retTypes.join(",")}].`)};let s=(...o)=>i({},...o);return s.withOptions=o=>(...a)=>i(o,...a),s}function f9(r){function e(t,n){if(r.effectiveCanisterId)return{effectiveCanisterId:Ve.from(r.effectiveCanisterId)};let i=n[0],s=Ve.fromHex("");return i&&typeof i=="object"&&i.target_canister&&t==="install_chunked_code"&&(s=Ve.from(i.target_canister)),i&&typeof i=="object"&&i.canister_id&&(s=Ve.from(i.canister_id)),{effectiveCanisterId:s}}return pi.createActor(fk,Object.assign(Object.assign(Object.assign({},r),{canisterId:Ve.fromHex("")}),{callTransform:e,queryTransform:e}))}var gk,Xw,BA,Jw,Ia,pi,mk,RA,g9,p9,kA=ye(()=>{"use strict";gk=lc(hP());Dw();I0();Mh();PA();Zi();bo();q0();pk();Xw=class extends Jr{constructor(e,t,n,i){super(["Call failed:",` Canister: ${e.toText()}`,` Method: ${t} (${n})`,...Object.getOwnPropertyNames(i).map(s=>` "${s}": ${JSON.stringify(i[s])}`)].join(`
53
53
  `)),this.canisterId=e,this.methodName=t,this.type=n,this.props=i}},BA=class extends Xw{constructor(e,t,n){var i;super(e,t,"query",{Status:n.status,Code:(i=A0[n.reject_code])!==null&&i!==void 0?i:`Unknown Code "${n.reject_code}"`,Message:n.reject_message}),this.result=n}},Jw=class extends Xw{constructor(e,t,n,i,s,o,a){super(e,t,"update",Object.assign({"Request ID":zt(n)},i.body?Object.assign(Object.assign({},a?{"Error code":a}:{}),{"Reject code":String(s),"Reject message":o}):{"HTTP status code":i.status.toString(),"HTTP status text":i.statusText})),this.requestId=n,this.response=i,this.reject_code=s,this.reject_message=o,this.error_code=a}},Ia=Symbol.for("ic-agent-metadata"),pi=class r{constructor(e){this[Ia]=Object.freeze(e)}static agentOf(e){return e[Ia].config.agent}static interfaceOf(e){return e[Ia].service}static canisterIdOf(e){return Ve.from(e[Ia].config.canisterId)}static async install(e,t){let n=e.mode===void 0?{install:null}:e.mode,i=e.arg?[...new Uint8Array(e.arg)]:[],s=[...new Uint8Array(e.module)],o=typeof t.canisterId=="string"?Ve.fromText(t.canisterId):t.canisterId;await f9(t).install_code({mode:n,arg:i,wasm_module:s,canister_id:o,sender_canister_version:[]})}static async createCanister(e,t){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 f9(e||{}).provisional_create_canister_with_cycles({amount:[],settings:n(t||{}),specified_id:[],sender_canister_version:[]});return i}static async createAndInstallCanister(e,t,n){let i=await this.createCanister(n);return await this.install(Object.assign({},t),Object.assign(Object.assign({},n),{canisterId:i})),this.createActor(e,Object.assign(Object.assign({},n),{canisterId:i}))}static createActorClass(e,t){let n=e({IDL:Oh});class i extends r{constructor(o){if(!o.canisterId)throw new Jr(`Canister ID is required, but received ${typeof o.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 a=typeof o.canisterId=="string"?Ve.fromText(o.canisterId):o.canisterId;super({config:Object.assign(Object.assign(Object.assign({},mk),o),{canisterId:a}),service:n});for(let[c,l]of n._fields)t?.httpDetails&&l.annotations.push(RA),t?.certificate&&l.annotations.push(g9),this[c]=Lne(this,c,l,o.blsVerify)}}return i}static createActor(e,t){if(!t.canisterId)throw new Jr(`Canister ID is required, but received ${typeof t.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(e))(t)}static createActorWithHttpDetails(e,t){return new(this.createActorClass(e,{httpDetails:!0}))(t)}static createActorWithExtendedDetails(e,t,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(e,n))(t)}};mk={pollingStrategyFactory:X0.defaultStrategy},RA="http-details",g9="certificate";p9=class extends pi{constructor(e){super(e)}}});var wk,yk=ye(()=>{"use strict";wk=({IDL:r})=>r.Service({retrieve:r.Func([r.Text],[r.Vec(r.Nat8)],["query"]),store:r.Func([r.Text,r.Vec(r.Nat8)],[],[])})});function jne(r){return pi.createActor(wk,r)}var bk=ye(()=>{"use strict";kA();yk()});async function zne(r,e){e||(e=await Vn.create());let n=(await qw({agent:e,canisterId:Ve.fromText(r),paths:["candid"]})).get("candid");if(n)return n;let i=({IDL:o})=>o.Service({__get_candid_interface_tmp_hack:o.Func([],[o.Text],["query"])});return await pi.createActor(i,{agent:e,canisterId:r}).__get_candid_interface_tmp_hack()}var vk=ye(()=>{"use strict";Zi();Fw();l9();kA()});var Ak={};Re(Ak,{ACTOR_METHOD_WITH_CERTIFICATE:()=>g9,ACTOR_METHOD_WITH_HTTP_DETAILS:()=>RA,Actor:()=>pi,ActorCallError:()=>Xw,AdvancedActor:()=>p9,AgentCallError:()=>xw,AgentHTTPResponseError:()=>gf,AgentQueryError:()=>Sw,AgentReadStateError:()=>Cw,AnonymousIdentity:()=>Aa,CanisterStatus:()=>Hw,Cbor:()=>Bh,Certificate:()=>Ca,CertificateVerificationError:()=>Eo,DER_COSE_OID:()=>s9,ED25519_OID:()=>Dh,Ed25519PublicKey:()=>$0,Expiry:()=>wc,HttpAgent:()=>Vn,IC_ROOT_KEY:()=>TA,IdentityInvalidError:()=>Nf,LookupStatus:()=>tn,MANAGEMENT_CANISTER_ID:()=>QE,NodeType:()=>fi,Observable:()=>yA,ObservableLog:()=>Vw,ProxyAgent:()=>h9,ProxyMessageKind:()=>gn,ProxyStubAgent:()=>u9,QueryCallRejectedError:()=>BA,ReplicaRejectCode:()=>A0,RequestStatusResponseStatus:()=>Ec,SECP256K1_OID:()=>Cne,SignIdentity:()=>al,SubmitRequestType:()=>df,UpdateCallRejectedError:()=>Jw,blsVerify:()=>WE,bufEquals:()=>rl,bufFromBufLike:()=>ba,check_canister_ranges:()=>dA,compare:()=>C0,concat:()=>Xi,createAssetCanisterActor:()=>jne,createIdentityDescriptor:()=>Vte,decodeLen:()=>rk,decodeLenBytes:()=>gA,defaultStrategy:()=>Z0,encodeLen:()=>i9,encodeLenBytes:()=>n9,fetchCandid:()=>zne,find_label:()=>jw,flatten_forks:()=>zw,fromHex:()=>Es,getDefaultAgent:()=>OA,getManagementCanister:()=>f9,hash:()=>Ko,hashOfMap:()=>P0,hashTreeToString:()=>hA,hashValue:()=>mw,httpHeadersTransform:()=>pf,lookupResultToBuffer:()=>Ni,lookup_path:()=>yu,makeExpiryTransform:()=>hre,makeNonce:()=>ff,makeNonceTransform:()=>Y2,pollForResponse:()=>Zw,polling:()=>d9,randomNumber:()=>B0,reconstruct:()=>Lw,requestIdOf:()=>pc,strategy:()=>X0,toHex:()=>zt,uint8ToBuf:()=>Ih,unwrapDER:()=>F0,verify:()=>Zre,wrapDER:()=>Af});var _a=ye(()=>{"use strict";kA();Dw();Z2();Ew();aE();bk();q0();o9();vk();c9();a9();ww();VE();bo();mE();PA();Fw();Aw();PA()});function Ek(r){return r!==null&&typeof r=="object"}var jA,qh,UA,LA,eg,tg,Tf,Na,xk=ye(()=>{"use strict";_a();_a();r9();jA=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},qh=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)};Tf=class r{constructor(e){if(UA.set(this,void 0),LA.set(this,void 0),e.byteLength!==r.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");jA(this,UA,ba(e),"f"),jA(this,LA,r.derEncode(e),"f")}static from(e){if(typeof e=="string"){let t=Es(e);return this.fromRaw(t)}else if(Ek(e)){let t=e;if(Ek(t)&&Object.hasOwnProperty.call(t,"__derEncodedPublicKey__"))return this.fromDer(t);if(ArrayBuffer.isView(t)){let n=t;return this.fromRaw(ba(n.buffer))}else{if(t instanceof ArrayBuffer)return this.fromRaw(t);if("rawKey"in t)return this.fromRaw(t.rawKey);if("derKey"in t)return this.fromDer(t.derKey);if("toDer"in t)return this.fromDer(t.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(e){return new r(e)}static fromDer(e){return new r(this.derDecode(e))}static derEncode(e){let t=Af(e,Dh).buffer;return t.__derEncodedPublicKey__=void 0,t}static derDecode(e){let t=F0(e,Dh);if(t.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return ba(t)}get rawKey(){return qh(this,UA,"f")}get derKey(){return qh(this,LA,"f")}toDer(){return this.derKey}toRaw(){return this.rawKey}};UA=new WeakMap,LA=new WeakMap;Tf.RAW_KEY_LENGTH=32;Na=class r extends al{constructor(e,t){super(),eg.set(this,void 0),tg.set(this,void 0),jA(this,eg,Tf.from(e),"f"),jA(this,tg,new Uint8Array(t),"f")}static generate(e){if(e&&e.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");e||(e=Xs.utils.randomPrivateKey()),rl(e,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let t=new Uint8Array(32);for(let i=0;i<32;i++)t[i]=new Uint8Array(e)[i];let n=Xs.getPublicKey(t);return r.fromKeyPair(n,t)}static fromParsedJson(e){let[t,n]=e;return new r(Tf.fromDer(Es(t)),Es(n))}static fromJSON(e){let t=JSON.parse(e);if(Array.isArray(t)){if(typeof t[0]=="string"&&typeof t[1]=="string")return this.fromParsedJson([t[0],t[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(e)}`)}static fromKeyPair(e,t){return new r(Tf.fromRaw(e),t)}static fromSecretKey(e){let t=Xs.getPublicKey(new Uint8Array(e));return r.fromKeyPair(t,e)}toJSON(){return[zt(qh(this,eg,"f").toDer()),zt(qh(this,tg,"f"))]}getKeyPair(){return{secretKey:qh(this,tg,"f"),publicKey:qh(this,eg,"f")}}getPublicKey(){return qh(this,eg,"f")}async sign(e){let t=new Uint8Array(e),n=Ih(Xs.sign(t,qh(this,tg,"f").slice(0,32)));return Object.defineProperty(n,"__signature__",{enumerable:!1,value:void 0}),n}static verify(e,t,n){let[i,s,o]=[e,t,n].map(a=>(typeof a=="string"&&(a=Es(a)),a instanceof Uint8Array&&(a=ba(a.buffer)),new Uint8Array(a)));return Xs.verify(i,s,o)}};eg=new WeakMap,tg=new WeakMap});function Sk(r){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(r)return r;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new m9("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var m9,Of,Ck=ye(()=>{"use strict";_a();m9=class r extends Error{constructor(e){super(e),this.message=e,Object.setPrototypeOf(this,r.prototype)}};Of=class r extends al{constructor(e,t,n){super(),this._keyPair=e,this._derKey=t,this._subtleCrypto=n}static async generate(e){let{extractable:t=!1,keyUsages:n=["sign","verify"],subtleCrypto:i}=e??{},s=Sk(i),o=await s.generateKey({name:"ECDSA",namedCurve:"P-256"},t,n),a=await s.exportKey("spki",o.publicKey);return new this(o,a,s)}static async fromKeyPair(e,t){let n=Sk(t),i=await n.exportKey("spki",e.publicKey);return new r(e,i,n)}getKeyPair(){return this._keyPair}getPublicKey(){let e=this._derKey,t=Object.create(this._keyPair.publicKey);return t.toDer=function(){return e},t}async sign(e){let t={name:"ECDSA",hash:{name:"SHA-256"}};return await this._subtleCrypto.sign(t,this._keyPair.privateKey,e)}}});var Dne,rg,Eu,zA,w9=ye(()=>{"use strict";Zi();Dne=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},rg=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},zA=class{constructor(e){Eu.set(this,void 0),Dne(this,Eu,e,"f")}get rawKey(){return rg(this,Eu,"f").rawKey}get derKey(){return rg(this,Eu,"f").derKey}toDer(){return rg(this,Eu,"f").toDer()}getPublicKey(){return rg(this,Eu,"f")}getPrincipal(){if(!rg(this,Eu,"f").rawKey)throw new Error("Cannot get principal from a public key without a raw key.");return Ve.fromUint8Array(new Uint8Array(rg(this,Eu,"f").rawKey))}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}};Eu=new WeakMap});function y9(r){if(typeof r!="string"||r.length<64)throw new Error("Invalid public key.");return Es(r)}async function Vne(r,e,t,n){let i=new xu(e.toDer(),BigInt(+t)*BigInt(1e6),n),s=new Uint8Array([...$ne,...new Uint8Array(pc(Object.assign({},i)))]),o=await r.sign(nl(s));return{delegation:i,signature:o}}function Ik(r,e){for(let{delegation:i}of r.delegations)if(+new Date(Number(i.expiration/BigInt(1e6)))<=+Date.now())return!1;let t=[],n=e?.scope;n&&(Array.isArray(n)?t.push(...n.map(i=>typeof i=="string"?Ve.fromText(i):i)):t.push(typeof n=="string"?Ve.fromText(n):n));for(let i of t){let s=i.toText();for(let{delegation:o}of r.delegations){if(o.targets===void 0)continue;let a=!0;for(let c of o.targets)if(c.toText()===s){a=!1;break}if(a)return!1}}return!0}var ng,qne,Hne,Fne,DA,$ne,Wne,xu,Su,xc,ey,_k=ye(()=>{"use strict";_a();Zi();ng=lc(bw());w9();Mh();qne=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Hne=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Fne=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},$ne=new TextEncoder().encode("ic-request-auth-delegation"),Wne=new TextEncoder().encode(`
54
- ic-request`);xu=class{constructor(e,t,n){this.pubkey=e,this.expiration=t,this.targets=n}toCBOR(){return ng.value.map(Object.assign({pubkey:ng.value.bytes(this.pubkey),expiration:ng.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:ng.value.array(this.targets.map(e=>ng.value.bytes(nl(e.toUint8Array()))))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:zt(this.pubkey)},this.targets&&{targets:this.targets.map(e=>e.toHex())})}};Su=class r{constructor(e,t){this.delegations=e,this.publicKey=t}static async create(e,t,n=new Date(Date.now()+900*1e3),i={}){var s,o;let a=await Vne(e,t,n,i.targets);return new r([...((s=i.previous)===null||s===void 0?void 0:s.delegations)||[],a],((o=i.previous)===null||o===void 0?void 0:o.publicKey)||e.getPublicKey().toDer())}static fromJSON(e){let{publicKey:t,delegations:n}=typeof e=="string"?JSON.parse(e):e;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(s=>{let{delegation:o,signature:a}=s,{pubkey:c,expiration:l,targets:u}=o;if(u!==void 0&&!Array.isArray(u))throw new Error("Invalid targets.");return{delegation:new xu(y9(c),BigInt("0x"+l),u&&u.map(h=>{if(typeof h!="string")throw new Error("Invalid target.");return Ve.fromHex(h)})),signature:y9(a)}});return new this(i,y9(t))}static fromDelegations(e,t){return new this(e,t)}toJSON(){return{delegations:this.delegations.map(e=>{let{delegation:t,signature:n}=e,{targets:i}=t;return{delegation:Object.assign({expiration:t.expiration.toString(16),pubkey:zt(t.pubkey)},i&&{targets:i.map(s=>s.toHex())}),signature:zt(n)}}),publicKey:zt(this.publicKey)}}},xc=class extends al{constructor(e,t){super(),this._inner=e,this._delegation=t}static fromDelegation(e,t){return new this(e,t)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(e){return this._inner.sign(e)}async transformRequest(e){let{body:t}=e,n=Fne(e,["body"]),i=await pc(t);return Object.assign(Object.assign({},n),{body:{content:t,sender_sig:await this.sign(nl(new Uint8Array([...Wne,...new Uint8Array(i)]))),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}},ey=class r extends zA{constructor(e,t){super(e),DA.set(this,void 0),qne(this,DA,t,"f")}get delegation(){return Hne(this,DA,"f")}static fromDelegation(e,t){return new r(e,t)}};DA=new WeakMap});var Kne,Nk,Tk=ye(()=>{"use strict";_a();Kne=lc(F2());Mh();(function(r){r[r.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Nk||(Nk={}))});var b9=ye(()=>{"use strict";xk();Ck();_k();w9();Tk();_a()});var Ok,ig,v9=ye(()=>{"use strict";Ok=["mousedown","mousemove","keydown","touchstart","wheel"],ig=class{constructor(e={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=e||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let s=this._resetTimer.bind(this);window.addEventListener("load",s,!0),Ok.forEach(function(a){document.addEventListener(a,s,!0)});let o=(a,c)=>{let l;return(...u)=>{let h=this,p=function(){l=void 0,a.apply(h,u)};clearTimeout(l),l=window.setTimeout(p,c)}};if(e?.captureScroll){let a=o(s,(t=e?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",a,!0)}s()}static create(e={}){return new this(e)}registerCallback(e){this.callbacks.push(e)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let e=this._resetTimer.bind(this);Ok.forEach(function(t){document.removeEventListener(t,e,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let e=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(e,this.idleTimeout)}}});function Gne(){return Mk||(Mk=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Yne(){return Pk||(Pk=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function Zne(r){let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("success",s),r.removeEventListener("error",o)},s=()=>{t(dl(r.result)),i()},o=()=>{n(r.error),i()};r.addEventListener("success",s),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Bk.set(t,r)}).catch(()=>{}),S9.set(e,r),e}function Xne(r){if(E9.has(r))return;let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("complete",s),r.removeEventListener("error",o),r.removeEventListener("abort",o)},s=()=>{t(),i()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),i()};r.addEventListener("complete",s),r.addEventListener("error",o),r.addEventListener("abort",o)});E9.set(r,e)}function kk(r){x9=r(x9)}function Jne(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(qA(this),e,...t);return Rk.set(n,e.sort?e.sort():[e]),dl(n)}:Yne().includes(r)?function(...e){return r.apply(qA(this),e),dl(Bk.get(this))}:function(...e){return dl(r.apply(qA(this),e))}}function eie(r){return typeof r=="function"?Jne(r):(r instanceof IDBTransaction&&Xne(r),Qne(r,Gne())?new Proxy(r,x9):r)}function dl(r){if(r instanceof IDBRequest)return Zne(r);if(A9.has(r))return A9.get(r);let e=eie(r);return e!==r&&(A9.set(r,e),S9.set(e,r)),e}var Qne,Mk,Pk,Bk,E9,Rk,A9,S9,x9,qA,C9=ye(()=>{"use strict";Qne=(r,e)=>e.some(t=>r instanceof t);Bk=new WeakMap,E9=new WeakMap,Rk=new WeakMap,A9=new WeakMap,S9=new WeakMap;x9={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return E9.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Rk.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return dl(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};qA=r=>S9.get(r)});function Lk(r,e,{blocked:t,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(r,e),a=dl(o);return n&&o.addEventListener("upgradeneeded",c=>{n(dl(o.result),c.oldVersion,c.newVersion,dl(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Uk(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(I9.get(e))return I9.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,i=rie.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(i||tie.includes(t)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),i&&c.done]))[0]};return I9.set(e,s),s}var tie,rie,I9,jk=ye(()=>{"use strict";C9();C9();tie=["get","getKey","getAll","getAllKeys","count"],rie=["put","add","delete","clear"],I9=new Map;kk(r=>({...r,get:(e,t,n)=>Uk(e,t)||r.get(e,t,n),has:(e,t)=>!!Uk(e,t)||r.has(e,t)}))});async function iie(r,e,t){return await r.get(e,t)}async function sie(r,e,t,n){return await r.put(e,n,t)}async function oie(r,e,t){return await r.delete(e,t)}var zk,Dk,nie,sg,_9=ye(()=>{"use strict";jk();FA();zk="auth-client-db",Dk="ic-keyval",nie=async(r=zk,e=Dk,t)=>(HA&&(localStorage!=null&&localStorage.getItem(Ta))&&(localStorage.removeItem(Ta),localStorage.removeItem(Oa)),await Lk(r,t,{upgrade:n=>{n.objectStoreNames.contains(e)&&n.clear(e),n.createObjectStore(e)}}));sg=class r{constructor(e,t){this._db=e,this._storeName=t}static async create(e){let{dbName:t=zk,storeName:n=Dk,version:i=qk}=e??{},s=await nie(t,n,i);return new r(s,n)}async set(e,t){return await sie(this._db,this._storeName,e,t)}async get(e){var t;return(t=await iie(this._db,this._storeName,e))!==null&&t!==void 0?t:null}async remove(e){return await oie(this._db,this._storeName,e)}}});var aie,cie,$A,Oa,Ta,Hk,qk,HA,og,ag,FA=ye(()=>{"use strict";_9();aie=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},cie=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Oa="identity",Ta="delegation",Hk="iv",qk=1,HA=typeof window<"u",og=class{constructor(e="ic-",t){this.prefix=e,this._localStorage=t}get(e){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+e))}set(e,t){return this._getLocalStorage().setItem(this.prefix+e,t),Promise.resolve()}remove(e){return this._getLocalStorage().removeItem(this.prefix+e),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let e=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!e)throw new Error("Could not find local storage.");return e}},ag=class{constructor(e){$A.set(this,void 0),aie(this,$A,e??{},"f")}get _db(){return new Promise(e=>{if(this.initializedDb){e(this.initializedDb);return}sg.create(cie(this,$A,"f")).then(t=>{this.initializedDb=t,e(t)})})}async get(e){return await(await this._db).get(e)}async set(e,t){await(await this._db).set(e,t)}async remove(e){await(await this._db).remove(e)}};$A=new WeakMap});var $k={};Re($k,{AuthClient:()=>ty,ERROR_USER_INTERRUPT:()=>Fk,IdbKeyVal:()=>sg,IdbStorage:()=>ag,IdleManager:()=>ig,KEY_STORAGE_DELEGATION:()=>Ta,KEY_STORAGE_KEY:()=>Oa,LocalStorage:()=>og});async function O9(r){await r.remove(Oa),await r.remove(Ta),await r.remove(Hk)}var lie,uie,N9,T9,hie,Fk,ty,M9=ye(()=>{"use strict";_a();b9();v9();FA();FA();_9();v9();lie="https://identity.internetcomputer.org",uie="#authorize",N9="ECDSA",T9="Ed25519",hie=500,Fk="UserInterrupt",ty=class{constructor(e,t,n,i,s,o,a,c){this._identity=e,this._key=t,this._chain=n,this._storage=i,this.idleManager=s,this._createOptions=o,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(e={}){var t,n,i;let s=(t=e.storage)!==null&&t!==void 0?t:new ag,o=(n=e.keyType)!==null&&n!==void 0?n:N9,a=null;if(e.identity)a=e.identity;else{let h=await s.get(Oa);if(!h&&HA)try{let p=new og,w=await p.get(Ta),y=await p.get(Oa);w&&y&&o===N9&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await s.set(Ta,w),await s.set(Oa,y),h=w,await p.remove(Ta),await p.remove(Oa))}catch(p){console.error("error while attempting to recover localstorage: "+p)}if(h)try{typeof h=="object"?o===T9&&typeof h=="string"?a=await Na.fromJSON(h):a=await Of.fromKeyPair(h):typeof h=="string"&&(a=Na.fromJSON(h))}catch{}}let c=new Aa,l=null;if(a)try{let h=await s.get(Ta);if(typeof h=="object"&&h!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");e.identity?c=e.identity:h&&(l=Su.fromJSON(h),Ik(l)?"toDer"in a?c=ey.fromDelegation(a,l):c=xc.fromDelegation(a,l):(await O9(s),a=null))}catch(h){console.error(h),await O9(s),a=null}let u;return!((i=e.idleOptions)===null||i===void 0)&&i.disableIdle?u=void 0:(l||e.identity)&&(u=ig.create(e.idleOptions)),a||(o===T9?(a=await Na.generate(),await s.set(Oa,JSON.stringify(a.toJSON()))):(e.storage&&o===N9&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${T9}' as the key type, as it can serialize to a string`),a=await Of.generate(),await s.set(Oa,a.getKeyPair()))),new this(c,a,l,s,u,e)}_registerDefaultIdleCallback(){var e,t;let n=(e=this._createOptions)===null||e===void 0?void 0:e.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(e,t){var n,i;let s=e.delegations.map(l=>({delegation:new xu(l.delegation.pubkey,l.delegation.expiration,l.delegation.targets),signature:l.signature.buffer})),o=Su.fromDelegations(s,e.userPublicKey.buffer),a=this._key;if(!a)return;this._chain=o,"toDer"in a?this._identity=ey.fromDelegation(a,this._chain):this._identity=xc.fromDelegation(a,this._chain),(n=this._idpWindow)===null||n===void 0||n.close();let c=(i=this._createOptions)===null||i===void 0?void 0:i.idleOptions;!this.idleManager&&!c?.disableIdle&&(this.idleManager=ig.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ta,JSON.stringify(this._chain.toJSON())),t?.(e)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(e){var t,n,i,s;let o=BigInt(8)*BigInt(36e11),a=new URL(((t=e?.identityProvider)===null||t===void 0?void 0:t.toString())||lie);a.hash=uie,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(a,Object.assign({maxTimeToLive:(i=e?.maxTimeToLive)!==null&&i!==void 0?i:o},e)),window.addEventListener("message",this._eventHandler),this._idpWindow=(s=window.open(a.toString(),"idpWindow",e?.windowOpenerFeatures))!==null&&s!==void 0?s:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Fk,e?.onError):setTimeout(c,hie))};c()}_getEventHandler(e,t){return async n=>{var i,s,o;if(n.origin!==e.origin)return;let a=n.data;switch(a.kind){case"authorize-ready":{let c=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((i=this._key)===null||i===void 0?void 0:i.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(s=t?.derivationOrigin)===null||s===void 0?void 0:s.toString()},t?.customValues);(o=this._idpWindow)===null||o===void 0||o.postMessage(c,e.origin);break}case"authorize-client-success":try{await this._handleSuccess(a,t?.onSuccess)}catch(c){this._handleFailure(c.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(a.text,t?.onError);break;default:break}}}_handleFailure(e,t){var n;(n=this._idpWindow)===null||n===void 0||n.close(),t?.(e),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(e={}){if(await O9(this._storage),this._identity=new Aa,this._chain=null,e.returnTo)try{window.history.pushState({},"",e.returnTo)}catch{window.location.href=e.returnTo}}}});var B9=$r(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.IcpayWallet=void 0;var die=(M9(),Yd($k)),Wk=(Zi(),Yd(k8)),Ma=ew(),P9=class{constructor(e){this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null,this.connectedWallet=null,this.providers=[{id:"internet-identity",name:"Internet Identity",icon:"\u{1F310}",description:"Official Internet Computer identity provider"},{id:"oisy",name:"OISY",icon:"\u{1F510}",description:"OISY wallet for Internet Computer"},{id:"plug",name:"Plug Wallet",icon:"\u{1F50C}",description:"Plug wallet extension"}],e?.connectedWallet&&(this.connectedWallet=e.connectedWallet)}getProviders(){return this.providers}isProviderAvailable(e){if(typeof window>"u")return!1;switch(e){case"internet-identity":return!0;case"oisy":return"oisy"in window;case"plug":return"ic"in window&&window.ic!==void 0&&"plug"in window.ic;default:return!1}}async connectToProvider(e){try{switch(e){case"internet-identity":return await this.connectInternetIdentity();case"oisy":return await this.connectOisy();case"plug":return await this.connectPlug();default:throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.UNSUPPORTED_PROVIDER,`Unsupported wallet provider: ${e}`)}}catch(t){throw t instanceof Error&&(t.message.includes("rejected")||t.message.includes("cancelled"))?(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,`Connection to ${e} was cancelled by user`):(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_CONNECTION_FAILED,`Failed to connect to ${e}`,t)}}async connectInternetIdentity(){return this.authClient=await die.AuthClient.create(),await this.authClient.isAuthenticated()?(this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity"):await new Promise((e,t)=>{this.authClient.login({identityProvider:"https://identity.ic0.app",onSuccess:()=>{this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity",e()},onError:n=>{t(new Error(`Authentication failed: ${n||"Unknown error"}`))}})}),{provider:"internet-identity",principal:this.principal.toText(),accountId:this.principal.toText(),connected:!0}}async connectOisy(){if(typeof window>"u"||!window.oisy)throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_PROVIDER_NOT_AVAILABLE,"OISY wallet is not available");try{let e=await window.oisy.requestConnect();if(e.connected)return this.principal=Wk.Principal.fromText(e.principal),this.connectedProvider="oisy",{provider:"oisy",principal:e.principal,accountId:e.principal,connected:!0};throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,"OISY connection was rejected by user")}catch(e){throw new Error(`OISY connection failed: ${e}`)}}async connectPlug(){if(typeof window>"u"||!window.ic?.plug)throw new Error("Plug wallet is not available");try{if(await window.ic.plug.requestConnect()){let t=await window.ic.plug.getPrincipal();return this.principal=Wk.Principal.fromText(t),this.connectedProvider="plug",{provider:"plug",principal:t,accountId:t,connected:!0}}else throw new Error("Plug connection was rejected")}catch(e){throw new Error(`Plug connection failed: ${e}`)}}async showConnectionModal(){let e=this.providers.filter(t=>this.isProviderAvailable(t.id));if(e.length===0)throw new Ma.IcpayError({code:"NO_PROVIDERS_AVAILABLE",message:"No wallet providers are available"});return await this.connectToProvider(e[0].id)}getAccountAddress(){if(!this.principal)throw new Ma.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet is not connected"});return this.principal.toText()}async disconnect(){this.authClient&&await this.authClient.logout(),this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null}isConnected(){return this.connectedWallet?this.connectedWallet.owner||this.connectedWallet.principal||typeof this.connectedWallet.getPrincipal=="function"?!0:"connected"in this.connectedWallet?!!this.connectedWallet.connected:this.connectedWallet!==null&&typeof this.connectedWallet=="object":this.identity!==null&&this.principal!==null}getIdentity(){return this.identity}getPrincipal(){return this.principal}getConnectedProvider(){return this.connectedProvider}};WA.IcpayWallet=P9});var Vk={};Re(Vk,{idlFactory:()=>fie,init:()=>pie});var fie,pie,Kk=ye(()=>{"use strict";fie=({IDL:r})=>{let e=r.Record({account_canister_id:r.Nat64,percentage:r.Nat16}),t=r.Record({account_canister_id:r.Nat64,platform_fee_percentage:r.Nat16,subaccount:r.Opt(r.Vec(r.Nat8)),wallet_address:r.Text,icp_account_identifier:r.Opt(r.Text),platform_fee_fixed:r.Opt(r.Nat),is_active:r.Bool,splits:r.Vec(e)}),n=r.Variant({Ok:r.Null,Err:r.Text}),i=r.Variant({Failed:r.Text,Processed:r.Null,Received:r.Null,Completed:r.Null,Pending:r.Null}),s=r.Record({account_canister_id:r.Nat64,index_block:r.Opt(r.Nat64),timestamp:r.Opt(r.Nat64),account_percentage:r.Nat16,amount:r.Nat}),o=r.Record({id:r.Nat,status:i,account_canister_id:r.Nat64,platform_fee_amount:r.Nat,transfer_fee:r.Nat,memo:r.Opt(r.Vec(r.Nat8)),timestamp_to_account:r.Opt(r.Nat64),notify_processing:r.Bool,source_type:r.Nat8,timestamp:r.Nat64,index_received:r.Opt(r.Nat64),sender_principal_id:r.Text,account_amount:r.Nat,ledger_canister_id:r.Text,splits:r.Vec(s),timestamp_received:r.Opt(r.Nat64),amount:r.Nat}),a=r.Record({transactions:r.Vec(o),total_count:r.Nat32,has_more:r.Bool}),c=r.Record({total_accounts:r.Nat32,cycles_balance:r.Nat64,controllers:r.Vec(r.Principal),is_healthy:r.Bool,last_update_timestamp:r.Nat64,active_accounts:r.Nat32,memory_size_bytes:r.Nat64,total_transactions:r.Nat32,platform_wallet:r.Text}),l=r.Record({id:r.Nat,fee:r.Nat,status:i,account_canister_id:r.Nat64,to_principal:r.Text,to_subaccount:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Vec(r.Nat8),icp_account_identifier:r.Opt(r.Text),notify_processing:r.Opt(r.Bool),timestamp_created:r.Nat64,index:r.Opt(r.Nat64),ledger_canister_id:r.Text,timestamp_completed:r.Opt(r.Nat64),amount:r.Nat,status_message:r.Opt(r.Text)}),u=r.Record({status:i,timestamp_platform_to_account:r.Opt(r.Nat64),account_canister_id:r.Nat64,original_tx_id:r.Nat,notify_processing:r.Bool,timestamp_created:r.Nat64,timestamp_to_sender:r.Opt(r.Nat64),ledger_canister_id:r.Text,amount:r.Nat,platform_refund_amount:r.Nat,index_to_sender:r.Opt(r.Nat64),index_platform_to_account:r.Opt(r.Nat64)}),h=r.Record({status:i,amount:r.Nat}),p=r.Record({from_timestamp:r.Opt(r.Nat64),status:r.Opt(i),account_canister_id:r.Opt(r.Nat64),from_id:r.Opt(r.Nat),offset:r.Opt(r.Nat32),limit:r.Opt(r.Nat32),to_timestamp:r.Opt(r.Nat64),ledger_canister_id:r.Opt(r.Text)}),w=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),y=r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}),v=r.Record({metadata:w,device_spec:r.Opt(y)}),C=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:v}),N=r.Record({lines:r.Vec(r.Text)}),O=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(N)}),GenericDisplayMessage:r.Text}),L=r.Record({metadata:w,consent_message:O}),j=r.Record({description:r.Text}),q=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat64}),InsufficientPayment:j,UnsupportedCanisterCall:j,ConsentMessageUnavailable:j}),D=r.Variant({Ok:L,Err:q}),F=r.Record({account_canister_id:r.Nat64,account:t}),P=r.Record({block_index:r.Nat64,ledger_canister_id:r.Text}),S=r.Record({id:r.Text,status:i,amount:r.Nat}),z=r.Variant({Ok:S,Err:r.Text}),B=r.Variant({Ok:l,Err:r.Text}),g=r.Variant({Ok:r.Nat,Err:r.Text});return r.Service({add_account:r.Func([r.Nat64,t],[n],[]),get_account:r.Func([r.Nat64],[r.Opt(t)],["query"]),get_account_transactions:r.Func([r.Nat64,r.Opt(r.Nat32),r.Opt(r.Nat32)],[a],["query"]),get_canister_info:r.Func([],[c],["query"]),get_controllers:r.Func([],[r.Vec(r.Principal)],["query"]),get_payout:r.Func([r.Nat],[r.Opt(l)],["query"]),get_refund_by_original_tx_id:r.Func([r.Nat],[r.Opt(u)],["query"]),get_transaction:r.Func([r.Nat],[r.Opt(o)],["query"]),get_transaction_status_public:r.Func([r.Nat64,r.Nat,r.Opt(r.Nat64)],[r.Opt(h)],["query"]),get_transactions:r.Func([p],[a],["query"]),icrc21_canister_call_consent_message:r.Func([C],[D],["query"]),initialize_controllers:r.Func([],[n],[]),list_accounts:r.Func([],[r.Vec(F)],["query"]),notify_ledger_transaction:r.Func([P],[z],[]),notify_onramp_icp:r.Func([r.Vec(r.Nat8),r.Vec(r.Nat8)],[z],[]),remove_account:r.Func([r.Nat64],[n],[]),request_payout:r.Func([r.Nat64,r.Text,r.Nat],[B],[]),request_refund:r.Func([r.Nat],[g],[]),retry_payout:r.Func([r.Nat],[B],[]),set_platform_wallet:r.Func([r.Text],[n],[]),update_account:r.Func([r.Nat64,t],[n],[]),update_controllers:r.Func([],[n],[])})},pie=({IDL:r})=>[]});var Qk={};Re(Qk,{idlFactory:()=>gie,init:()=>mie});var gie,mie,Gk=ye(()=>{"use strict";gie=({IDL:r})=>{let e=r.Rec(),t=r.Rec(),n=r.Rec(),i=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),s=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),o=r.Vec(r.Nat8),a=r.Record({owner:r.Principal,subaccount:r.Opt(o)}),c=r.Variant({SetTo:a,Unset:r.Null}),l=r.Record({icrc2:r.Bool}),u=r.Record({change_archive_options:r.Opt(i),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,s))),change_fee_collector:r.Opt(c),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(l)}),h=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,s)),minting_account:a,initial_balances:r.Vec(r.Tuple(a,r.Nat)),fee_collector_account:r.Opt(a),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(l)}),p=r.Variant({Upgrade:r.Opt(u),Init:h}),w=r.Nat,y=r.Record({block_range_end:w,canister_id:r.Principal,block_range_start:w}),v=r.Record({start:w,length:r.Nat}),C=r.Vec(r.Tuple(r.Text,n));n.fill(r.Variant({Int:r.Int,Map:C,Nat:r.Nat,Nat64:r.Nat64,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(n)}));let N=n,O=r.Record({blocks:r.Vec(N)}),L=r.Func([v],[O],["query"]),j=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),first_index:w,blocks:r.Vec(N),chain_length:r.Nat64,archived_blocks:r.Vec(r.Record({callback:L,start:w,length:r.Nat}))}),q=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),hash_tree:r.Vec(r.Nat8)}),D=r.Nat,F=r.Record({start:D,length:r.Nat}),P=r.Nat64,S=r.Record({from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,spender:r.Opt(a)}),z=r.Record({to:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat}),B=r.Record({fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(P),spender:a}),g=r.Record({to:a,fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,spender:r.Opt(a)}),m=r.Record({burn:r.Opt(S),kind:r.Text,mint:r.Opt(z),approve:r.Opt(B),timestamp:P,transfer:r.Opt(g)}),d=r.Record({transactions:r.Vec(m)}),f=r.Func([F],[d],["query"]),b=r.Record({first_index:D,log_length:r.Nat,transactions:r.Vec(m),archived_transactions:r.Vec(r.Record({callback:f,start:D,length:r.Nat}))}),_=r.Record({take:r.Opt(r.Nat),prev_spender:r.Opt(a),from_account:r.Opt(a)}),T=r.Record({from_account:a,to_spender:a,allowance:r.Nat,expires_at:r.Opt(r.Nat64)}),I=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),AccessDenied:r.Record({reason:r.Text})}),A=r.Variant({Ok:r.Vec(T),Err:I}),U=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),IndexPrincipalNotSet:r.Null}),M=r.Variant({Ok:r.Principal,Err:U}),R=r.Nat,H=r.Record({url:r.Text,name:r.Text}),V=r.Record({to:a,fee:r.Opt(R),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(o),created_at_time:r.Opt(P),amount:R}),G=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,BadBurn:r.Record({min_burn_amount:R}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:R}),CreatedInFuture:r.Record({ledger_time:P}),TooOld:r.Null,InsufficientFunds:r.Record({balance:R})}),X=r.Variant({Ok:w,Err:G}),se=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),W=r.Record({metadata:se,device_spec:r.Opt(r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}))}),Q=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:W}),Y=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(r.Record({lines:r.Vec(r.Text)}))}),GenericDisplayMessage:r.Text}),ne=r.Record({metadata:se,consent_message:Y}),J=r.Record({description:r.Text}),re=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),InsufficientPayment:J,UnsupportedCanisterCall:J,ConsentMessageUnavailable:J}),oe=r.Variant({Ok:ne,Err:re}),ie=r.Record({account:a,spender:a}),le=r.Record({allowance:r.Nat,expires_at:r.Opt(P)}),de=r.Record({fee:r.Opt(r.Nat),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(P),spender:a}),fe=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:r.Nat}),AllowanceChanged:r.Record({current_allowance:r.Nat}),CreatedInFuture:r.Record({ledger_time:P}),TooOld:r.Null,Expired:r.Record({ledger_time:P}),InsufficientFunds:r.Record({balance:r.Nat})}),Ee=r.Variant({Ok:w,Err:fe}),xe=r.Record({to:a,fee:r.Opt(R),spender_subaccount:r.Opt(o),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:R}),_e=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,InsufficientAllowance:r.Record({allowance:R}),BadBurn:r.Record({min_burn_amount:R}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:R}),CreatedInFuture:r.Record({ledger_time:P}),TooOld:r.Null,InsufficientFunds:r.Record({balance:R})}),Qe=r.Variant({Ok:w,Err:_e}),De=r.Record({from:r.Opt(r.Principal)}),Ye=r.Vec(r.Record({end:r.Nat,canister_id:r.Principal,start:r.Nat}));t.fill(r.Variant({Int:r.Int,Map:r.Vec(r.Tuple(r.Text,t)),Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(t)})),e.fill(r.Record({log_length:r.Nat,blocks:r.Vec(r.Record({id:r.Nat,block:t})),archived_blocks:r.Vec(r.Record({args:r.Vec(v),callback:r.Func([r.Vec(v)],[e],["query"])}))}));let Ze=r.Record({certificate:r.Vec(r.Nat8),hash_tree:r.Vec(r.Nat8)});return r.Service({archives:r.Func([],[r.Vec(y)],["query"]),get_blocks:r.Func([v],[j],["query"]),get_data_certificate:r.Func([],[q],["query"]),get_transactions:r.Func([F],[b],["query"]),icrc103_get_allowances:r.Func([_],[A],["query"]),icrc106_get_index_principal:r.Func([],[M],["query"]),icrc10_supported_standards:r.Func([],[r.Vec(r.Record({url:r.Text,name:r.Text}))],["query"]),icrc1_balance_of:r.Func([a],[R],["query"]),icrc1_decimals:r.Func([],[r.Nat8],["query"]),icrc1_fee:r.Func([],[R],["query"]),icrc1_metadata:r.Func([],[r.Vec(r.Tuple(r.Text,s))],["query"]),icrc1_minting_account:r.Func([],[r.Opt(a)],["query"]),icrc1_name:r.Func([],[r.Text],["query"]),icrc1_supported_standards:r.Func([],[r.Vec(H)],["query"]),icrc1_symbol:r.Func([],[r.Text],["query"]),icrc1_total_supply:r.Func([],[R],["query"]),icrc1_transfer:r.Func([V],[X],[]),icrc21_canister_call_consent_message:r.Func([Q],[oe],[]),icrc2_allowance:r.Func([ie],[le],["query"]),icrc2_approve:r.Func([de],[Ee],[]),icrc2_transfer_from:r.Func([xe],[Qe],[]),icrc3_get_archives:r.Func([De],[Ye],["query"]),icrc3_get_blocks:r.Func([r.Vec(v)],[e],["query"]),icrc3_get_tip_certificate:r.Func([],[r.Opt(Ze)],["query"]),icrc3_supported_block_types:r.Func([],[r.Vec(r.Record({url:r.Text,block_type:r.Text}))],["query"]),is_ledger_ready:r.Func([],[r.Bool],["query"])})},mie=({IDL:r})=>{let e=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),t=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),n=r.Vec(r.Nat8),i=r.Record({owner:r.Principal,subaccount:r.Opt(n)}),s=r.Variant({SetTo:i,Unset:r.Null}),o=r.Record({icrc2:r.Bool}),a=r.Record({change_archive_options:r.Opt(e),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,t))),change_fee_collector:r.Opt(s),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(o)}),c=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,t)),minting_account:i,initial_balances:r.Vec(r.Tuple(i,r.Nat)),fee_collector_account:r.Opt(i),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(o)});return[r.Variant({Upgrade:r.Opt(a),Init:c})]}});var Yk=$r(R9=>{"use strict";Object.defineProperty(R9,"__esModule",{value:!0});R9.debugLog=wie;function wie(r,e,t){r&&(t!==void 0?console.log(`[ICPay SDK] ${e}`,t):console.log(`[ICPay SDK] ${e}`))}});var Zk=$r(k9=>{"use strict";Object.defineProperty(k9,"__esModule",{value:!0});k9.createProtectedApi=yie;var cg=ew();function yie(r){let e=r.privateApiClient,t=r.emitStart,n=r.emitSuccess,i=r.emitError,s=o=>{if(!e)throw new cg.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${o} requires secret key authentication. Please provide secretKey in configuration.`})};return{async getPaymentById(o){s("getPaymentById"),t("getPaymentById",{id:o});try{let a=await e.get(`/sdk/payments/${o}`);return n("getPaymentById",{id:o}),a}catch(a){throw i("getPaymentById",a),a}},async listPayments(){s("listPayments"),t("listPayments");try{let o=await e.get("/sdk/payments");return n("listPayments",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("listPayments",o),o}},async getPaymentIntentById(o){s("getPaymentIntentById"),t("getPaymentIntentById",{id:o});try{let a=await e.get(`/sdk/payment-intents/${o}`);return n("getPaymentIntentById",{id:o}),a}catch(a){throw i("getPaymentIntentById",a),a}},async getInvoiceById(o){s("getInvoiceById"),t("getInvoiceById",{id:o});try{let a=await e.get(`/sdk/invoices/${o}`);return n("getInvoiceById",{id:o}),a}catch(a){throw i("getInvoiceById",a),a}},async getTransactionById(o){s("getTransactionById"),t("getTransactionById",{id:o});try{let a=await e.get(`/sdk/transactions/${o}`);return n("getTransactionById",{id:o}),a}catch(a){throw i("getTransactionById",a),a}},async getWalletById(o){s("getWalletById"),t("getWalletById",{id:o});try{let a=await e.get(`/sdk/wallets/${o}`);return n("getWalletById",{id:o}),a}catch(a){throw i("getWalletById",a),a}},async getVerifiedLedgersPrivate(){s("getVerifiedLedgersPrivate"),t("getVerifiedLedgersPrivate");try{let o=await e.get("/sdk/ledgers/verified");return n("getVerifiedLedgersPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getVerifiedLedgersPrivate",o),o}},async getAllLedgersWithPricesPrivate(){s("getAllLedgersWithPricesPrivate"),t("getAllLedgersWithPricesPrivate");try{let o=await e.get("/sdk/ledgers/all-with-prices");return n("getAllLedgersWithPricesPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getAllLedgersWithPricesPrivate",o),o}},async getLedgerInfoPrivate(o){s("getLedgerInfoPrivate"),t("getLedgerInfoPrivate",{idOrCanisterId:o});try{let a=await e.get(`/sdk/ledgers/${o}`);return n("getLedgerInfoPrivate",{idOrCanisterId:o}),a}catch(a){throw i("getLedgerInfoPrivate",a),a}},async getWebhookEventById(o){s("getWebhookEventById"),t("getWebhookEventById",{id:o});try{let a=await e.get(`/sdk/webhook-events/${o}`);return n("getWebhookEventById",{id:o}),a.data}catch(a){throw i("getWebhookEventById",a),a}},async getDetailedAccountInfo(){s("getDetailedAccountInfo"),t("getDetailedAccountInfo");try{let o=await e.get("/sdk/account"),a={id:o.id,name:o.name,email:o.email,isActive:o.isActive,isLive:o.isLive,accountCanisterId:o.accountCanisterId,walletAddress:o.walletAddress,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt)};return n("getDetailedAccountInfo",a),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch detailed account information",details:o});throw i("getDetailedAccountInfo",a),a}},async getTransactionStatus(o){s("getTransactionStatus"),t("getTransactionStatus",{canisterTransactionId:o});try{let a=await e.get(`/sdk/transactions/${o}/status`);return n("getTransactionStatus",a),a}catch(a){let c=new cg.IcpayError({code:"TRANSACTION_STATUS_FETCH_FAILED",message:"Failed to fetch transaction status",details:a});throw i("getTransactionStatus",c),c}},async getPaymentHistory(o={}){s("getPaymentHistory"),t("getPaymentHistory",{request:o});try{let a=new URLSearchParams;o.accountId&&a.append("accountId",o.accountId),o.ledgerCanisterId&&a.append("ledgerCanisterId",o.ledgerCanisterId),o.fromTimestamp&&a.append("fromTimestamp",o.fromTimestamp.toISOString()),o.toTimestamp&&a.append("toTimestamp",o.toTimestamp.toISOString()),o.status&&a.append("status",o.status),o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString());let c=await e.get(`/sdk/payments/history?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentHistory",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENT_HISTORY_FETCH_FAILED",message:"Failed to fetch payment history",details:a});throw i("getPaymentHistory",c),c}},async getPaymentsByPrincipal(o){s("getPaymentsByPrincipal"),t("getPaymentsByPrincipal",{request:o});try{let a=new URLSearchParams;o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString()),o.status&&a.append("status",o.status);let c=await e.get(`/sdk/payments/by-principal/${o.principalId}?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentsByPrincipal",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENTS_BY_PRINCIPAL_FETCH_FAILED",message:"Failed to fetch payments by principal",details:a});throw i("getPaymentsByPrincipal",c),c}},async getAccountWalletBalances(){s("getAccountWalletBalances"),t("getAccountWalletBalances");try{let o=await e.get("/sdk/account/wallet-balances"),a={balances:o.balances.map(c=>({ledgerId:c.ledgerId,ledgerName:c.ledgerName,ledgerSymbol:c.ledgerSymbol,canisterId:c.canisterId,balance:c.balance,formattedBalance:c.formattedBalance,decimals:c.decimals,currentPrice:c.currentPrice,lastPriceUpdate:c.lastPriceUpdate?new Date(c.lastPriceUpdate):void 0,lastUpdated:new Date(c.lastUpdated)})),totalBalancesUSD:o.totalBalancesUSD,lastUpdated:new Date(o.lastUpdated)};return n("getAccountWalletBalances",{count:a.balances.length,totalUSD:a.totalBalancesUSD}),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_WALLET_BALANCES_FETCH_FAILED",message:"Failed to fetch account wallet balances",details:o});throw i("getAccountWalletBalances",a),a}}}}});var Xk=$r(VA=>{"use strict";Object.defineProperty(VA,"__esModule",{value:!0});VA.HttpClient=void 0;var U9=class{constructor(e){this.baseURL=e.baseURL.replace(/\/$/,""),this.defaultHeaders={"Content-Type":"application/json",...e.headers||{}}}setHeader(e,t){t===void 0?delete this.defaultHeaders[e]:this.defaultHeaders[e]=t}async get(e,t){let n=this.resolve(e),i=await fetch(n,{method:"GET",headers:{...this.defaultHeaders,...t||{}}});return this.handleResponse(i)}async post(e,t,n){let i=this.resolve(e),s=await fetch(i,{method:"POST",headers:{...this.defaultHeaders,...n||{}},body:t===void 0?void 0:JSON.stringify(t)});return this.handleResponse(s)}resolve(e){return/^https?:\/\//i.test(e)?e:`${this.baseURL}${e.startsWith("/")?"":"/"}${e}`}async handleResponse(e){let t=await e.text(),i=(e.headers.get("content-type")||"").includes("application/json")&&t?JSON.parse(t):t;if(!e.ok){let s=new Error(`HTTP ${e.status}: ${e.statusText}`);throw s.status=e.status,s.data=i,s}return i}};VA.HttpClient=U9});var eU=$r(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0})});var j9=$r(eo=>{"use strict";var bie=eo&&eo.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),iU=eo&&eo.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&bie(e,r,t)};Object.defineProperty(eo,"__esModule",{value:!0});eo.IcpayWallet=eo.IcpayError=eo.Icpay=void 0;var Mt=ew(),vie=g8(),Aie=B9(),Hh=(_a(),Yd(Ak)),L9=(Kk(),Yd(Vk)),tU=(Gk(),Yd(Qk)),rU=(Zi(),Yd(k8)),Wr=Yk(),Eie=Zk(),nU=Xk(),KA=class{constructor(e){if(this.privateApiClient=null,this.connectedWallet=null,this.icpayCanisterId=null,this.accountInfoCache=null,this.verifiedLedgersCache={data:null,timestamp:0},this.icpLedgerCanisterId="ryjl3-tyaaa-aaaaa-aaaba-cai",this.config={environment:"production",apiUrl:"https://api.icpay.org",debug:!1,enableEvents:!0,...e},(0,Wr.debugLog)(this.config.debug||!1,"constructor",{config:this.config}),!this.config.publishableKey&&!this.config.secretKey)throw new Error("Either publishableKey or secretKey must be provided");if(this.icHost=e.icHost||"https://ic0.app",this.connectedWallet=e.connectedWallet||null,this.actorProvider=e.actorProvider,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet,actorProvider:this.actorProvider}),this.wallet=new Aie.IcpayWallet({connectedWallet:this.connectedWallet}),this.events=new vie.IcpayEventCenter,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet}),this.publicApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.publishableKey||this.config.secretKey||""}`}}),(0,Wr.debugLog)(this.config.debug||!1,"publicApiClient created",this.publicApiClient),this.config.secretKey){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.config.secretKey||""}`};this.privateApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:t})}(0,Wr.debugLog)(this.config.debug||!1,"privateApiClient created",this.privateApiClient),this.protected=(0,Eie.createProtectedApi)({privateApiClient:this.privateApiClient,emitStart:(t,n)=>this.emitMethodStart(t,n),emitSuccess:(t,n)=>this.emitMethodSuccess(t,n),emitError:(t,n)=>this.emitMethodError(t,n)})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.config.enableEvents&&this.events.emit(e,t)}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}dispatchEvent(e){return this.events.dispatchEvent(e)}emitError(e){let t=e instanceof Mt.IcpayError?e:new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.UNKNOWN_ERROR,message:e&&(e.message||e.toString())||"Unknown error",details:e});this.config.enableEvents&&this.events.emit("icpay-sdk-error",t)}emitMethodStart(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-start",{name:e,args:t})}emitMethodSuccess(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-success",{name:e,result:t})}emitMethodError(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-error",{name:e,error:t}),this.emitError(t)}hasSecretKey(){return!!this.config.secretKey&&!!this.privateApiClient}requireSecretKey(e){if(!this.hasSecretKey())throw new Mt.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${e} requires secret key authentication. Please provide secretKey and accountId in configuration.`})}async getAccountInfo(){this.emitMethodStart("getAccountInfo");try{let e=await this.publicApiClient.get("/sdk/public/account"),t={id:e.id,name:e.name,isActive:e.isActive,isLive:e.isLive,accountCanisterId:e.accountCanisterId,icpayCanisterId:e.icpayCanisterId,branding:e.branding||null};return this.emitMethodSuccess("getAccountInfo",t),t}catch(e){let t=new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e});throw this.emitMethodError("getAccountInfo",t),t}}async getVerifiedLedgers(){this.emitMethodStart("getVerifiedLedgers");let e=Date.now(),t=3600*1e3;if(this.verifiedLedgersCache.data&&e-this.verifiedLedgersCache.timestamp<t)return this.verifiedLedgersCache.data;try{let i=(await this.publicApiClient.get("/sdk/public/ledgers/verified")).map(s=>({id:s.id,name:s.name,symbol:s.symbol,canisterId:s.canisterId,decimals:s.decimals,logoUrl:s.logoUrl,verified:s.verified,fee:s.fee,currentPrice:s.currentPrice??null,lastPriceUpdate:s.lastPriceUpdate??null}));return this.verifiedLedgersCache={data:i,timestamp:e},this.emitMethodSuccess("getVerifiedLedgers",{count:i.length}),i}catch(n){let i=new Mt.IcpayError({code:"VERIFIED_LEDGERS_FETCH_FAILED",message:"Failed to fetch verified ledgers",details:n});throw this.emitMethodError("getVerifiedLedgers",i),i}}async getLedgerCanisterIdBySymbol(e){if(this.emitMethodStart("getLedgerCanisterIdBySymbol",{symbol:e}),!e||typeof e!="string")throw new Mt.IcpayError({code:"INVALID_LEDGER_SYMBOL",message:"Symbol must be a non-empty string"});let n=(await this.getVerifiedLedgers()).find(s=>s.symbol.toLowerCase()===e.toLowerCase());if(!n)throw new Mt.IcpayError({code:"LEDGER_SYMBOL_NOT_FOUND",message:`Verified ledger with symbol ${e} not found`});let i=n.canisterId;return this.emitMethodSuccess("getLedgerCanisterIdBySymbol",{symbol:e,canisterId:i}),i}async triggerTransactionSync(e){this.emitMethodStart("triggerTransactionSync",{canisterTransactionId:e});try{let t=await this.publicApiClient.get(`/sdk/public/transactions/${e}/sync`);return this.emitMethodSuccess("triggerTransactionSync",t),t}catch(t){let n=new Mt.IcpayError({code:"TRANSACTION_SYNC_TRIGGER_FAILED",message:"Failed to trigger transaction sync from canister",details:t});throw this.emitMethodError("triggerTransactionSync",n),n}}async fetchAccountInfo(){if(this.accountInfoCache)return this.icpayCanisterId=this.accountInfoCache.icpayCanisterId.toString(),this.accountInfoCache;try{let e=await this.publicApiClient.get("/sdk/public/account");return this.accountInfoCache=e,e&&e.icpayCanisterId&&(this.icpayCanisterId=e.icpayCanisterId.toString()),this.accountInfoCache}catch(e){throw new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e})}}async showWalletModal(){this.emitMethodStart("showWalletModal");try{let e=await this.wallet.showConnectionModal();return this.emitMethodSuccess("showWalletModal",e),e}catch(e){throw this.emitMethodError("showWalletModal",e),e}}async connectWallet(e){this.emitMethodStart("connectWallet",{providerId:e});try{let t=await this.wallet.connectToProvider(e);return this.emitMethodSuccess("connectWallet",t),t}catch(t){throw this.emitMethodError("connectWallet",t),t}}getWalletProviders(){this.emitMethodStart("getWalletProviders");let e=this.wallet.getProviders();return this.emitMethodSuccess("getWalletProviders",{count:Array.isArray(e)?e.length:void 0}),e}isWalletProviderAvailable(e){this.emitMethodStart("isWalletProviderAvailable",{providerId:e});let t=this.wallet.isProviderAvailable(e);return this.emitMethodSuccess("isWalletProviderAvailable",{providerId:e,available:t}),t}getAccountAddress(){this.emitMethodStart("getAccountAddress");let e=this.wallet.getAccountAddress();return this.emitMethodSuccess("getAccountAddress",{accountAddress:e}),e}async getLedgerBalance(e){this.emitMethodStart("getLedgerBalance",{ledgerCanisterId:e});try{let t=null;if(this.connectedWallet&&(this.connectedWallet.owner?t=this.connectedWallet.owner:this.connectedWallet.principal&&(t=this.connectedWallet.principal)),!t)throw new Error("No principal available for balance check");let n=rU.Principal.fromText(t),i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(tU.idlFactory,{agent:i,canisterId:e}).icrc1_balance_of({owner:n,subaccount:[]}),a=BigInt(o);return this.emitMethodSuccess("getLedgerBalance",{ledgerCanisterId:e,balance:a.toString()}),a}catch(t){throw this.emitMethodError("getLedgerBalance",t),t}}createPackedMemo(e,t){let n=BigInt(e>>>0)<<BigInt(32)|BigInt(t>>>0);if(n===BigInt(0))return new Uint8Array([0]);let i=[];for(;n>BigInt(0);)i.push(Number(n&BigInt(255))),n>>=BigInt(8);return new Uint8Array(i)}async sendFunds(e){this.emitMethodStart("sendFunds",{request:{...e,amount:typeof e.amount=="string"?e.amount:String(e.amount)}});try{(0,Wr.debugLog)(this.config.debug||!1,"sendFunds start",{request:e});let t=e.ledgerCanisterId;if(!t&&e.symbol&&(t=await this.getLedgerCanisterIdBySymbol(e.symbol)),!t){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("sendFunds",P),P}let n=e.accountCanisterId;if(n||((0,Wr.debugLog)(this.config.debug||!1,"fetching account info for accountCanisterId"),n=(await this.getAccountInfo()).accountCanisterId.toString(),(0,Wr.debugLog)(this.config.debug||!1,"accountCanisterId resolved",{accountCanisterId:n})),this.icpayCanisterId||await this.fetchAccountInfo(),!this.icpayCanisterId)try{let P=await this.getAccountInfo();P?.icpayCanisterId&&(this.icpayCanisterId=P.icpayCanisterId.toString())}catch{}if(!this.icpayCanisterId||typeof this.icpayCanisterId!="string"){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Could not resolve ICPay canister ID from account info",details:{accountInfoCache:this.accountInfoCache}});throw this.emitMethodError("sendFunds",P),P}let i=this.icpayCanisterId,s=this.icHost,o;if(e.onrampPayment===!0||this.config.onrampPayment===!0){if(t!==this.icpLedgerCanisterId){let B=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Onramp is only supported for ICP ledger",details:{provided:t,expected:this.icpLedgerCanisterId}});throw this.emitError(B),B}let P=e.amountUsd;if(P==null)try{let B=await this.calculateTokenAmountFromUSD({usdAmount:1,ledgerCanisterId:t}),g=B.currentPrice,m=(typeof e.amount=="string",Number(e.amount));P=g*(m/Math.pow(10,B.decimals))}catch{}let S=null,z=null;try{(0,Wr.debugLog)(this.config.debug||!1,"creating onramp payment intent");let B=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,metadata:e.metadata||{},onrampPayment:!0,widgetParams:e.widgetParams||{},amountUsd:typeof P=="string"?P:P?.toFixed(2)});S=B?.paymentIntentId||B?.paymentIntent?.id||null,z=B?.paymentIntentCode??null;let g=B?.onramp||{};return{transactionId:0,status:"pending",amount:e.amount,recipientCanister:this.icpayCanisterId,timestamp:new Date,metadata:{paymentIntentId:S,paymentIntentCode:z,onramp:g}}}catch(B){let g=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create onramp payment intent",details:B,retryable:!0,userAction:"Try again"});throw this.emitError(g),g}}let c=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;if(!c&&e.amountUsd!=null)try{c=(await this.calculateTokenAmountFromUSD({usdAmount:Number(e.amountUsd),ledgerCanisterId:t})).tokenAmountDecimals}catch{}if(!c){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Either amount or amountUsd must be provided"});throw this.emitError(P),P}let l=BigInt(c);(0,Wr.debugLog)(this.config.debug||!1,"checking balance",{ledgerCanisterId:t,requiredAmount:l.toString()});let u=(P,S=8,z="")=>{let B=BigInt(10**S),g=P/B,d=(P%B).toString().padStart(S,"0").replace(/0+$/,"");return`${g}${d?"."+d:""} ${z}`.trim()};try{let P=await this.getLedgerBalance(t);if(P<l){let S=u(l,8,"tokens"),z=u(P,8,"tokens");throw(0,Mt.createBalanceError)(S,z,{required:l,available:P,ledgerCanisterId:t})}(0,Wr.debugLog)(this.config.debug||!1,"balance ok",{actualBalance:P.toString()})}catch{throw new Mt.IcpayError({code:"INSUFFICIENT_BALANCE",message:"Insufficient balance",details:{required:l,available:0}})}let h=null,p=null,w=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;try{(0,Wr.debugLog)(this.config.debug||!1,"creating payment intent");let P=this.connectedWallet?.owner||this.connectedWallet?.principal?.toString();if(!P)throw new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.WALLET_NOT_CONNECTED,message:"Wallet must be connected to create payment intent",details:{connectedWallet:this.connectedWallet},retryable:!1,userAction:"Connect your wallet first"});let S=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,expectedSenderPrincipal:P,metadata:e.metadata||{},amountUsd:e.amountUsd});h=S?.paymentIntent?.id||null,p=S?.paymentIntent?.intentCode??null,w=S?.paymentIntent?.amount||w,(0,Wr.debugLog)(this.config.debug||!1,"payment intent created",{paymentIntentId:h,paymentIntentCode:p,expectedSenderPrincipal:P,resolvedAmountStr:w}),h&&this.emit("icpay-sdk-transaction-created",{paymentIntentId:h,amount:w,ledgerCanisterId:t,expectedSenderPrincipal:P})}catch(P){let S=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create payment intent. Please try again.",details:P,retryable:!0,userAction:"Try again"});throw this.emitError(S),S}if(!w){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Payment intent did not return amount"});throw this.emitError(P),P}let y=BigInt(w);try{let P=parseInt(n);!isNaN(P)&&p!=null&&(o=this.createPackedMemo(P,Number(p)),(0,Wr.debugLog)(this.config.debug||!1,"built packed memo",{accountCanisterId:P,paymentIntentCode:p})),(0,Wr.debugLog)(this.config.debug||!1,"memo",{memo:o})}catch{}let v;t===this.icpLedgerCanisterId?((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer (ICP)"),v=await this.sendFundsToLedger(t,i,y,o,s)):((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer"),v=await this.sendFundsToLedger(t,i,y,o,s));let C=v?.Ok?.toString()||v?.blockIndex?.toString()||`temp-${Date.now()}`;(0,Wr.debugLog)(this.config.debug||!1,"transfer result",{blockIndex:C});let N,O=null;try{(0,Wr.debugLog)(this.config.debug||!1,"notifying canister about ledger tx");let P=await this.notifyLedgerTransaction(this.icpayCanisterId,t,BigInt(C));typeof P=="string"?N=parseInt(P,10):(N=parseInt(P.id,10),O=P),(0,Wr.debugLog)(this.config.debug||!1,"canister notified",{canisterTransactionId:N})}catch{N=parseInt(C,10),(0,Wr.debugLog)(this.config.debug||!1,"notify failed, using blockIndex as tx id",{canisterTransactionId:N})}let L=null;if(O&&O.status)L={status:O.status};else try{(0,Wr.debugLog)(this.config.debug||!1,"polling transaction status (public)",{canisterTransactionId:N}),L=await this.pollTransactionStatus(this.icpayCanisterId,N,n,Number(C),2e3,30),(0,Wr.debugLog)(this.config.debug||!1,"poll done",{status:L})}catch{L={status:"pending"},(0,Wr.debugLog)(this.config.debug||!1,"poll failed, falling back to pending")}let j="pending";if(L&&typeof L=="object"&&L.status)if(typeof L.status=="object"){let P=Object.keys(L.status);if(P.length>0){let S=P[0].toLowerCase();(S==="completed"||S==="failed")&&(j=S)}}else{let P=L.status;(P==="completed"||P==="failed")&&(j=P)}let q;q=await this.performNotifyPaymentIntent({paymentIntentId:h,canisterTransactionId:N?.toString(),maxAttempts:99999,delayMs:1e3});let D=q?.paymentIntent?.status||q?.payment?.status||q?.status;if(typeof D=="string"){let P=D.toLowerCase();P==="completed"||P==="succeeded"?j="completed":P==="failed"||P==="canceled"||P==="cancelled"?j="failed":j="pending"}let F={transactionId:N,status:j,amount:y.toString(),recipientCanister:t,timestamp:new Date,description:"Fund transfer",metadata:e.metadata,payment:q};if((0,Wr.debugLog)(this.config.debug||!1,"sendFunds done",F),j==="completed"){let P=q?.payment?.requestedAmount||null,S=q?.payment?.paidAmount||null;q?.payment?.status==="mismatched"?(this.emit("icpay-sdk-transaction-mismatched",{...F,requestedAmount:P,paidAmount:S}),this.emit("icpay-sdk-transaction-updated",{...F,status:"mismatched",requestedAmount:P,paidAmount:S})):this.emit("icpay-sdk-transaction-completed",F)}else j==="failed"?this.emit("icpay-sdk-transaction-failed",F):this.emit("icpay-sdk-transaction-updated",F);return this.emitMethodSuccess("sendFunds",F),F}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("sendFunds",t),t;let n=new Mt.IcpayError({code:"TRANSACTION_FAILED",message:"Failed to send funds",details:t});throw this.emitMethodError("sendFunds",n),n}}async disconnectWallet(){return await this.wallet.disconnect()}isWalletConnected(){return this.wallet.isConnected()}getConnectedWalletProvider(){return this.wallet.getConnectedProvider()}async pollTransactionStatus(e,t,n,i,s=2e3,o=30){this.emitMethodStart("pollTransactionStatus",{canisterId:e,transactionId:t,accountCanisterId:n,indexReceived:i,intervalMs:s,maxAttempts:o});for(let c=0;c<o;c++)try{let l=await this.getTransactionStatusPublic(e,t,i,n);if(Array.isArray(l)&&l.length>0){let u=l[0];if(u&&typeof u=="object"&&u.status){let h=u.status;if(this.isTransactionCompleted(h))return u}}if(l&&l.status&&this.isTransactionCompleted(l.status))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;if(l&&typeof l=="object"&&(l.Ok||l.Err))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;c<o-1&&await new Promise(u=>setTimeout(u,s))}catch(l){c===o-1&&this.emitMethodError("pollTransactionStatus",l),c<o-1&&await new Promise(u=>setTimeout(u,s))}let a=new Error("Transaction status polling timed out");throw this.emitMethodError("pollTransactionStatus",a),a}isTransactionCompleted(e){if(!e)return!1;if(typeof e=="object"){let t=Object.keys(e);if(t.length>0)return t[0].toLowerCase()==="completed"}return typeof e=="string"?e.toLowerCase()==="completed":!1}async notifyLedgerTransaction(e,t,n){this.emitMethodStart("notifyLedgerTransaction",{canisterId:e,ledgerCanisterId:t,blockIndex:n.toString()});let i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(L9.idlFactory,{agent:i,canisterId:e}).notify_ledger_transaction({ledger_canister_id:t,block_index:n});if(o&&o.Ok)return this.emitMethodSuccess("notifyLedgerTransaction",{result:o.Ok}),o.Ok;if(o&&o.Err){let a=new Error(o.Err);throw this.emitMethodError("notifyLedgerTransaction",a),a}else{let a=new Error("Unexpected canister notify result");throw this.emitMethodError("notifyLedgerTransaction",a),a}}async getTransactionStatusPublic(e,t,n,i){this.emitMethodStart("getTransactionStatusPublic",{canisterId:e,canisterTransactionId:t,indexReceived:n,accountCanisterId:i});let s=new Hh.HttpAgent({host:this.icHost}),o=Hh.Actor.createActor(L9.idlFactory,{agent:s,canisterId:e}),a=parseInt(i),l=await o.get_transaction_status_public(a,BigInt(t),[n])||{status:"pending"};return this.emitMethodSuccess("getTransactionStatusPublic",l),l}async sendFundsToLedger(e,t,n,i,s){this.emitMethodStart("sendFundsToLedger",{ledgerCanisterId:e,toPrincipal:t,amount:n.toString(),hasMemo:!!i});let o;if(this.actorProvider)o=this.actorProvider(e,tU.idlFactory);else{let c=new Error("actorProvider is required for sending funds");throw this.emitMethodError("sendFundsToLedger",c),c}let a=await o.icrc1_transfer({to:{owner:rU.Principal.fromText(t),subaccount:[]},amount:n,fee:[],memo:i?[i]:[],from_subaccount:[],created_at_time:[]});return this.emitMethodSuccess("sendFundsToLedger",a),a}async getTransactionByFilter(e){this.emitMethodStart("getTransactionByFilter",{transactionId:e});try{this.icpayCanisterId||await this.fetchAccountInfo();let t=new Hh.HttpAgent({host:this.icHost}),n=Hh.Actor.createActor(L9.idlFactory,{agent:t,canisterId:this.icpayCanisterId}),i=BigInt(e),s=await n.get_transactions({account_canister_id:[],ledger_canister_id:[],from_timestamp:[],to_timestamp:[],from_id:[],status:[],limit:[],offset:[]});if(s&&s.transactions){let o=s.transactions.find(a=>a.id.toString()===e.toString());return this.emitMethodSuccess("getTransactionByFilter",{found:!!o}),o}return this.emitMethodSuccess("getTransactionByFilter",{found:!1}),null}catch(t){throw this.emitMethodError("getTransactionByFilter",t),t}}async getAllLedgerBalances(){this.emitMethodStart("getAllLedgerBalances");try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balances"});let e=await this.getVerifiedLedgers(),t=[],n=0;for(let s of e)try{let o=await this.getLedgerBalance(s.canisterId),a=this.formatBalance(o.toString(),s.decimals),c={ledgerId:s.id,ledgerName:s.name,ledgerSymbol:s.symbol,canisterId:s.canisterId,balance:o.toString(),formattedBalance:a,decimals:s.decimals,currentPrice:s.currentPrice||void 0,lastPriceUpdate:s.lastPriceUpdate?new Date(s.lastPriceUpdate):void 0,lastUpdated:new Date};if(t.push(c),s.currentPrice&&o>0){let l=parseFloat(a);n+=l*s.currentPrice}}catch(o){this.emit("icpay-sdk-method-error",{name:"getAllLedgerBalances.getLedgerBalance",error:o,ledgerSymbol:s.symbol,ledgerCanisterId:s.canisterId})}let i={balances:t,totalBalancesUSD:n>0?n:void 0,lastUpdated:new Date};return this.emitMethodSuccess("getAllLedgerBalances",{count:t.length,totalUSD:i.totalBalancesUSD}),i}catch(e){let t=new Mt.IcpayError({code:"BALANCES_FETCH_FAILED",message:"Failed to fetch all ledger balances",details:e});throw this.emitMethodError("getAllLedgerBalances",t),t}}async getSingleLedgerBalance(e){this.emitMethodStart("getSingleLedgerBalance",{ledgerCanisterId:e});try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balance"});let n=(await this.getVerifiedLedgers()).find(a=>a.canisterId===e);if(!n)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger with canister ID ${e} not found or not verified`});let i=await this.getLedgerBalance(e),s=this.formatBalance(i.toString(),n.decimals),o={ledgerId:n.id,ledgerName:n.name,ledgerSymbol:n.symbol,canisterId:n.canisterId,balance:i.toString(),formattedBalance:s,decimals:n.decimals,currentPrice:n.currentPrice||void 0,lastPriceUpdate:n.lastPriceUpdate?new Date(n.lastPriceUpdate):void 0,lastUpdated:new Date};return this.emitMethodSuccess("getSingleLedgerBalance",{ledgerCanisterId:e,balance:o.balance}),o}catch(t){let n=new Mt.IcpayError({code:"SINGLE_BALANCE_FETCH_FAILED",message:`Failed to fetch balance for ledger ${e}`,details:t});throw this.emitMethodError("getSingleLedgerBalance",n),n}}async calculateTokenAmountFromUSD(e){this.emitMethodStart("calculateTokenAmountFromUSD",{usdAmount:e.usdAmount,ledgerCanisterId:e.ledgerCanisterId,ledgerSymbol:e.ledgerSymbol});try{let{usdAmount:t,ledgerCanisterId:n,ledgerSymbol:i}=e;if(t<=0)throw new Mt.IcpayError({code:"INVALID_USD_AMOUNT",message:"USD amount must be greater than 0"});let o=(await this.getVerifiedLedgers()).find(u=>u.canisterId===n||i&&u.symbol===i);if(!o)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger not found for canister ID ${n} or symbol ${i}`});if(!o.currentPrice||o.currentPrice<=0)throw new Mt.IcpayError({code:"PRICE_NOT_AVAILABLE",message:`Current price not available for ledger ${o.symbol}`});let a=t/o.currentPrice,c=Math.floor(a*Math.pow(10,o.decimals)).toString(),l={usdAmount:t,ledgerCanisterId:o.canisterId,ledgerSymbol:o.symbol,ledgerName:o.name,currentPrice:o.currentPrice,priceTimestamp:o.lastPriceUpdate?new Date(o.lastPriceUpdate):new Date,tokenAmountHuman:a.toFixed(o.decimals),tokenAmountDecimals:c,decimals:o.decimals};return this.emitMethodSuccess("calculateTokenAmountFromUSD",{ledgerCanisterId:l.ledgerCanisterId,tokenAmountDecimals:c}),l}catch(t){let n=new Mt.IcpayError({code:"PRICE_CALCULATION_FAILED",message:"Failed to calculate token amount from USD",details:t});throw this.emitMethodError("calculateTokenAmountFromUSD",n),n}}async getLedgerInfo(e){this.emitMethodStart("getLedgerInfo",{ledgerCanisterId:e});try{let t=await this.publicApiClient.get(`/sdk/public/ledgers/${e}`),n={id:t.id,name:t.name,symbol:t.symbol,canisterId:t.canisterId,standard:t.standard,decimals:t.decimals,logoUrl:t.logoUrl??null,verified:t.verified,fee:t.fee??null,network:t.network,description:t.description??null,lastBlockIndex:t.lastBlockIndex??null,coingeckoId:t.coingeckoId??null,currentPrice:t.currentPrice??null,priceFetchMethod:t.priceFetchMethod??null,lastPriceUpdate:t.lastPriceUpdate??null,createdAt:t.createdAt,updatedAt:t.updatedAt};return this.emitMethodSuccess("getLedgerInfo",{ledgerCanisterId:e}),n}catch(t){let n=new Mt.IcpayError({code:"LEDGER_INFO_FETCH_FAILED",message:`Failed to fetch ledger info for ${e}`,details:t});throw this.emitMethodError("getLedgerInfo",n),n}}async sendFundsUsd(e){this.emitMethodStart("sendFundsUsd",{request:e});try{let t=typeof e.usdAmount=="string"?parseFloat(e.usdAmount):e.usdAmount,n=e.ledgerCanisterId;if(!n&&e.symbol&&(n=await this.getLedgerCanisterIdBySymbol(e.symbol)),!n){let o=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("sendFundsUsd",o),o}let i={ledgerCanisterId:n,symbol:e.symbol,amountUsd:t,accountCanisterId:e.accountCanisterId,metadata:e.metadata,onrampPayment:e.onrampPayment,widgetParams:e.widgetParams},s=await this.sendFunds(i);return this.emitMethodSuccess("sendFundsUsd",s),s}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("sendFundsUsd",t),t;let n=new Mt.IcpayError({code:"SEND_FUNDS_USD_FAILED",message:"Failed to send funds from USD",details:t});throw this.emitMethodError("sendFundsUsd",n),n}}notifyPaymentIntentOnRamp(e){let t=e.paymentIntentId,n=Math.max(1e3,e.intervalMs??5e3),i=e.orderId,s=null,o=null;try{this.emitMethodSuccess("notifyLedgerTransaction",{paymentIntentId:t})}catch{}let a=async()=>{let c=await this.performNotifyPaymentIntent({paymentIntentId:t,orderId:i}),l=(c?.paymentIntent?.status||"").toLowerCase(),u=(c?.payment?.status||"").toLowerCase(),h=l||u||"";h&&h!==o&&(o=h,h==="completed"||h==="succeeded"?this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-completed",{detail:{id:t,status:h}})):h==="mismatched"?(this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-mismatched",{detail:{id:t,status:h,payment:c?.payment}})),this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:h}}))):this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:h}})))};return a().catch(()=>{}),s=setInterval(a,n),{stop:()=>{s&&(clearInterval(s),s=null)}}}async performNotifyPaymentIntent(e){let t=this.publicApiClient,n="/sdk/public/payments/notify",i=e.maxAttempts??1,s=e.delayMs??0;for(let o=1;o<=i;o++)try{(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent",{attempt:o,notifyPath:n,paymentIntentId:e.paymentIntentId,canisterTxId:e.canisterTransactionId});let a={paymentIntentId:e.paymentIntentId};e.canisterTransactionId&&(a.canisterTxId=e.canisterTransactionId),e.orderId&&(a.orderId=e.orderId);let c=await t.post(n,a);if(o===i)return c;let l=c?.paymentIntent?.status||c?.payment?.status||c?.status||"";if(typeof l=="string"){let u=l.toLowerCase();if(u==="completed"||u==="succeeded")return c}s>0&&await new Promise(u=>setTimeout(u,s))}catch(a){let c=a?.response?.status,l=a?.response?.data;(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent error",{attempt:o,status:c,data:l}),o<i&&s>0&&await new Promise(u=>setTimeout(u,s))}return{}}async getAllLedgersWithPrices(){this.emitMethodStart("getAllLedgersWithPrices");try{let t=(await this.publicApiClient.get("/sdk/public/ledgers/all-with-prices")).map(n=>({id:n.id,name:n.name,symbol:n.symbol,canisterId:n.canisterId,standard:n.standard,decimals:n.decimals,logoUrl:n.logoUrl??null,verified:n.verified,fee:n.fee??null,network:n.network,description:n.description??null,lastBlockIndex:n.lastBlockIndex??null,coingeckoId:n.coingeckoId??null,currentPrice:n.currentPrice??null,priceFetchMethod:n.priceFetchMethod??null,lastPriceUpdate:n.lastPriceUpdate??null,createdAt:n.createdAt,updatedAt:n.updatedAt}));return this.emitMethodSuccess("getAllLedgersWithPrices",{count:t.length}),t}catch(e){let t=new Mt.IcpayError({code:"LEDGERS_WITH_PRICES_FETCH_FAILED",message:"Failed to fetch ledgers with price information",details:e});throw this.emitMethodError("getAllLedgersWithPrices",t),t}}formatBalance(e,t){let n=parseFloat(e),i=Math.pow(10,t),s=Math.floor(n/i),a=(n%i).toString().padStart(t,"0").replace(/0+$/,"");return`${s}${a?"."+a:""}`}};eo.Icpay=KA;iU(eU(),eo);var xie=ew();Object.defineProperty(eo,"IcpayError",{enumerable:!0,get:function(){return xie.IcpayError}});var Sie=B9();Object.defineProperty(eo,"IcpayWallet",{enumerable:!0,get:function(){return Sie.IcpayWallet}});iU(g8(),eo);eo.default=KA});var Bie,m$e,aU,cU,lU,oU,ry,Rie,kie,uU,hU=ye(()=>{"use strict";_a();_a();Zi();Bie=(r=>(r[r.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",r[r.InvalidFormat=1]="InvalidFormat",r[r.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",r))(Bie||{}),m$e=BigInt(1e8),aU=r=>new Uint8Array(r),cU=r=>Array.from(r).map(e=>e.charCodeAt(0)),lU=r=>(r instanceof Uint8Array||(r=Uint8Array.from(r)),r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")),oU="abcdefghijklmnopqrstuvwxyz234567",ry=Object.create(null);for(let r=0;r<oU.length;r++)ry[oU[r]]=r;ry[0]=ry.o;ry[1]=ry.i;Rie=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]),kie=r=>{let e=-1;for(let t=0;t<r.length;t++){let n=(r[t]^e)&255;e=Rie[n]^e>>>8}return(e^-1)>>>0},uU=r=>{let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,kie(r),!1),new Uint8Array(e)}});function Lie(){if(!GA&&(GA=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!GA))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return GA(Uie)}function jie(r,e=0){return es[r[e+0]]+es[r[e+1]]+es[r[e+2]]+es[r[e+3]]+"-"+es[r[e+4]]+es[r[e+5]]+"-"+es[r[e+6]]+es[r[e+7]]+"-"+es[r[e+8]]+es[r[e+9]]+"-"+es[r[e+10]]+es[r[e+11]]+es[r[e+12]]+es[r[e+13]]+es[r[e+14]]+es[r[e+15]]}function YA(r,e,t){if(dU.randomUUID&&!r)return dU.randomUUID();r=r||{};let n=r.random||(r.rng||Lie)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,jie(n)}var GA,Uie,es,zie,dU,H9=ye(()=>{"use strict";Uie=new Uint8Array(16);es=[];for(let r=0;r<256;++r)es.push((r+256).toString(16).slice(1));zie=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dU={randomUUID:zie}});var wU={};Re(wU,{StandardSolflareMetaMaskWalletAccount:()=>n4,default:()=>i4});function Die(){if(fU)return F9;fU=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,C=0,N=0,O=y.length;N!==O&&y[N]===0;)N++,v++;for(var L=(O-N)*u+1>>>0,j=new Uint8Array(L);N!==O;){for(var q=y[N],D=0,F=L-1;(q!==0||D<C)&&F!==-1;F--,D++)q+=256*j[F]>>>0,j[F]=q%a>>>0,q=q/a>>>0;if(q!==0)throw new Error("Non-zero carry");C=D,N++}for(var P=L-C;P!==L&&j[P]===0;)P++;for(var S=c.repeat(v);P<L;++P)S+=e.charAt(j[P]);return S}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var v=0,C=0,N=0;y[v]===c;)C++,v++;for(var O=(y.length-v)*l+1>>>0,L=new Uint8Array(O);y[v];){var j=y.charCodeAt(v);if(j>255)return;var q=t[j];if(q===255)return;for(var D=0,F=O-1;(q!==0||D<N)&&F!==-1;F--,D++)q+=a*L[F]>>>0,L[F]=q%256>>>0,q=q/256>>>0;if(q!==0)throw new Error("Non-zero carry");N=D,v++}for(var P=O-N;P!==O&&L[P]===0;)P++;for(var S=new Uint8Array(C+(O-P)),z=C;P!==O;)S[z++]=L[P++];return S}function w(y){var v=p(y);if(v)return v;throw new Error("Non-base"+a+" character")}return{encode:h,decodeUnsafe:p,decode:w}}return F9=r,F9}function qie(){return pU||(pU=1,$9=Die()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),$9}function Q9(r){return r.version===void 0}function W9(r){return Q9(r)?r.serialize({verifySignatures:!1,requireAllSignatures:!1}):r.serialize()}function V9(r){return gU(this,void 0,void 0,function*(){try{return yield r.request({method:"wallet_getSnaps"}),!0}catch{return!1}})}function Fie(){return gU(this,void 0,void 0,function*(){try{let r=window.ethereum;if(!r)return null;if(r.providers&&Array.isArray(r.providers)){let e=r.providers;for(let t of e)if(yield V9(t))return t}if(r.detected&&Array.isArray(r.detected)){let e=r.detected;for(let t of e)if(yield V9(t))return t}return(yield V9(r))?r:null}catch(r){return console.error(r),null}})}function K9(r){return mU.includes(r)}var F9,fU,$9,pU,Hie,fl,gU,$ie,Wie,Vie,Kie,mU,lg,ug,ZA,XA,JA,e4,t4,r4,Qie,Gie,n4,Sc,i4,yU=ye(()=>{"use strict";hg();H9();Hie=qie(),fl=co(Hie);gU=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};$ie="solana:mainnet",Wie="solana:devnet",Vie="solana:testnet",Kie="solana:localnet",mU=[$ie,Wie,Vie,Kie];lg=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ug=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Qie=mU,Gie=[G9,Z9,Y9],n4=class r{get address(){return lg(this,ZA,"f")}get publicKey(){return lg(this,XA,"f").slice()}get chains(){return lg(this,JA,"f").slice()}get features(){return lg(this,e4,"f").slice()}get label(){return lg(this,t4,"f")}get icon(){return lg(this,r4,"f")}constructor({address:e,publicKey:t,label:n,icon:i}){ZA.set(this,void 0),XA.set(this,void 0),JA.set(this,void 0),e4.set(this,void 0),t4.set(this,void 0),r4.set(this,void 0),new.target===r&&Object.freeze(this),ug(this,ZA,e,"f"),ug(this,XA,t,"f"),ug(this,JA,Qie,"f"),ug(this,e4,Gie,"f"),ug(this,t4,n,"f"),ug(this,r4,i,"f")}};ZA=new WeakMap,XA=new WeakMap,JA=new WeakMap,e4=new WeakMap,t4=new WeakMap,r4=new WeakMap;Sc=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},i4=class r extends Cu{constructor(e){super(),this._network="mainnet-beta",this._iframeParams={},this._element=null,this._iframe=null,this._publicKey=null,this._account=null,this._isConnected=!1,this._connectHandler=null,this._messageHandlers={},this._handleEvent=t=>{var n,i;switch(t.type){case"connect":{this._collapseIframe(),!((n=t.data)===null||n===void 0)&&n.publicKey?(this._publicKey=t.data.publicKey,this._isConnected=!0,this._connectHandler&&(this._connectHandler.resolve(),this._connectHandler=null),this._connected()):(this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected());return}case"disconnect":{this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected();return}case"accountChanged":{!((i=t.data)===null||i===void 0)&&i.publicKey?(this._publicKey=t.data.publicKey,this.emit("accountChanged",this.publicKey),this._standardConnected()):(this.emit("accountChanged",void 0),this._standardDisconnected());return}default:return}},this._handleResize=t=>{t.resizeMode==="full"?t.params.mode==="fullscreen"?this._expandIframe():t.params.mode==="hide"&&this._collapseIframe():t.resizeMode==="coordinates"&&this._resizeIframe(t.params)},this._handleMessage=t=>{var n;if(((n=t.data)===null||n===void 0?void 0:n.channel)!=="solflareIframeToWalletAdapter")return;let i=t.data.data||{};if(i.type==="event")this._handleEvent(i.event);else if(i.type==="resize")this._handleResize(i);else if(i.type==="response"&&this._messageHandlers[i.id]){let{resolve:s,reject:o}=this._messageHandlers[i.id];delete this._messageHandlers[i.id],i.error?o(i.error):s(i.result)}},this._removeElement=()=>{this._element&&(this._element.remove(),this._element=null)},this._removeDanglingElements=()=>{let t=document.getElementsByClassName("solflare-metamask-wallet-adapter-iframe");for(let n of t)n.parentElement&&n.remove()},this._injectElement=()=>{this._removeElement(),this._removeDanglingElements();let t=Object.assign(Object.assign({},this._iframeParams),{mm:!0,v:1,cluster:this._network||"mainnet-beta",origin:window.location.origin||"",title:document.title||""}),n=Object.keys(t).map(s=>`${s}=${encodeURIComponent(t[s])}`).join("&"),i=`${r.IFRAME_URL}?${n}`;this._element=document.createElement("div"),this._element.className="solflare-metamask-wallet-adapter-iframe",this._element.innerHTML=`
54
+ ic-request`);xu=class{constructor(e,t,n){this.pubkey=e,this.expiration=t,this.targets=n}toCBOR(){return ng.value.map(Object.assign({pubkey:ng.value.bytes(this.pubkey),expiration:ng.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:ng.value.array(this.targets.map(e=>ng.value.bytes(nl(e.toUint8Array()))))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:zt(this.pubkey)},this.targets&&{targets:this.targets.map(e=>e.toHex())})}};Su=class r{constructor(e,t){this.delegations=e,this.publicKey=t}static async create(e,t,n=new Date(Date.now()+900*1e3),i={}){var s,o;let a=await Vne(e,t,n,i.targets);return new r([...((s=i.previous)===null||s===void 0?void 0:s.delegations)||[],a],((o=i.previous)===null||o===void 0?void 0:o.publicKey)||e.getPublicKey().toDer())}static fromJSON(e){let{publicKey:t,delegations:n}=typeof e=="string"?JSON.parse(e):e;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(s=>{let{delegation:o,signature:a}=s,{pubkey:c,expiration:l,targets:u}=o;if(u!==void 0&&!Array.isArray(u))throw new Error("Invalid targets.");return{delegation:new xu(y9(c),BigInt("0x"+l),u&&u.map(h=>{if(typeof h!="string")throw new Error("Invalid target.");return Ve.fromHex(h)})),signature:y9(a)}});return new this(i,y9(t))}static fromDelegations(e,t){return new this(e,t)}toJSON(){return{delegations:this.delegations.map(e=>{let{delegation:t,signature:n}=e,{targets:i}=t;return{delegation:Object.assign({expiration:t.expiration.toString(16),pubkey:zt(t.pubkey)},i&&{targets:i.map(s=>s.toHex())}),signature:zt(n)}}),publicKey:zt(this.publicKey)}}},xc=class extends al{constructor(e,t){super(),this._inner=e,this._delegation=t}static fromDelegation(e,t){return new this(e,t)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(e){return this._inner.sign(e)}async transformRequest(e){let{body:t}=e,n=Fne(e,["body"]),i=await pc(t);return Object.assign(Object.assign({},n),{body:{content:t,sender_sig:await this.sign(nl(new Uint8Array([...Wne,...new Uint8Array(i)]))),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}},ey=class r extends zA{constructor(e,t){super(e),DA.set(this,void 0),qne(this,DA,t,"f")}get delegation(){return Hne(this,DA,"f")}static fromDelegation(e,t){return new r(e,t)}};DA=new WeakMap});var Kne,Nk,Tk=ye(()=>{"use strict";_a();Kne=lc(F2());Mh();(function(r){r[r.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Nk||(Nk={}))});var b9=ye(()=>{"use strict";xk();Ck();_k();w9();Tk();_a()});var Ok,ig,v9=ye(()=>{"use strict";Ok=["mousedown","mousemove","keydown","touchstart","wheel"],ig=class{constructor(e={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=e||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let s=this._resetTimer.bind(this);window.addEventListener("load",s,!0),Ok.forEach(function(a){document.addEventListener(a,s,!0)});let o=(a,c)=>{let l;return(...u)=>{let h=this,p=function(){l=void 0,a.apply(h,u)};clearTimeout(l),l=window.setTimeout(p,c)}};if(e?.captureScroll){let a=o(s,(t=e?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",a,!0)}s()}static create(e={}){return new this(e)}registerCallback(e){this.callbacks.push(e)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let e=this._resetTimer.bind(this);Ok.forEach(function(t){document.removeEventListener(t,e,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let e=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(e,this.idleTimeout)}}});function Gne(){return Mk||(Mk=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Yne(){return Pk||(Pk=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function Zne(r){let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("success",s),r.removeEventListener("error",o)},s=()=>{t(dl(r.result)),i()},o=()=>{n(r.error),i()};r.addEventListener("success",s),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Bk.set(t,r)}).catch(()=>{}),S9.set(e,r),e}function Xne(r){if(E9.has(r))return;let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("complete",s),r.removeEventListener("error",o),r.removeEventListener("abort",o)},s=()=>{t(),i()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),i()};r.addEventListener("complete",s),r.addEventListener("error",o),r.addEventListener("abort",o)});E9.set(r,e)}function kk(r){x9=r(x9)}function Jne(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(qA(this),e,...t);return Rk.set(n,e.sort?e.sort():[e]),dl(n)}:Yne().includes(r)?function(...e){return r.apply(qA(this),e),dl(Bk.get(this))}:function(...e){return dl(r.apply(qA(this),e))}}function eie(r){return typeof r=="function"?Jne(r):(r instanceof IDBTransaction&&Xne(r),Qne(r,Gne())?new Proxy(r,x9):r)}function dl(r){if(r instanceof IDBRequest)return Zne(r);if(A9.has(r))return A9.get(r);let e=eie(r);return e!==r&&(A9.set(r,e),S9.set(e,r)),e}var Qne,Mk,Pk,Bk,E9,Rk,A9,S9,x9,qA,C9=ye(()=>{"use strict";Qne=(r,e)=>e.some(t=>r instanceof t);Bk=new WeakMap,E9=new WeakMap,Rk=new WeakMap,A9=new WeakMap,S9=new WeakMap;x9={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return E9.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Rk.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return dl(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};qA=r=>S9.get(r)});function Lk(r,e,{blocked:t,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(r,e),a=dl(o);return n&&o.addEventListener("upgradeneeded",c=>{n(dl(o.result),c.oldVersion,c.newVersion,dl(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Uk(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(I9.get(e))return I9.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,i=rie.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(i||tie.includes(t)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),i&&c.done]))[0]};return I9.set(e,s),s}var tie,rie,I9,jk=ye(()=>{"use strict";C9();C9();tie=["get","getKey","getAll","getAllKeys","count"],rie=["put","add","delete","clear"],I9=new Map;kk(r=>({...r,get:(e,t,n)=>Uk(e,t)||r.get(e,t,n),has:(e,t)=>!!Uk(e,t)||r.has(e,t)}))});async function iie(r,e,t){return await r.get(e,t)}async function sie(r,e,t,n){return await r.put(e,n,t)}async function oie(r,e,t){return await r.delete(e,t)}var zk,Dk,nie,sg,_9=ye(()=>{"use strict";jk();FA();zk="auth-client-db",Dk="ic-keyval",nie=async(r=zk,e=Dk,t)=>(HA&&(localStorage!=null&&localStorage.getItem(Ta))&&(localStorage.removeItem(Ta),localStorage.removeItem(Oa)),await Lk(r,t,{upgrade:n=>{n.objectStoreNames.contains(e)&&n.clear(e),n.createObjectStore(e)}}));sg=class r{constructor(e,t){this._db=e,this._storeName=t}static async create(e){let{dbName:t=zk,storeName:n=Dk,version:i=qk}=e??{},s=await nie(t,n,i);return new r(s,n)}async set(e,t){return await sie(this._db,this._storeName,e,t)}async get(e){var t;return(t=await iie(this._db,this._storeName,e))!==null&&t!==void 0?t:null}async remove(e){return await oie(this._db,this._storeName,e)}}});var aie,cie,$A,Oa,Ta,Hk,qk,HA,og,ag,FA=ye(()=>{"use strict";_9();aie=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},cie=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Oa="identity",Ta="delegation",Hk="iv",qk=1,HA=typeof window<"u",og=class{constructor(e="ic-",t){this.prefix=e,this._localStorage=t}get(e){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+e))}set(e,t){return this._getLocalStorage().setItem(this.prefix+e,t),Promise.resolve()}remove(e){return this._getLocalStorage().removeItem(this.prefix+e),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let e=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!e)throw new Error("Could not find local storage.");return e}},ag=class{constructor(e){$A.set(this,void 0),aie(this,$A,e??{},"f")}get _db(){return new Promise(e=>{if(this.initializedDb){e(this.initializedDb);return}sg.create(cie(this,$A,"f")).then(t=>{this.initializedDb=t,e(t)})})}async get(e){return await(await this._db).get(e)}async set(e,t){await(await this._db).set(e,t)}async remove(e){await(await this._db).remove(e)}};$A=new WeakMap});var $k={};Re($k,{AuthClient:()=>ty,ERROR_USER_INTERRUPT:()=>Fk,IdbKeyVal:()=>sg,IdbStorage:()=>ag,IdleManager:()=>ig,KEY_STORAGE_DELEGATION:()=>Ta,KEY_STORAGE_KEY:()=>Oa,LocalStorage:()=>og});async function O9(r){await r.remove(Oa),await r.remove(Ta),await r.remove(Hk)}var lie,uie,N9,T9,hie,Fk,ty,M9=ye(()=>{"use strict";_a();b9();v9();FA();FA();_9();v9();lie="https://identity.internetcomputer.org",uie="#authorize",N9="ECDSA",T9="Ed25519",hie=500,Fk="UserInterrupt",ty=class{constructor(e,t,n,i,s,o,a,c){this._identity=e,this._key=t,this._chain=n,this._storage=i,this.idleManager=s,this._createOptions=o,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(e={}){var t,n,i;let s=(t=e.storage)!==null&&t!==void 0?t:new ag,o=(n=e.keyType)!==null&&n!==void 0?n:N9,a=null;if(e.identity)a=e.identity;else{let h=await s.get(Oa);if(!h&&HA)try{let p=new og,w=await p.get(Ta),y=await p.get(Oa);w&&y&&o===N9&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await s.set(Ta,w),await s.set(Oa,y),h=w,await p.remove(Ta),await p.remove(Oa))}catch(p){console.error("error while attempting to recover localstorage: "+p)}if(h)try{typeof h=="object"?o===T9&&typeof h=="string"?a=await Na.fromJSON(h):a=await Of.fromKeyPair(h):typeof h=="string"&&(a=Na.fromJSON(h))}catch{}}let c=new Aa,l=null;if(a)try{let h=await s.get(Ta);if(typeof h=="object"&&h!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");e.identity?c=e.identity:h&&(l=Su.fromJSON(h),Ik(l)?"toDer"in a?c=ey.fromDelegation(a,l):c=xc.fromDelegation(a,l):(await O9(s),a=null))}catch(h){console.error(h),await O9(s),a=null}let u;return!((i=e.idleOptions)===null||i===void 0)&&i.disableIdle?u=void 0:(l||e.identity)&&(u=ig.create(e.idleOptions)),a||(o===T9?(a=await Na.generate(),await s.set(Oa,JSON.stringify(a.toJSON()))):(e.storage&&o===N9&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${T9}' as the key type, as it can serialize to a string`),a=await Of.generate(),await s.set(Oa,a.getKeyPair()))),new this(c,a,l,s,u,e)}_registerDefaultIdleCallback(){var e,t;let n=(e=this._createOptions)===null||e===void 0?void 0:e.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(e,t){var n,i;let s=e.delegations.map(l=>({delegation:new xu(l.delegation.pubkey,l.delegation.expiration,l.delegation.targets),signature:l.signature.buffer})),o=Su.fromDelegations(s,e.userPublicKey.buffer),a=this._key;if(!a)return;this._chain=o,"toDer"in a?this._identity=ey.fromDelegation(a,this._chain):this._identity=xc.fromDelegation(a,this._chain),(n=this._idpWindow)===null||n===void 0||n.close();let c=(i=this._createOptions)===null||i===void 0?void 0:i.idleOptions;!this.idleManager&&!c?.disableIdle&&(this.idleManager=ig.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ta,JSON.stringify(this._chain.toJSON())),t?.(e)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(e){var t,n,i,s;let o=BigInt(8)*BigInt(36e11),a=new URL(((t=e?.identityProvider)===null||t===void 0?void 0:t.toString())||lie);a.hash=uie,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(a,Object.assign({maxTimeToLive:(i=e?.maxTimeToLive)!==null&&i!==void 0?i:o},e)),window.addEventListener("message",this._eventHandler),this._idpWindow=(s=window.open(a.toString(),"idpWindow",e?.windowOpenerFeatures))!==null&&s!==void 0?s:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Fk,e?.onError):setTimeout(c,hie))};c()}_getEventHandler(e,t){return async n=>{var i,s,o;if(n.origin!==e.origin)return;let a=n.data;switch(a.kind){case"authorize-ready":{let c=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((i=this._key)===null||i===void 0?void 0:i.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(s=t?.derivationOrigin)===null||s===void 0?void 0:s.toString()},t?.customValues);(o=this._idpWindow)===null||o===void 0||o.postMessage(c,e.origin);break}case"authorize-client-success":try{await this._handleSuccess(a,t?.onSuccess)}catch(c){this._handleFailure(c.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(a.text,t?.onError);break;default:break}}}_handleFailure(e,t){var n;(n=this._idpWindow)===null||n===void 0||n.close(),t?.(e),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(e={}){if(await O9(this._storage),this._identity=new Aa,this._chain=null,e.returnTo)try{window.history.pushState({},"",e.returnTo)}catch{window.location.href=e.returnTo}}}});var B9=$r(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.IcpayWallet=void 0;var die=(M9(),Yd($k)),Wk=(Zi(),Yd(k8)),Ma=ew(),P9=class{constructor(e){this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null,this.connectedWallet=null,this.providers=[{id:"internet-identity",name:"Internet Identity",icon:"\u{1F310}",description:"Official Internet Computer identity provider"},{id:"oisy",name:"OISY",icon:"\u{1F510}",description:"OISY wallet for Internet Computer"},{id:"plug",name:"Plug Wallet",icon:"\u{1F50C}",description:"Plug wallet extension"}],e?.connectedWallet&&(this.connectedWallet=e.connectedWallet)}getProviders(){return this.providers}isProviderAvailable(e){if(typeof window>"u")return!1;switch(e){case"internet-identity":return!0;case"oisy":return"oisy"in window;case"plug":return"ic"in window&&window.ic!==void 0&&"plug"in window.ic;default:return!1}}async connectToProvider(e){try{switch(e){case"internet-identity":return await this.connectInternetIdentity();case"oisy":return await this.connectOisy();case"plug":return await this.connectPlug();default:throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.UNSUPPORTED_PROVIDER,`Unsupported wallet provider: ${e}`)}}catch(t){throw t instanceof Error&&(t.message.includes("rejected")||t.message.includes("cancelled"))?(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,`Connection to ${e} was cancelled by user`):(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_CONNECTION_FAILED,`Failed to connect to ${e}`,t)}}async connectInternetIdentity(){return this.authClient=await die.AuthClient.create(),await this.authClient.isAuthenticated()?(this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity"):await new Promise((e,t)=>{this.authClient.login({identityProvider:"https://identity.ic0.app",onSuccess:()=>{this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity",e()},onError:n=>{t(new Error(`Authentication failed: ${n||"Unknown error"}`))}})}),{provider:"internet-identity",principal:this.principal.toText(),accountId:this.principal.toText(),connected:!0}}async connectOisy(){if(typeof window>"u"||!window.oisy)throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_PROVIDER_NOT_AVAILABLE,"OISY wallet is not available");try{let e=await window.oisy.requestConnect();if(e.connected)return this.principal=Wk.Principal.fromText(e.principal),this.connectedProvider="oisy",{provider:"oisy",principal:e.principal,accountId:e.principal,connected:!0};throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,"OISY connection was rejected by user")}catch(e){throw new Error(`OISY connection failed: ${e}`)}}async connectPlug(){if(typeof window>"u"||!window.ic?.plug)throw new Error("Plug wallet is not available");try{if(await window.ic.plug.requestConnect()){let t=await window.ic.plug.getPrincipal();return this.principal=Wk.Principal.fromText(t),this.connectedProvider="plug",{provider:"plug",principal:t,accountId:t,connected:!0}}else throw new Error("Plug connection was rejected")}catch(e){throw new Error(`Plug connection failed: ${e}`)}}async showConnectionModal(){let e=this.providers.filter(t=>this.isProviderAvailable(t.id));if(e.length===0)throw new Ma.IcpayError({code:"NO_PROVIDERS_AVAILABLE",message:"No wallet providers are available"});return await this.connectToProvider(e[0].id)}getAccountAddress(){if(!this.principal)throw new Ma.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet is not connected"});return this.principal.toText()}async disconnect(){this.authClient&&await this.authClient.logout(),this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null}isConnected(){return this.connectedWallet?this.connectedWallet.owner||this.connectedWallet.principal||typeof this.connectedWallet.getPrincipal=="function"?!0:"connected"in this.connectedWallet?!!this.connectedWallet.connected:this.connectedWallet!==null&&typeof this.connectedWallet=="object":this.identity!==null&&this.principal!==null}getIdentity(){return this.identity}getPrincipal(){return this.principal}getConnectedProvider(){return this.connectedProvider}};WA.IcpayWallet=P9});var Vk={};Re(Vk,{idlFactory:()=>fie,init:()=>pie});var fie,pie,Kk=ye(()=>{"use strict";fie=({IDL:r})=>{let e=r.Record({account_canister_id:r.Nat64,percentage:r.Nat16}),t=r.Record({account_canister_id:r.Nat64,platform_fee_percentage:r.Nat16,subaccount:r.Opt(r.Vec(r.Nat8)),wallet_address:r.Text,icp_account_identifier:r.Opt(r.Text),platform_fee_fixed:r.Opt(r.Nat),is_active:r.Bool,splits:r.Vec(e)}),n=r.Variant({Ok:r.Null,Err:r.Text}),i=r.Variant({Failed:r.Text,Processed:r.Null,Received:r.Null,Completed:r.Null,Pending:r.Null}),s=r.Record({account_canister_id:r.Nat64,index_block:r.Opt(r.Nat64),timestamp:r.Opt(r.Nat64),account_percentage:r.Nat16,amount:r.Nat}),o=r.Record({id:r.Nat,status:i,account_canister_id:r.Nat64,platform_fee_amount:r.Nat,transfer_fee:r.Nat,memo:r.Opt(r.Vec(r.Nat8)),timestamp_to_account:r.Opt(r.Nat64),notify_processing:r.Bool,source_type:r.Nat8,timestamp:r.Nat64,index_received:r.Opt(r.Nat64),sender_principal_id:r.Text,account_amount:r.Nat,ledger_canister_id:r.Text,splits:r.Vec(s),timestamp_received:r.Opt(r.Nat64),amount:r.Nat}),a=r.Record({transactions:r.Vec(o),total_count:r.Nat32,has_more:r.Bool}),c=r.Record({total_accounts:r.Nat32,cycles_balance:r.Nat64,controllers:r.Vec(r.Principal),is_healthy:r.Bool,last_update_timestamp:r.Nat64,active_accounts:r.Nat32,memory_size_bytes:r.Nat64,total_transactions:r.Nat32,platform_wallet:r.Text}),l=r.Record({id:r.Nat,fee:r.Nat,status:i,account_canister_id:r.Nat64,to_principal:r.Text,to_subaccount:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Vec(r.Nat8),icp_account_identifier:r.Opt(r.Text),notify_processing:r.Opt(r.Bool),timestamp_created:r.Nat64,index:r.Opt(r.Nat64),ledger_canister_id:r.Text,timestamp_completed:r.Opt(r.Nat64),amount:r.Nat,status_message:r.Opt(r.Text)}),u=r.Record({status:i,timestamp_platform_to_account:r.Opt(r.Nat64),account_canister_id:r.Nat64,original_tx_id:r.Nat,notify_processing:r.Bool,timestamp_created:r.Nat64,timestamp_to_sender:r.Opt(r.Nat64),ledger_canister_id:r.Text,amount:r.Nat,platform_refund_amount:r.Nat,index_to_sender:r.Opt(r.Nat64),index_platform_to_account:r.Opt(r.Nat64)}),h=r.Record({status:i,amount:r.Nat}),p=r.Record({from_timestamp:r.Opt(r.Nat64),status:r.Opt(i),account_canister_id:r.Opt(r.Nat64),from_id:r.Opt(r.Nat),offset:r.Opt(r.Nat32),limit:r.Opt(r.Nat32),to_timestamp:r.Opt(r.Nat64),ledger_canister_id:r.Opt(r.Text)}),w=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),y=r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}),v=r.Record({metadata:w,device_spec:r.Opt(y)}),C=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:v}),N=r.Record({lines:r.Vec(r.Text)}),O=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(N)}),GenericDisplayMessage:r.Text}),L=r.Record({metadata:w,consent_message:O}),j=r.Record({description:r.Text}),q=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat64}),InsufficientPayment:j,UnsupportedCanisterCall:j,ConsentMessageUnavailable:j}),D=r.Variant({Ok:L,Err:q}),F=r.Record({account_canister_id:r.Nat64,account:t}),P=r.Record({block_index:r.Nat64,ledger_canister_id:r.Text}),S=r.Record({id:r.Text,status:i,amount:r.Nat}),z=r.Variant({Ok:S,Err:r.Text}),B=r.Variant({Ok:l,Err:r.Text}),g=r.Variant({Ok:r.Nat,Err:r.Text});return r.Service({add_account:r.Func([r.Nat64,t],[n],[]),get_account:r.Func([r.Nat64],[r.Opt(t)],["query"]),get_account_transactions:r.Func([r.Nat64,r.Opt(r.Nat32),r.Opt(r.Nat32)],[a],["query"]),get_canister_info:r.Func([],[c],["query"]),get_controllers:r.Func([],[r.Vec(r.Principal)],["query"]),get_payout:r.Func([r.Nat],[r.Opt(l)],["query"]),get_refund_by_original_tx_id:r.Func([r.Nat],[r.Opt(u)],["query"]),get_transaction:r.Func([r.Nat],[r.Opt(o)],["query"]),get_transaction_status_public:r.Func([r.Nat64,r.Nat,r.Opt(r.Nat64)],[r.Opt(h)],["query"]),get_transactions:r.Func([p],[a],["query"]),icrc21_canister_call_consent_message:r.Func([C],[D],["query"]),initialize_controllers:r.Func([],[n],[]),list_accounts:r.Func([],[r.Vec(F)],["query"]),notify_ledger_transaction:r.Func([P],[z],[]),notify_onramp_icp:r.Func([r.Vec(r.Nat8),r.Vec(r.Nat8)],[z],[]),remove_account:r.Func([r.Nat64],[n],[]),request_payout:r.Func([r.Nat64,r.Text,r.Nat],[B],[]),request_refund:r.Func([r.Nat],[g],[]),retry_payout:r.Func([r.Nat],[B],[]),set_platform_wallet:r.Func([r.Text],[n],[]),update_account:r.Func([r.Nat64,t],[n],[]),update_controllers:r.Func([],[n],[])})},pie=({IDL:r})=>[]});var Qk={};Re(Qk,{idlFactory:()=>gie,init:()=>mie});var gie,mie,Gk=ye(()=>{"use strict";gie=({IDL:r})=>{let e=r.Rec(),t=r.Rec(),n=r.Rec(),i=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),s=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),o=r.Vec(r.Nat8),a=r.Record({owner:r.Principal,subaccount:r.Opt(o)}),c=r.Variant({SetTo:a,Unset:r.Null}),l=r.Record({icrc2:r.Bool}),u=r.Record({change_archive_options:r.Opt(i),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,s))),change_fee_collector:r.Opt(c),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(l)}),h=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,s)),minting_account:a,initial_balances:r.Vec(r.Tuple(a,r.Nat)),fee_collector_account:r.Opt(a),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(l)}),p=r.Variant({Upgrade:r.Opt(u),Init:h}),w=r.Nat,y=r.Record({block_range_end:w,canister_id:r.Principal,block_range_start:w}),v=r.Record({start:w,length:r.Nat}),C=r.Vec(r.Tuple(r.Text,n));n.fill(r.Variant({Int:r.Int,Map:C,Nat:r.Nat,Nat64:r.Nat64,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(n)}));let N=n,O=r.Record({blocks:r.Vec(N)}),L=r.Func([v],[O],["query"]),j=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),first_index:w,blocks:r.Vec(N),chain_length:r.Nat64,archived_blocks:r.Vec(r.Record({callback:L,start:w,length:r.Nat}))}),q=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),hash_tree:r.Vec(r.Nat8)}),D=r.Nat,F=r.Record({start:D,length:r.Nat}),P=r.Nat64,S=r.Record({from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,spender:r.Opt(a)}),z=r.Record({to:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat}),B=r.Record({fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(P),spender:a}),g=r.Record({to:a,fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,spender:r.Opt(a)}),m=r.Record({burn:r.Opt(S),kind:r.Text,mint:r.Opt(z),approve:r.Opt(B),timestamp:P,transfer:r.Opt(g)}),d=r.Record({transactions:r.Vec(m)}),f=r.Func([F],[d],["query"]),b=r.Record({first_index:D,log_length:r.Nat,transactions:r.Vec(m),archived_transactions:r.Vec(r.Record({callback:f,start:D,length:r.Nat}))}),_=r.Record({take:r.Opt(r.Nat),prev_spender:r.Opt(a),from_account:r.Opt(a)}),T=r.Record({from_account:a,to_spender:a,allowance:r.Nat,expires_at:r.Opt(r.Nat64)}),I=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),AccessDenied:r.Record({reason:r.Text})}),A=r.Variant({Ok:r.Vec(T),Err:I}),U=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),IndexPrincipalNotSet:r.Null}),M=r.Variant({Ok:r.Principal,Err:U}),R=r.Nat,H=r.Record({url:r.Text,name:r.Text}),V=r.Record({to:a,fee:r.Opt(R),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(o),created_at_time:r.Opt(P),amount:R}),G=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,BadBurn:r.Record({min_burn_amount:R}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:R}),CreatedInFuture:r.Record({ledger_time:P}),TooOld:r.Null,InsufficientFunds:r.Record({balance:R})}),X=r.Variant({Ok:w,Err:G}),se=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),W=r.Record({metadata:se,device_spec:r.Opt(r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}))}),Q=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:W}),Y=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(r.Record({lines:r.Vec(r.Text)}))}),GenericDisplayMessage:r.Text}),ne=r.Record({metadata:se,consent_message:Y}),J=r.Record({description:r.Text}),re=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),InsufficientPayment:J,UnsupportedCanisterCall:J,ConsentMessageUnavailable:J}),oe=r.Variant({Ok:ne,Err:re}),ie=r.Record({account:a,spender:a}),le=r.Record({allowance:r.Nat,expires_at:r.Opt(P)}),de=r.Record({fee:r.Opt(r.Nat),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(P),spender:a}),fe=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:r.Nat}),AllowanceChanged:r.Record({current_allowance:r.Nat}),CreatedInFuture:r.Record({ledger_time:P}),TooOld:r.Null,Expired:r.Record({ledger_time:P}),InsufficientFunds:r.Record({balance:r.Nat})}),Ee=r.Variant({Ok:w,Err:fe}),xe=r.Record({to:a,fee:r.Opt(R),spender_subaccount:r.Opt(o),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(P),amount:R}),_e=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,InsufficientAllowance:r.Record({allowance:R}),BadBurn:r.Record({min_burn_amount:R}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:R}),CreatedInFuture:r.Record({ledger_time:P}),TooOld:r.Null,InsufficientFunds:r.Record({balance:R})}),Qe=r.Variant({Ok:w,Err:_e}),De=r.Record({from:r.Opt(r.Principal)}),Ye=r.Vec(r.Record({end:r.Nat,canister_id:r.Principal,start:r.Nat}));t.fill(r.Variant({Int:r.Int,Map:r.Vec(r.Tuple(r.Text,t)),Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(t)})),e.fill(r.Record({log_length:r.Nat,blocks:r.Vec(r.Record({id:r.Nat,block:t})),archived_blocks:r.Vec(r.Record({args:r.Vec(v),callback:r.Func([r.Vec(v)],[e],["query"])}))}));let Ze=r.Record({certificate:r.Vec(r.Nat8),hash_tree:r.Vec(r.Nat8)});return r.Service({archives:r.Func([],[r.Vec(y)],["query"]),get_blocks:r.Func([v],[j],["query"]),get_data_certificate:r.Func([],[q],["query"]),get_transactions:r.Func([F],[b],["query"]),icrc103_get_allowances:r.Func([_],[A],["query"]),icrc106_get_index_principal:r.Func([],[M],["query"]),icrc10_supported_standards:r.Func([],[r.Vec(r.Record({url:r.Text,name:r.Text}))],["query"]),icrc1_balance_of:r.Func([a],[R],["query"]),icrc1_decimals:r.Func([],[r.Nat8],["query"]),icrc1_fee:r.Func([],[R],["query"]),icrc1_metadata:r.Func([],[r.Vec(r.Tuple(r.Text,s))],["query"]),icrc1_minting_account:r.Func([],[r.Opt(a)],["query"]),icrc1_name:r.Func([],[r.Text],["query"]),icrc1_supported_standards:r.Func([],[r.Vec(H)],["query"]),icrc1_symbol:r.Func([],[r.Text],["query"]),icrc1_total_supply:r.Func([],[R],["query"]),icrc1_transfer:r.Func([V],[X],[]),icrc21_canister_call_consent_message:r.Func([Q],[oe],[]),icrc2_allowance:r.Func([ie],[le],["query"]),icrc2_approve:r.Func([de],[Ee],[]),icrc2_transfer_from:r.Func([xe],[Qe],[]),icrc3_get_archives:r.Func([De],[Ye],["query"]),icrc3_get_blocks:r.Func([r.Vec(v)],[e],["query"]),icrc3_get_tip_certificate:r.Func([],[r.Opt(Ze)],["query"]),icrc3_supported_block_types:r.Func([],[r.Vec(r.Record({url:r.Text,block_type:r.Text}))],["query"]),is_ledger_ready:r.Func([],[r.Bool],["query"])})},mie=({IDL:r})=>{let e=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),t=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),n=r.Vec(r.Nat8),i=r.Record({owner:r.Principal,subaccount:r.Opt(n)}),s=r.Variant({SetTo:i,Unset:r.Null}),o=r.Record({icrc2:r.Bool}),a=r.Record({change_archive_options:r.Opt(e),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,t))),change_fee_collector:r.Opt(s),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(o)}),c=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,t)),minting_account:i,initial_balances:r.Vec(r.Tuple(i,r.Nat)),fee_collector_account:r.Opt(i),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(o)});return[r.Variant({Upgrade:r.Opt(a),Init:c})]}});var Yk=$r(R9=>{"use strict";Object.defineProperty(R9,"__esModule",{value:!0});R9.debugLog=wie;function wie(r,e,t){r&&(t!==void 0?console.log(`[ICPay SDK] ${e}`,t):console.log(`[ICPay SDK] ${e}`))}});var Zk=$r(k9=>{"use strict";Object.defineProperty(k9,"__esModule",{value:!0});k9.createProtectedApi=yie;var cg=ew();function yie(r){let e=r.privateApiClient,t=r.emitStart,n=r.emitSuccess,i=r.emitError,s=o=>{if(!e)throw new cg.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${o} requires secret key authentication. Please provide secretKey in configuration.`})};return{async getPaymentById(o){s("getPaymentById"),t("getPaymentById",{id:o});try{let a=await e.get(`/sdk/payments/${o}`);return n("getPaymentById",{id:o}),a}catch(a){throw i("getPaymentById",a),a}},async listPayments(){s("listPayments"),t("listPayments");try{let o=await e.get("/sdk/payments");return n("listPayments",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("listPayments",o),o}},async getPaymentIntentById(o){s("getPaymentIntentById"),t("getPaymentIntentById",{id:o});try{let a=await e.get(`/sdk/payment-intents/${o}`);return n("getPaymentIntentById",{id:o}),a}catch(a){throw i("getPaymentIntentById",a),a}},async getInvoiceById(o){s("getInvoiceById"),t("getInvoiceById",{id:o});try{let a=await e.get(`/sdk/invoices/${o}`);return n("getInvoiceById",{id:o}),a}catch(a){throw i("getInvoiceById",a),a}},async getTransactionById(o){s("getTransactionById"),t("getTransactionById",{id:o});try{let a=await e.get(`/sdk/transactions/${o}`);return n("getTransactionById",{id:o}),a}catch(a){throw i("getTransactionById",a),a}},async getWalletById(o){s("getWalletById"),t("getWalletById",{id:o});try{let a=await e.get(`/sdk/wallets/${o}`);return n("getWalletById",{id:o}),a}catch(a){throw i("getWalletById",a),a}},async getVerifiedLedgersPrivate(){s("getVerifiedLedgersPrivate"),t("getVerifiedLedgersPrivate");try{let o=await e.get("/sdk/ledgers/verified");return n("getVerifiedLedgersPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getVerifiedLedgersPrivate",o),o}},async getAllLedgersWithPricesPrivate(){s("getAllLedgersWithPricesPrivate"),t("getAllLedgersWithPricesPrivate");try{let o=await e.get("/sdk/ledgers/all-with-prices");return n("getAllLedgersWithPricesPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getAllLedgersWithPricesPrivate",o),o}},async getLedgerInfoPrivate(o){s("getLedgerInfoPrivate"),t("getLedgerInfoPrivate",{idOrCanisterId:o});try{let a=await e.get(`/sdk/ledgers/${o}`);return n("getLedgerInfoPrivate",{idOrCanisterId:o}),a}catch(a){throw i("getLedgerInfoPrivate",a),a}},async getWebhookEventById(o){s("getWebhookEventById"),t("getWebhookEventById",{id:o});try{let a=await e.get(`/sdk/webhook-events/${o}`);return n("getWebhookEventById",{id:o}),a.data}catch(a){throw i("getWebhookEventById",a),a}},async getDetailedAccountInfo(){s("getDetailedAccountInfo"),t("getDetailedAccountInfo");try{let o=await e.get("/sdk/account"),a={id:o.id,name:o.name,email:o.email,isActive:o.isActive,isLive:o.isLive,accountCanisterId:o.accountCanisterId,walletAddress:o.walletAddress,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt)};return n("getDetailedAccountInfo",a),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch detailed account information",details:o});throw i("getDetailedAccountInfo",a),a}},async getTransactionStatus(o){s("getTransactionStatus"),t("getTransactionStatus",{canisterTransactionId:o});try{let a=await e.get(`/sdk/transactions/${o}/status`);return n("getTransactionStatus",a),a}catch(a){let c=new cg.IcpayError({code:"TRANSACTION_STATUS_FETCH_FAILED",message:"Failed to fetch transaction status",details:a});throw i("getTransactionStatus",c),c}},async getPaymentHistory(o={}){s("getPaymentHistory"),t("getPaymentHistory",{request:o});try{let a=new URLSearchParams;o.accountId&&a.append("accountId",o.accountId),o.ledgerCanisterId&&a.append("ledgerCanisterId",o.ledgerCanisterId),o.fromTimestamp&&a.append("fromTimestamp",o.fromTimestamp.toISOString()),o.toTimestamp&&a.append("toTimestamp",o.toTimestamp.toISOString()),o.status&&a.append("status",o.status),o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString());let c=await e.get(`/sdk/payments/history?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentHistory",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENT_HISTORY_FETCH_FAILED",message:"Failed to fetch payment history",details:a});throw i("getPaymentHistory",c),c}},async getPaymentsByPrincipal(o){s("getPaymentsByPrincipal"),t("getPaymentsByPrincipal",{request:o});try{let a=new URLSearchParams;o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString()),o.status&&a.append("status",o.status);let c=await e.get(`/sdk/payments/by-principal/${o.principalId}?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentsByPrincipal",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENTS_BY_PRINCIPAL_FETCH_FAILED",message:"Failed to fetch payments by principal",details:a});throw i("getPaymentsByPrincipal",c),c}},async getAccountWalletBalances(){s("getAccountWalletBalances"),t("getAccountWalletBalances");try{let o=await e.get("/sdk/account/wallet-balances"),a={balances:o.balances.map(c=>({ledgerId:c.ledgerId,ledgerName:c.ledgerName,ledgerSymbol:c.ledgerSymbol,canisterId:c.canisterId,balance:c.balance,formattedBalance:c.formattedBalance,decimals:c.decimals,currentPrice:c.currentPrice,lastPriceUpdate:c.lastPriceUpdate?new Date(c.lastPriceUpdate):void 0,lastUpdated:new Date(c.lastUpdated)})),totalBalancesUSD:o.totalBalancesUSD,lastUpdated:new Date(o.lastUpdated)};return n("getAccountWalletBalances",{count:a.balances.length,totalUSD:a.totalBalancesUSD}),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_WALLET_BALANCES_FETCH_FAILED",message:"Failed to fetch account wallet balances",details:o});throw i("getAccountWalletBalances",a),a}}}}});var Xk=$r(VA=>{"use strict";Object.defineProperty(VA,"__esModule",{value:!0});VA.HttpClient=void 0;var U9=class{constructor(e){this.baseURL=e.baseURL.replace(/\/$/,""),this.defaultHeaders={"Content-Type":"application/json",...e.headers||{}}}setHeader(e,t){t===void 0?delete this.defaultHeaders[e]:this.defaultHeaders[e]=t}async get(e,t){let n=this.resolve(e),i=await fetch(n,{method:"GET",headers:{...this.defaultHeaders,...t||{}}});return this.handleResponse(i)}async post(e,t,n){let i=this.resolve(e),s=await fetch(i,{method:"POST",headers:{...this.defaultHeaders,...n||{}},body:t===void 0?void 0:JSON.stringify(t)});return this.handleResponse(s)}resolve(e){return/^https?:\/\//i.test(e)?e:`${this.baseURL}${e.startsWith("/")?"":"/"}${e}`}async handleResponse(e){let t=await e.text(),i=(e.headers.get("content-type")||"").includes("application/json")&&t?JSON.parse(t):t;if(!e.ok){let s=new Error(`HTTP ${e.status}: ${e.statusText}`);throw s.status=e.status,s.data=i,s}return i}};VA.HttpClient=U9});var eU=$r(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0})});var j9=$r(eo=>{"use strict";var bie=eo&&eo.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),iU=eo&&eo.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&bie(e,r,t)};Object.defineProperty(eo,"__esModule",{value:!0});eo.IcpayWallet=eo.IcpayError=eo.Icpay=void 0;var Mt=ew(),vie=g8(),Aie=B9(),Hh=(_a(),Yd(Ak)),L9=(Kk(),Yd(Vk)),tU=(Gk(),Yd(Qk)),rU=(Zi(),Yd(k8)),Wr=Yk(),Eie=Zk(),nU=Xk(),KA=class{constructor(e){if(this.privateApiClient=null,this.connectedWallet=null,this.icpayCanisterId=null,this.accountInfoCache=null,this.verifiedLedgersCache={data:null,timestamp:0},this.icpLedgerCanisterId="ryjl3-tyaaa-aaaaa-aaaba-cai",this.config={environment:"production",apiUrl:"https://api.icpay.org",debug:!1,enableEvents:!0,...e,onrampDisabled:!0},(0,Wr.debugLog)(this.config.debug||!1,"constructor",{config:this.config}),!this.config.publishableKey&&!this.config.secretKey)throw new Error("Either publishableKey or secretKey must be provided");if(this.icHost=e.icHost||"https://ic0.app",this.connectedWallet=e.connectedWallet||null,this.actorProvider=e.actorProvider,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet,actorProvider:this.actorProvider}),this.wallet=new Aie.IcpayWallet({connectedWallet:this.connectedWallet}),this.events=new vie.IcpayEventCenter,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet}),this.publicApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.publishableKey||this.config.secretKey||""}`}}),(0,Wr.debugLog)(this.config.debug||!1,"publicApiClient created",this.publicApiClient),this.config.secretKey){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.config.secretKey||""}`};this.privateApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:t})}(0,Wr.debugLog)(this.config.debug||!1,"privateApiClient created",this.privateApiClient),this.protected=(0,Eie.createProtectedApi)({privateApiClient:this.privateApiClient,emitStart:(t,n)=>this.emitMethodStart(t,n),emitSuccess:(t,n)=>this.emitMethodSuccess(t,n),emitError:(t,n)=>this.emitMethodError(t,n)})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.config.enableEvents&&this.events.emit(e,t)}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}dispatchEvent(e){return this.events.dispatchEvent(e)}emitError(e){let t=e instanceof Mt.IcpayError?e:new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.UNKNOWN_ERROR,message:e&&(e.message||e.toString())||"Unknown error",details:e});this.config.enableEvents&&this.events.emit("icpay-sdk-error",t)}emitMethodStart(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-start",{name:e,args:t})}emitMethodSuccess(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-success",{name:e,result:t})}emitMethodError(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-error",{name:e,error:t}),this.emitError(t)}hasSecretKey(){return!!this.config.secretKey&&!!this.privateApiClient}requireSecretKey(e){if(!this.hasSecretKey())throw new Mt.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${e} requires secret key authentication. Please provide secretKey and accountId in configuration.`})}async getAccountInfo(){this.emitMethodStart("getAccountInfo");try{let e=await this.publicApiClient.get("/sdk/public/account"),t={id:e.id,name:e.name,isActive:e.isActive,isLive:e.isLive,accountCanisterId:e.accountCanisterId,icpayCanisterId:e.icpayCanisterId,branding:e.branding||null};return this.emitMethodSuccess("getAccountInfo",t),t}catch(e){let t=new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e});throw this.emitMethodError("getAccountInfo",t),t}}async getVerifiedLedgers(){this.emitMethodStart("getVerifiedLedgers");let e=Date.now(),t=3600*1e3;if(this.verifiedLedgersCache.data&&e-this.verifiedLedgersCache.timestamp<t)return this.verifiedLedgersCache.data;try{let i=(await this.publicApiClient.get("/sdk/public/ledgers/verified")).map(s=>({id:s.id,name:s.name,symbol:s.symbol,canisterId:s.canisterId,decimals:s.decimals,logoUrl:s.logoUrl,verified:s.verified,fee:s.fee,currentPrice:s.currentPrice??null,lastPriceUpdate:s.lastPriceUpdate??null}));return this.verifiedLedgersCache={data:i,timestamp:e},this.emitMethodSuccess("getVerifiedLedgers",{count:i.length}),i}catch(n){let i=new Mt.IcpayError({code:"VERIFIED_LEDGERS_FETCH_FAILED",message:"Failed to fetch verified ledgers",details:n});throw this.emitMethodError("getVerifiedLedgers",i),i}}async getLedgerCanisterIdBySymbol(e){if(this.emitMethodStart("getLedgerCanisterIdBySymbol",{symbol:e}),!e||typeof e!="string")throw new Mt.IcpayError({code:"INVALID_LEDGER_SYMBOL",message:"Symbol must be a non-empty string"});let n=(await this.getVerifiedLedgers()).find(s=>s.symbol.toLowerCase()===e.toLowerCase());if(!n)throw new Mt.IcpayError({code:"LEDGER_SYMBOL_NOT_FOUND",message:`Verified ledger with symbol ${e} not found`});let i=n.canisterId;return this.emitMethodSuccess("getLedgerCanisterIdBySymbol",{symbol:e,canisterId:i}),i}async triggerTransactionSync(e){this.emitMethodStart("triggerTransactionSync",{canisterTransactionId:e});try{let t=await this.publicApiClient.get(`/sdk/public/transactions/${e}/sync`);return this.emitMethodSuccess("triggerTransactionSync",t),t}catch(t){let n=new Mt.IcpayError({code:"TRANSACTION_SYNC_TRIGGER_FAILED",message:"Failed to trigger transaction sync from canister",details:t});throw this.emitMethodError("triggerTransactionSync",n),n}}async fetchAccountInfo(){if(this.accountInfoCache)return this.icpayCanisterId=this.accountInfoCache.icpayCanisterId.toString(),this.accountInfoCache;try{let e=await this.publicApiClient.get("/sdk/public/account");return this.accountInfoCache=e,e&&e.icpayCanisterId&&(this.icpayCanisterId=e.icpayCanisterId.toString()),this.accountInfoCache}catch(e){throw new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e})}}async showWalletModal(){this.emitMethodStart("showWalletModal");try{let e=await this.wallet.showConnectionModal();return this.emitMethodSuccess("showWalletModal",e),e}catch(e){throw this.emitMethodError("showWalletModal",e),e}}async connectWallet(e){this.emitMethodStart("connectWallet",{providerId:e});try{let t=await this.wallet.connectToProvider(e);return this.emitMethodSuccess("connectWallet",t),t}catch(t){throw this.emitMethodError("connectWallet",t),t}}getWalletProviders(){this.emitMethodStart("getWalletProviders");let e=this.wallet.getProviders();return this.emitMethodSuccess("getWalletProviders",{count:Array.isArray(e)?e.length:void 0}),e}isWalletProviderAvailable(e){this.emitMethodStart("isWalletProviderAvailable",{providerId:e});let t=this.wallet.isProviderAvailable(e);return this.emitMethodSuccess("isWalletProviderAvailable",{providerId:e,available:t}),t}getAccountAddress(){this.emitMethodStart("getAccountAddress");let e=this.wallet.getAccountAddress();return this.emitMethodSuccess("getAccountAddress",{accountAddress:e}),e}async getLedgerBalance(e){this.emitMethodStart("getLedgerBalance",{ledgerCanisterId:e});try{let t=null;if(this.connectedWallet&&(this.connectedWallet.owner?t=this.connectedWallet.owner:this.connectedWallet.principal&&(t=this.connectedWallet.principal)),!t)throw new Error("No principal available for balance check");let n=rU.Principal.fromText(t),i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(tU.idlFactory,{agent:i,canisterId:e}).icrc1_balance_of({owner:n,subaccount:[]}),a=BigInt(o);return this.emitMethodSuccess("getLedgerBalance",{ledgerCanisterId:e,balance:a.toString()}),a}catch(t){throw this.emitMethodError("getLedgerBalance",t),t}}createPackedMemo(e,t){let n=BigInt(e>>>0)<<BigInt(32)|BigInt(t>>>0);if(n===BigInt(0))return new Uint8Array([0]);let i=[];for(;n>BigInt(0);)i.push(Number(n&BigInt(255))),n>>=BigInt(8);return new Uint8Array(i)}async createPayment(e){this.emitMethodStart("createPayment",{request:{...e,amount:typeof e.amount=="string"?e.amount:String(e.amount)}});try{(0,Wr.debugLog)(this.config.debug||!1,"createPayment start",{request:e});let t=e.ledgerCanisterId;if(!t&&e.symbol&&(t=await this.getLedgerCanisterIdBySymbol(e.symbol)),!t){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("createPayment",P),P}let n=e.accountCanisterId;if(n||((0,Wr.debugLog)(this.config.debug||!1,"fetching account info for accountCanisterId"),n=(await this.getAccountInfo()).accountCanisterId.toString(),(0,Wr.debugLog)(this.config.debug||!1,"accountCanisterId resolved",{accountCanisterId:n})),this.icpayCanisterId||await this.fetchAccountInfo(),!this.icpayCanisterId)try{let P=await this.getAccountInfo();P?.icpayCanisterId&&(this.icpayCanisterId=P.icpayCanisterId.toString())}catch{}if(!this.icpayCanisterId||typeof this.icpayCanisterId!="string"){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Could not resolve ICPay canister ID from account info",details:{accountInfoCache:this.accountInfoCache}});throw this.emitMethodError("createPayment",P),P}let i=this.icpayCanisterId,s=this.icHost,o;if((e.onrampPayment===!0||this.config.onrampPayment===!0)&&this.config.onrampDisabled!==!0){if(t!==this.icpLedgerCanisterId){let B=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Onramp is only supported for ICP ledger",details:{provided:t,expected:this.icpLedgerCanisterId}});throw this.emitError(B),B}let P=e.amountUsd;if(P==null)try{let B=await this.calculateTokenAmountFromUSD({usdAmount:1,ledgerCanisterId:t}),g=B.currentPrice,m=(typeof e.amount=="string",Number(e.amount));P=g*(m/Math.pow(10,B.decimals))}catch{}let S=null,z=null;try{(0,Wr.debugLog)(this.config.debug||!1,"creating onramp payment intent");let B=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,metadata:e.metadata||{},onrampPayment:!0,widgetParams:e.widgetParams||{},amountUsd:typeof P=="string"?P:P?.toFixed(2)});S=B?.paymentIntentId||B?.paymentIntent?.id||null,z=B?.paymentIntentCode??null;let g=B?.onramp||{};return{transactionId:0,status:"pending",amount:e.amount,recipientCanister:this.icpayCanisterId,timestamp:new Date,metadata:{paymentIntentId:S,paymentIntentCode:z,onramp:g}}}catch(B){let g=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create onramp payment intent",details:B,retryable:!0,userAction:"Try again"});throw this.emitError(g),g}}let c=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;if(!c&&e.amountUsd!=null)try{c=(await this.calculateTokenAmountFromUSD({usdAmount:Number(e.amountUsd),ledgerCanisterId:t})).tokenAmountDecimals}catch{}if(!c){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Either amount or amountUsd must be provided"});throw this.emitError(P),P}let l=BigInt(c);(0,Wr.debugLog)(this.config.debug||!1,"checking balance",{ledgerCanisterId:t,requiredAmount:l.toString()});let u=(P,S=8,z="")=>{let B=BigInt(10**S),g=P/B,d=(P%B).toString().padStart(S,"0").replace(/0+$/,"");return`${g}${d?"."+d:""} ${z}`.trim()};try{let P=await this.getLedgerBalance(t);if(P<l){let S=u(l,8,"tokens"),z=u(P,8,"tokens");throw(0,Mt.createBalanceError)(S,z,{required:l,available:P,ledgerCanisterId:t})}(0,Wr.debugLog)(this.config.debug||!1,"balance ok",{actualBalance:P.toString()})}catch{throw new Mt.IcpayError({code:"INSUFFICIENT_BALANCE",message:"Insufficient balance",details:{required:l,available:0}})}let h=null,p=null,w=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;try{(0,Wr.debugLog)(this.config.debug||!1,"creating payment intent");let P=this.connectedWallet?.owner||this.connectedWallet?.principal?.toString();if(!P)throw new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.WALLET_NOT_CONNECTED,message:"Wallet must be connected to create payment intent",details:{connectedWallet:this.connectedWallet},retryable:!1,userAction:"Connect your wallet first"});let S=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,expectedSenderPrincipal:P,metadata:e.metadata||{},amountUsd:e.amountUsd});h=S?.paymentIntent?.id||null,p=S?.paymentIntent?.intentCode??null,w=S?.paymentIntent?.amount||w,(0,Wr.debugLog)(this.config.debug||!1,"payment intent created",{paymentIntentId:h,paymentIntentCode:p,expectedSenderPrincipal:P,resolvedAmountStr:w}),h&&this.emit("icpay-sdk-transaction-created",{paymentIntentId:h,amount:w,ledgerCanisterId:t,expectedSenderPrincipal:P})}catch(P){let S=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create payment intent. Please try again.",details:P,retryable:!0,userAction:"Try again"});throw this.emitError(S),S}if(!w){let P=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Payment intent did not return amount"});throw this.emitError(P),P}let y=BigInt(w);try{let P=parseInt(n);!isNaN(P)&&p!=null&&(o=this.createPackedMemo(P,Number(p)),(0,Wr.debugLog)(this.config.debug||!1,"built packed memo",{accountCanisterId:P,paymentIntentCode:p})),(0,Wr.debugLog)(this.config.debug||!1,"memo",{memo:o})}catch{}let v;t===this.icpLedgerCanisterId?((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer (ICP)"),v=await this.sendFundsToLedger(t,i,y,o,s)):((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer"),v=await this.sendFundsToLedger(t,i,y,o,s));let C=v?.Ok?.toString()||v?.blockIndex?.toString()||`temp-${Date.now()}`;(0,Wr.debugLog)(this.config.debug||!1,"transfer result",{blockIndex:C});let N,O=null;try{(0,Wr.debugLog)(this.config.debug||!1,"notifying canister about ledger tx");let P=await this.notifyLedgerTransaction(this.icpayCanisterId,t,BigInt(C));typeof P=="string"?N=parseInt(P,10):(N=parseInt(P.id,10),O=P),(0,Wr.debugLog)(this.config.debug||!1,"canister notified",{canisterTransactionId:N})}catch{N=parseInt(C,10),(0,Wr.debugLog)(this.config.debug||!1,"notify failed, using blockIndex as tx id",{canisterTransactionId:N})}let L=null;if(O&&O.status)L={status:O.status};else try{(0,Wr.debugLog)(this.config.debug||!1,"polling transaction status (public)",{canisterTransactionId:N}),L=await this.pollTransactionStatus(this.icpayCanisterId,N,n,Number(C),2e3,30),(0,Wr.debugLog)(this.config.debug||!1,"poll done",{status:L})}catch{L={status:"pending"},(0,Wr.debugLog)(this.config.debug||!1,"poll failed, falling back to pending")}let j="pending";if(L&&typeof L=="object"&&L.status)if(typeof L.status=="object"){let P=Object.keys(L.status);if(P.length>0){let S=P[0].toLowerCase();(S==="completed"||S==="failed")&&(j=S)}}else{let P=L.status;(P==="completed"||P==="failed")&&(j=P)}let q;q=await this.performNotifyPaymentIntent({paymentIntentId:h,canisterTransactionId:N?.toString(),maxAttempts:99999,delayMs:1e3});let D=q?.paymentIntent?.status||q?.payment?.status||q?.status;if(typeof D=="string"){let P=D.toLowerCase();P==="completed"||P==="succeeded"?j="completed":P==="failed"||P==="canceled"||P==="cancelled"?j="failed":j="pending"}let F={transactionId:N,status:j,amount:y.toString(),recipientCanister:t,timestamp:new Date,description:"Fund transfer",metadata:e.metadata,payment:q};if((0,Wr.debugLog)(this.config.debug||!1,"createPayment done",F),j==="completed"){let P=q?.payment?.requestedAmount||null,S=q?.payment?.paidAmount||null;q?.payment?.status==="mismatched"?(this.emit("icpay-sdk-transaction-mismatched",{...F,requestedAmount:P,paidAmount:S}),this.emit("icpay-sdk-transaction-updated",{...F,status:"mismatched",requestedAmount:P,paidAmount:S})):this.emit("icpay-sdk-transaction-completed",F)}else j==="failed"?this.emit("icpay-sdk-transaction-failed",F):this.emit("icpay-sdk-transaction-updated",F);return this.emitMethodSuccess("createPayment",F),F}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("createPayment",t),t;let n=new Mt.IcpayError({code:"TRANSACTION_FAILED",message:"Failed to create payment",details:t});throw this.emitMethodError("createPayment",n),n}}async disconnectWallet(){return await this.wallet.disconnect()}isWalletConnected(){return this.wallet.isConnected()}getConnectedWalletProvider(){return this.wallet.getConnectedProvider()}async pollTransactionStatus(e,t,n,i,s=2e3,o=30){this.emitMethodStart("pollTransactionStatus",{canisterId:e,transactionId:t,accountCanisterId:n,indexReceived:i,intervalMs:s,maxAttempts:o});for(let c=0;c<o;c++)try{let l=await this.getTransactionStatusPublic(e,t,i,n);if(Array.isArray(l)&&l.length>0){let u=l[0];if(u&&typeof u=="object"&&u.status){let h=u.status;if(this.isTransactionCompleted(h))return u}}if(l&&l.status&&this.isTransactionCompleted(l.status))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;if(l&&typeof l=="object"&&(l.Ok||l.Err))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;c<o-1&&await new Promise(u=>setTimeout(u,s))}catch(l){c===o-1&&this.emitMethodError("pollTransactionStatus",l),c<o-1&&await new Promise(u=>setTimeout(u,s))}let a=new Error("Transaction status polling timed out");throw this.emitMethodError("pollTransactionStatus",a),a}isTransactionCompleted(e){if(!e)return!1;if(typeof e=="object"){let t=Object.keys(e);if(t.length>0)return t[0].toLowerCase()==="completed"}return typeof e=="string"?e.toLowerCase()==="completed":!1}async notifyLedgerTransaction(e,t,n){this.emitMethodStart("notifyLedgerTransaction",{canisterId:e,ledgerCanisterId:t,blockIndex:n.toString()});let i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(L9.idlFactory,{agent:i,canisterId:e}).notify_ledger_transaction({ledger_canister_id:t,block_index:n});if(o&&o.Ok)return this.emitMethodSuccess("notifyLedgerTransaction",{result:o.Ok}),o.Ok;if(o&&o.Err){let a=new Error(o.Err);throw this.emitMethodError("notifyLedgerTransaction",a),a}else{let a=new Error("Unexpected canister notify result");throw this.emitMethodError("notifyLedgerTransaction",a),a}}async getTransactionStatusPublic(e,t,n,i){this.emitMethodStart("getTransactionStatusPublic",{canisterId:e,canisterTransactionId:t,indexReceived:n,accountCanisterId:i});let s=new Hh.HttpAgent({host:this.icHost}),o=Hh.Actor.createActor(L9.idlFactory,{agent:s,canisterId:e}),a=parseInt(i),l=await o.get_transaction_status_public(a,BigInt(t),[n])||{status:"pending"};return this.emitMethodSuccess("getTransactionStatusPublic",l),l}async sendFundsToLedger(e,t,n,i,s){this.emitMethodStart("sendFundsToLedger",{ledgerCanisterId:e,toPrincipal:t,amount:n.toString(),hasMemo:!!i});let o;if(this.actorProvider)o=this.actorProvider(e,tU.idlFactory);else{let c=new Error("actorProvider is required for sending funds");throw this.emitMethodError("sendFundsToLedger",c),c}let a=await o.icrc1_transfer({to:{owner:rU.Principal.fromText(t),subaccount:[]},amount:n,fee:[],memo:i?[i]:[],from_subaccount:[],created_at_time:[]});return this.emitMethodSuccess("sendFundsToLedger",a),a}async getTransactionByFilter(e){this.emitMethodStart("getTransactionByFilter",{transactionId:e});try{this.icpayCanisterId||await this.fetchAccountInfo();let t=new Hh.HttpAgent({host:this.icHost}),n=Hh.Actor.createActor(L9.idlFactory,{agent:t,canisterId:this.icpayCanisterId}),i=BigInt(e),s=await n.get_transactions({account_canister_id:[],ledger_canister_id:[],from_timestamp:[],to_timestamp:[],from_id:[],status:[],limit:[],offset:[]});if(s&&s.transactions){let o=s.transactions.find(a=>a.id.toString()===e.toString());return this.emitMethodSuccess("getTransactionByFilter",{found:!!o}),o}return this.emitMethodSuccess("getTransactionByFilter",{found:!1}),null}catch(t){throw this.emitMethodError("getTransactionByFilter",t),t}}async getAllLedgerBalances(){this.emitMethodStart("getAllLedgerBalances");try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balances"});let e=await this.getVerifiedLedgers(),t=[],n=0;for(let s of e)try{let o=await this.getLedgerBalance(s.canisterId),a=this.formatBalance(o.toString(),s.decimals),c={ledgerId:s.id,ledgerName:s.name,ledgerSymbol:s.symbol,canisterId:s.canisterId,balance:o.toString(),formattedBalance:a,decimals:s.decimals,currentPrice:s.currentPrice||void 0,lastPriceUpdate:s.lastPriceUpdate?new Date(s.lastPriceUpdate):void 0,lastUpdated:new Date};if(t.push(c),s.currentPrice&&o>0){let l=parseFloat(a);n+=l*s.currentPrice}}catch(o){this.emit("icpay-sdk-method-error",{name:"getAllLedgerBalances.getLedgerBalance",error:o,ledgerSymbol:s.symbol,ledgerCanisterId:s.canisterId})}let i={balances:t,totalBalancesUSD:n>0?n:void 0,lastUpdated:new Date};return this.emitMethodSuccess("getAllLedgerBalances",{count:t.length,totalUSD:i.totalBalancesUSD}),i}catch(e){let t=new Mt.IcpayError({code:"BALANCES_FETCH_FAILED",message:"Failed to fetch all ledger balances",details:e});throw this.emitMethodError("getAllLedgerBalances",t),t}}async getSingleLedgerBalance(e){this.emitMethodStart("getSingleLedgerBalance",{ledgerCanisterId:e});try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balance"});let n=(await this.getVerifiedLedgers()).find(a=>a.canisterId===e);if(!n)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger with canister ID ${e} not found or not verified`});let i=await this.getLedgerBalance(e),s=this.formatBalance(i.toString(),n.decimals),o={ledgerId:n.id,ledgerName:n.name,ledgerSymbol:n.symbol,canisterId:n.canisterId,balance:i.toString(),formattedBalance:s,decimals:n.decimals,currentPrice:n.currentPrice||void 0,lastPriceUpdate:n.lastPriceUpdate?new Date(n.lastPriceUpdate):void 0,lastUpdated:new Date};return this.emitMethodSuccess("getSingleLedgerBalance",{ledgerCanisterId:e,balance:o.balance}),o}catch(t){let n=new Mt.IcpayError({code:"SINGLE_BALANCE_FETCH_FAILED",message:`Failed to fetch balance for ledger ${e}`,details:t});throw this.emitMethodError("getSingleLedgerBalance",n),n}}async calculateTokenAmountFromUSD(e){this.emitMethodStart("calculateTokenAmountFromUSD",{usdAmount:e.usdAmount,ledgerCanisterId:e.ledgerCanisterId,ledgerSymbol:e.ledgerSymbol});try{let{usdAmount:t,ledgerCanisterId:n,ledgerSymbol:i}=e;if(t<=0)throw new Mt.IcpayError({code:"INVALID_USD_AMOUNT",message:"USD amount must be greater than 0"});let o=(await this.getVerifiedLedgers()).find(u=>u.canisterId===n||i&&u.symbol===i);if(!o)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger not found for canister ID ${n} or symbol ${i}`});if(!o.currentPrice||o.currentPrice<=0)throw new Mt.IcpayError({code:"PRICE_NOT_AVAILABLE",message:`Current price not available for ledger ${o.symbol}`});let a=t/o.currentPrice,c=Math.floor(a*Math.pow(10,o.decimals)).toString(),l={usdAmount:t,ledgerCanisterId:o.canisterId,ledgerSymbol:o.symbol,ledgerName:o.name,currentPrice:o.currentPrice,priceTimestamp:o.lastPriceUpdate?new Date(o.lastPriceUpdate):new Date,tokenAmountHuman:a.toFixed(o.decimals),tokenAmountDecimals:c,decimals:o.decimals};return this.emitMethodSuccess("calculateTokenAmountFromUSD",{ledgerCanisterId:l.ledgerCanisterId,tokenAmountDecimals:c}),l}catch(t){let n=new Mt.IcpayError({code:"PRICE_CALCULATION_FAILED",message:"Failed to calculate token amount from USD",details:t});throw this.emitMethodError("calculateTokenAmountFromUSD",n),n}}async getLedgerInfo(e){this.emitMethodStart("getLedgerInfo",{ledgerCanisterId:e});try{let t=await this.publicApiClient.get(`/sdk/public/ledgers/${e}`),n={id:t.id,name:t.name,symbol:t.symbol,canisterId:t.canisterId,standard:t.standard,decimals:t.decimals,logoUrl:t.logoUrl??null,verified:t.verified,fee:t.fee??null,network:t.network,description:t.description??null,lastBlockIndex:t.lastBlockIndex??null,coingeckoId:t.coingeckoId??null,currentPrice:t.currentPrice??null,priceFetchMethod:t.priceFetchMethod??null,lastPriceUpdate:t.lastPriceUpdate??null,createdAt:t.createdAt,updatedAt:t.updatedAt};return this.emitMethodSuccess("getLedgerInfo",{ledgerCanisterId:e}),n}catch(t){let n=new Mt.IcpayError({code:"LEDGER_INFO_FETCH_FAILED",message:`Failed to fetch ledger info for ${e}`,details:t});throw this.emitMethodError("getLedgerInfo",n),n}}async createPaymentUsd(e){this.emitMethodStart("createPaymentUsd",{request:e});try{let t=typeof e.usdAmount=="string"?parseFloat(e.usdAmount):e.usdAmount,n=e.ledgerCanisterId;if(!n&&e.symbol&&(n=await this.getLedgerCanisterIdBySymbol(e.symbol)),!n){let o=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("createPaymentUsd",o),o}let i={ledgerCanisterId:n,symbol:e.symbol,amountUsd:t,accountCanisterId:e.accountCanisterId,metadata:e.metadata,onrampPayment:e.onrampPayment,widgetParams:e.widgetParams},s=await this.createPayment(i);return this.emitMethodSuccess("createPaymentUsd",s),s}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("createPaymentUsd",t),t;let n=new Mt.IcpayError({code:"SEND_FUNDS_USD_FAILED",message:"Failed to send funds from USD",details:t});throw this.emitMethodError("createPaymentUsd",n),n}}notifyPaymentIntentOnRamp(e){let t=e.paymentIntentId,n=Math.max(1e3,e.intervalMs??5e3),i=e.orderId,s=null,o=null;try{this.emitMethodSuccess("notifyLedgerTransaction",{paymentIntentId:t})}catch{}let a=async()=>{let c=await this.performNotifyPaymentIntent({paymentIntentId:t,orderId:i}),l=(c?.paymentIntent?.status||"").toLowerCase(),u=(c?.payment?.status||"").toLowerCase(),h=l||u||"";h&&h!==o&&(o=h,h==="completed"||h==="succeeded"?this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-completed",{detail:{id:t,status:h}})):h==="mismatched"?(this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-mismatched",{detail:{id:t,status:h,payment:c?.payment}})),this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:h}}))):this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:h}})))};return a().catch(()=>{}),s=setInterval(a,n),{stop:()=>{s&&(clearInterval(s),s=null)}}}async performNotifyPaymentIntent(e){let t=this.publicApiClient,n="/sdk/public/payments/notify",i=e.maxAttempts??1,s=e.delayMs??0;for(let o=1;o<=i;o++)try{(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent",{attempt:o,notifyPath:n,paymentIntentId:e.paymentIntentId,canisterTxId:e.canisterTransactionId});let a={paymentIntentId:e.paymentIntentId};e.canisterTransactionId&&(a.canisterTxId=e.canisterTransactionId),e.orderId&&(a.orderId=e.orderId);let c=await t.post(n,a);if(o===i)return c;let l=c?.paymentIntent?.status||c?.payment?.status||c?.status||"";if(typeof l=="string"){let u=l.toLowerCase();if(u==="completed"||u==="succeeded")return c}s>0&&await new Promise(u=>setTimeout(u,s))}catch(a){let c=a?.response?.status,l=a?.response?.data;(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent error",{attempt:o,status:c,data:l}),o<i&&s>0&&await new Promise(u=>setTimeout(u,s))}return{}}async getAllLedgersWithPrices(){this.emitMethodStart("getAllLedgersWithPrices");try{let t=(await this.publicApiClient.get("/sdk/public/ledgers/all-with-prices")).map(n=>({id:n.id,name:n.name,symbol:n.symbol,canisterId:n.canisterId,standard:n.standard,decimals:n.decimals,logoUrl:n.logoUrl??null,verified:n.verified,fee:n.fee??null,network:n.network,description:n.description??null,lastBlockIndex:n.lastBlockIndex??null,coingeckoId:n.coingeckoId??null,currentPrice:n.currentPrice??null,priceFetchMethod:n.priceFetchMethod??null,lastPriceUpdate:n.lastPriceUpdate??null,createdAt:n.createdAt,updatedAt:n.updatedAt}));return this.emitMethodSuccess("getAllLedgersWithPrices",{count:t.length}),t}catch(e){let t=new Mt.IcpayError({code:"LEDGERS_WITH_PRICES_FETCH_FAILED",message:"Failed to fetch ledgers with price information",details:e});throw this.emitMethodError("getAllLedgersWithPrices",t),t}}formatBalance(e,t){let n=parseFloat(e),i=Math.pow(10,t),s=Math.floor(n/i),a=(n%i).toString().padStart(t,"0").replace(/0+$/,"");return`${s}${a?"."+a:""}`}};eo.Icpay=KA;iU(eU(),eo);var xie=ew();Object.defineProperty(eo,"IcpayError",{enumerable:!0,get:function(){return xie.IcpayError}});var Sie=B9();Object.defineProperty(eo,"IcpayWallet",{enumerable:!0,get:function(){return Sie.IcpayWallet}});iU(g8(),eo);eo.default=KA});var Bie,m$e,aU,cU,lU,oU,ry,Rie,kie,uU,hU=ye(()=>{"use strict";_a();_a();Zi();Bie=(r=>(r[r.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",r[r.InvalidFormat=1]="InvalidFormat",r[r.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",r))(Bie||{}),m$e=BigInt(1e8),aU=r=>new Uint8Array(r),cU=r=>Array.from(r).map(e=>e.charCodeAt(0)),lU=r=>(r instanceof Uint8Array||(r=Uint8Array.from(r)),r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")),oU="abcdefghijklmnopqrstuvwxyz234567",ry=Object.create(null);for(let r=0;r<oU.length;r++)ry[oU[r]]=r;ry[0]=ry.o;ry[1]=ry.i;Rie=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]),kie=r=>{let e=-1;for(let t=0;t<r.length;t++){let n=(r[t]^e)&255;e=Rie[n]^e>>>8}return(e^-1)>>>0},uU=r=>{let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,kie(r),!1),new Uint8Array(e)}});function Lie(){if(!GA&&(GA=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!GA))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return GA(Uie)}function jie(r,e=0){return es[r[e+0]]+es[r[e+1]]+es[r[e+2]]+es[r[e+3]]+"-"+es[r[e+4]]+es[r[e+5]]+"-"+es[r[e+6]]+es[r[e+7]]+"-"+es[r[e+8]]+es[r[e+9]]+"-"+es[r[e+10]]+es[r[e+11]]+es[r[e+12]]+es[r[e+13]]+es[r[e+14]]+es[r[e+15]]}function YA(r,e,t){if(dU.randomUUID&&!r)return dU.randomUUID();r=r||{};let n=r.random||(r.rng||Lie)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,jie(n)}var GA,Uie,es,zie,dU,H9=ye(()=>{"use strict";Uie=new Uint8Array(16);es=[];for(let r=0;r<256;++r)es.push((r+256).toString(16).slice(1));zie=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dU={randomUUID:zie}});var wU={};Re(wU,{StandardSolflareMetaMaskWalletAccount:()=>n4,default:()=>i4});function Die(){if(fU)return F9;fU=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,C=0,N=0,O=y.length;N!==O&&y[N]===0;)N++,v++;for(var L=(O-N)*u+1>>>0,j=new Uint8Array(L);N!==O;){for(var q=y[N],D=0,F=L-1;(q!==0||D<C)&&F!==-1;F--,D++)q+=256*j[F]>>>0,j[F]=q%a>>>0,q=q/a>>>0;if(q!==0)throw new Error("Non-zero carry");C=D,N++}for(var P=L-C;P!==L&&j[P]===0;)P++;for(var S=c.repeat(v);P<L;++P)S+=e.charAt(j[P]);return S}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var v=0,C=0,N=0;y[v]===c;)C++,v++;for(var O=(y.length-v)*l+1>>>0,L=new Uint8Array(O);y[v];){var j=y.charCodeAt(v);if(j>255)return;var q=t[j];if(q===255)return;for(var D=0,F=O-1;(q!==0||D<N)&&F!==-1;F--,D++)q+=a*L[F]>>>0,L[F]=q%256>>>0,q=q/256>>>0;if(q!==0)throw new Error("Non-zero carry");N=D,v++}for(var P=O-N;P!==O&&L[P]===0;)P++;for(var S=new Uint8Array(C+(O-P)),z=C;P!==O;)S[z++]=L[P++];return S}function w(y){var v=p(y);if(v)return v;throw new Error("Non-base"+a+" character")}return{encode:h,decodeUnsafe:p,decode:w}}return F9=r,F9}function qie(){return pU||(pU=1,$9=Die()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),$9}function Q9(r){return r.version===void 0}function W9(r){return Q9(r)?r.serialize({verifySignatures:!1,requireAllSignatures:!1}):r.serialize()}function V9(r){return gU(this,void 0,void 0,function*(){try{return yield r.request({method:"wallet_getSnaps"}),!0}catch{return!1}})}function Fie(){return gU(this,void 0,void 0,function*(){try{let r=window.ethereum;if(!r)return null;if(r.providers&&Array.isArray(r.providers)){let e=r.providers;for(let t of e)if(yield V9(t))return t}if(r.detected&&Array.isArray(r.detected)){let e=r.detected;for(let t of e)if(yield V9(t))return t}return(yield V9(r))?r:null}catch(r){return console.error(r),null}})}function K9(r){return mU.includes(r)}var F9,fU,$9,pU,Hie,fl,gU,$ie,Wie,Vie,Kie,mU,lg,ug,ZA,XA,JA,e4,t4,r4,Qie,Gie,n4,Sc,i4,yU=ye(()=>{"use strict";hg();H9();Hie=qie(),fl=co(Hie);gU=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};$ie="solana:mainnet",Wie="solana:devnet",Vie="solana:testnet",Kie="solana:localnet",mU=[$ie,Wie,Vie,Kie];lg=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ug=function(r,e,t,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 e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Qie=mU,Gie=[G9,Z9,Y9],n4=class r{get address(){return lg(this,ZA,"f")}get publicKey(){return lg(this,XA,"f").slice()}get chains(){return lg(this,JA,"f").slice()}get features(){return lg(this,e4,"f").slice()}get label(){return lg(this,t4,"f")}get icon(){return lg(this,r4,"f")}constructor({address:e,publicKey:t,label:n,icon:i}){ZA.set(this,void 0),XA.set(this,void 0),JA.set(this,void 0),e4.set(this,void 0),t4.set(this,void 0),r4.set(this,void 0),new.target===r&&Object.freeze(this),ug(this,ZA,e,"f"),ug(this,XA,t,"f"),ug(this,JA,Qie,"f"),ug(this,e4,Gie,"f"),ug(this,t4,n,"f"),ug(this,r4,i,"f")}};ZA=new WeakMap,XA=new WeakMap,JA=new WeakMap,e4=new WeakMap,t4=new WeakMap,r4=new WeakMap;Sc=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},i4=class r extends Cu{constructor(e){super(),this._network="mainnet-beta",this._iframeParams={},this._element=null,this._iframe=null,this._publicKey=null,this._account=null,this._isConnected=!1,this._connectHandler=null,this._messageHandlers={},this._handleEvent=t=>{var n,i;switch(t.type){case"connect":{this._collapseIframe(),!((n=t.data)===null||n===void 0)&&n.publicKey?(this._publicKey=t.data.publicKey,this._isConnected=!0,this._connectHandler&&(this._connectHandler.resolve(),this._connectHandler=null),this._connected()):(this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected());return}case"disconnect":{this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected();return}case"accountChanged":{!((i=t.data)===null||i===void 0)&&i.publicKey?(this._publicKey=t.data.publicKey,this.emit("accountChanged",this.publicKey),this._standardConnected()):(this.emit("accountChanged",void 0),this._standardDisconnected());return}default:return}},this._handleResize=t=>{t.resizeMode==="full"?t.params.mode==="fullscreen"?this._expandIframe():t.params.mode==="hide"&&this._collapseIframe():t.resizeMode==="coordinates"&&this._resizeIframe(t.params)},this._handleMessage=t=>{var n;if(((n=t.data)===null||n===void 0?void 0:n.channel)!=="solflareIframeToWalletAdapter")return;let i=t.data.data||{};if(i.type==="event")this._handleEvent(i.event);else if(i.type==="resize")this._handleResize(i);else if(i.type==="response"&&this._messageHandlers[i.id]){let{resolve:s,reject:o}=this._messageHandlers[i.id];delete this._messageHandlers[i.id],i.error?o(i.error):s(i.result)}},this._removeElement=()=>{this._element&&(this._element.remove(),this._element=null)},this._removeDanglingElements=()=>{let t=document.getElementsByClassName("solflare-metamask-wallet-adapter-iframe");for(let n of t)n.parentElement&&n.remove()},this._injectElement=()=>{this._removeElement(),this._removeDanglingElements();let t=Object.assign(Object.assign({},this._iframeParams),{mm:!0,v:1,cluster:this._network||"mainnet-beta",origin:window.location.origin||"",title:document.title||""}),n=Object.keys(t).map(s=>`${s}=${encodeURIComponent(t[s])}`).join("&"),i=`${r.IFRAME_URL}?${n}`;this._element=document.createElement("div"),this._element.className="solflare-metamask-wallet-adapter-iframe",this._element.innerHTML=`
55
55
  <iframe src='${i}' style='position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; border: none; border-radius: 0; z-index: 99999; color-scheme: auto;' allowtransparency='true'></iframe>
56
56
  `,document.body.appendChild(this._element),this._iframe=this._element.querySelector("iframe"),window.addEventListener("message",this._handleMessage,!1)},this._collapseIframe=()=>{this._iframe&&(this._iframe.style.top="",this._iframe.style.right="",this._iframe.style.height="2px",this._iframe.style.width="2px")},this._expandIframe=()=>{this._iframe&&(this._iframe.style.top="0px",this._iframe.style.bottom="0px",this._iframe.style.left="0px",this._iframe.style.right="0px",this._iframe.style.width="100%",this._iframe.style.height="100%")},this._resizeIframe=t=>{this._iframe&&(this._iframe.style.top=isFinite(t.top)?`${t.top}px`:"",this._iframe.style.bottom=isFinite(t.bottom)?`${t.bottom}px`:"",this._iframe.style.left=isFinite(t.left)?`${t.left}px`:"",this._iframe.style.right=isFinite(t.right)?`${t.right}px`:"",this._iframe.style.width=isFinite(t.width)?`${t.width}px`:t.width,this._iframe.style.height=isFinite(t.height)?`${t.height}px`:t.height)},this._sendIframeMessage=t=>{if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");return new Promise((n,i)=>{var s,o;let a=YA();this._messageHandlers[a]={resolve:n,reject:i},(o=(s=this._iframe)===null||s===void 0?void 0:s.contentWindow)===null||o===void 0||o.postMessage({channel:"solflareWalletAdapterToIframe",data:Object.assign({id:a},t)},"*")})},this._connected=()=>{this._isConnected=!0,this.emit("connect",this.publicKey),this._standardConnected()},this._disconnected=()=>{this._publicKey=null,this._isConnected=!1,window.removeEventListener("message",this._handleMessage,!1),this._removeElement(),this.emit("disconnect"),this._standardDisconnected()},this._standardConnected=()=>{if(!this.publicKey)return;let t=this.publicKey.toString();(!this._account||this._account.address!==t)&&(this._account=new n4({address:t,publicKey:this.publicKey.toBytes()}),this.emit("standard_change",{accounts:this.standardAccounts}))},this._standardDisconnected=()=>{this._account&&(this._account=null,this.emit("standard_change",{accounts:this.standardAccounts}))},e?.network&&(this._network=e?.network),window.SolflareMetaMaskParams&&(this._iframeParams=Object.assign(Object.assign({},this._iframeParams),window.SolflareMetaMaskParams)),e?.params&&(this._iframeParams=Object.assign(Object.assign({},this._iframeParams),e?.params))}get publicKey(){return this._publicKey?new ht(this._publicKey):null}get standardAccount(){return this._account}get standardAccounts(){return this._account?[this._account]:[]}get isConnected(){return this._isConnected}get connected(){return this.isConnected}get autoApprove(){return!1}connect(){return Sc(this,void 0,void 0,function*(){this.connected||(this._injectElement(),yield new Promise((e,t)=>{this._connectHandler={resolve:e,reject:t}}))})}disconnect(){return Sc(this,void 0,void 0,function*(){yield this._sendIframeMessage({method:"disconnect"}),this._disconnected()})}signTransaction(e){var t;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let n=W9(e),i=yield this._sendIframeMessage({method:"signTransactionV2",params:{transaction:fl.encode(n)}}),{transaction:s}=i;return Q9(e)?ao.from(fl.decode(s)):Go.deserialize(fl.decode(s))}catch(n){throw new Error(((t=n?.toString)===null||t===void 0?void 0:t.call(n))||"Failed to sign transaction")}})}signAllTransactions(e){var t;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let n=e.map(s=>W9(s)),{transactions:i}=yield this._sendIframeMessage({method:"signAllTransactionsV2",params:{transactions:n.map(s=>fl.encode(s))}});return i.map((s,o)=>Q9(e[o])?ao.from(fl.decode(s)):Go.deserialize(fl.decode(s)))}catch(n){throw new Error(((t=n?.toString)===null||t===void 0?void 0:t.call(n))||"Failed to sign transactions")}})}signAndSendTransaction(e,t){var n;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let i=W9(e),{signature:s}=yield this._sendIframeMessage({method:"signAndSendTransaction",params:{transaction:fl.encode(i),options:t}});return s}catch(i){throw new Error(((n=i?.toString)===null||n===void 0?void 0:n.call(i))||"Failed to sign and send transaction")}})}signMessage(e,t="utf8"){var n;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let{signature:i}=yield this._sendIframeMessage({method:"signMessage",params:{data:fl.encode(e),display:t}});return Uint8Array.from(fl.decode(i))}catch(i){throw new Error(((n=i?.toString)===null||n===void 0?void 0:n.call(i))||"Failed to sign message")}})}sign(e,t="utf8"){return Sc(this,void 0,void 0,function*(){return yield this.signMessage(e,t)})}static isSupported(){return Sc(this,void 0,void 0,function*(){return!!(yield Fie())})}standardSignAndSendTransaction(...e){return Sc(this,void 0,void 0,function*(){if(!this.connected)throw new Error("not connected");let t=[];if(e.length===1){let{transaction:n,account:i,chain:s,options:o}=e[0],{minContextSlot:a,preflightCommitment:c,skipPreflight:l,maxRetries:u}=o||{};if(i!==this._account)throw new Error("invalid account");if(!K9(s))throw new Error("invalid chain");let h=yield this.signAndSendTransaction(Go.deserialize(n),{preflightCommitment:c,minContextSlot:a,maxRetries:u,skipPreflight:l});t.push({signature:fl.decode(h)})}else if(e.length>1)for(let n of e)t.push(...yield this.standardSignAndSendTransaction(n));return t})}standardSignTransaction(...e){return Sc(this,void 0,void 0,function*(){if(!this.connected)throw new Error("not connected");let t=[];if(e.length===1){let{transaction:n,account:i,chain:s}=e[0];if(i!==this._account)throw new Error("invalid account");if(s&&!K9(s))throw new Error("invalid chain");let o=yield this.signTransaction(Go.deserialize(n));t.push({signedTransaction:o.serialize()})}else if(e.length>1){let n;for(let o of e){if(o.account!==this._account)throw new Error("invalid account");if(o.chain){if(!K9(o.chain))throw new Error("invalid chain");if(n){if(o.chain!==n)throw new Error("conflicting chain")}else n=o.chain}}let i=e.map(({transaction:o})=>Go.deserialize(o)),s=yield this.signAllTransactions(i);t.push(...s.map(o=>({signedTransaction:o.serialize()})))}return t})}standardSignMessage(...e){return Sc(this,void 0,void 0,function*(){if(!this.connected)throw new Error("not connected");let t=[];if(e.length===1){let{message:n,account:i}=e[0];if(i!==this._account)throw new Error("invalid account");let s=yield this.signMessage(n);t.push({signedMessage:n,signature:s})}else if(e.length>1)for(let n of e)t.push(...yield this.standardSignMessage(n));return t})}};i4.IFRAME_URL="https://widget.solflare.com/"});var SU={};Re(SU,{default:()=>dse});function Zie(){if(bU)return X9;bU=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,C=0,N=0,O=y.length;N!==O&&y[N]===0;)N++,v++;for(var L=(O-N)*u+1>>>0,j=new Uint8Array(L);N!==O;){for(var q=y[N],D=0,F=L-1;(q!==0||D<C)&&F!==-1;F--,D++)q+=256*j[F]>>>0,j[F]=q%a>>>0,q=q/a>>>0;if(q!==0)throw new Error("Non-zero carry");C=D,N++}for(var P=L-C;P!==L&&j[P]===0;)P++;for(var S=c.repeat(v);P<L;++P)S+=e.charAt(j[P]);return S}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var v=0,C=0,N=0;y[v]===c;)C++,v++;for(var O=(y.length-v)*l+1>>>0,L=new Uint8Array(O);y[v];){var j=y.charCodeAt(v);if(j>255)return;var q=t[j];if(q===255)return;for(var D=0,F=O-1;(q!==0||D<N)&&F!==-1;F--,D++)q+=a*L[F]>>>0,L[F]=q%256>>>0,q=q/256>>>0;if(q!==0)throw new Error("Non-zero carry");N=D,v++}for(var P=O-N;P!==O&&L[P]===0;)P++;for(var S=new Uint8Array(C+(O-P)),z=C;P!==O;)S[z++]=L[P++];return S}function w(y){var v=p(y);if(v)return v;throw new Error("Non-base"+a+" character")}return{encode:h,decodeUnsafe:p,decode:w}}return X9=r,X9}function Xie(){return vU||(vU=1,J9=Zie()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),J9}function rse(r){return typeof r=="string"}function nse(r){return ise(r)&&sse(r.postMessage)}function ise(r){return typeof r=="object"&&r!==null}function sse(r){return typeof r=="function"}function ny(r){return r.version===void 0}var Yie,xU,X9,bU,J9,vU,Jie,Pa,ese,r7,e7,t7,AU,tse,ose,Pf,Bf,ase,cse,n7,dg,fg,EU,lse,use,iy,Fh,$h,hse,dse,CU=ye(()=>{"use strict";hg();H9();Yie=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),xU=(function(r){Yie(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(Cu);Jie=Xie(),Pa=co(Jie),ese=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),r7=function(){return r7=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},r7.apply(this,arguments)},e7=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},t7=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},AU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},tse=(function(r){ese(e,r);function e(t,n){var i=r.call(this)||this;if(i._handleMessage=function(s){if(i._injectedProvider&&s.source===window||s.origin===i._providerUrl.origin&&s.source===i._popup){if(s.data.method==="connected"){var o=new ht(s.data.params.publicKey);(!i._publicKey||!i._publicKey.equals(o))&&(i._publicKey&&!i._publicKey.equals(o)&&i._handleDisconnect(),i._publicKey=o,i._autoApprove=!!s.data.params.autoApprove,i.emit("connect",i._publicKey))}else if(s.data.method==="disconnected")i._handleDisconnect();else if((s.data.result||s.data.error)&&i._responsePromises.has(s.data.id)){var a=AU(i._responsePromises.get(s.data.id),2),c=a[0],l=a[1];s.data.result?c(s.data.result):l(new Error(s.data.error))}}},i._handleConnect=function(){return i._handlerAdded||(i._handlerAdded=!0,window.addEventListener("message",i._handleMessage),window.addEventListener("beforeunload",i.disconnect)),i._injectedProvider?new Promise(function(s){i._sendRequest("connect",{}),s()}):(window.name="parent",i._popup=window.open(i._providerUrl.toString(),"_blank","location,resizable,width=460,height=675"),new Promise(function(s){i.once("connect",s)}))},i._handleDisconnect=function(){i._handlerAdded&&(i._handlerAdded=!1,window.removeEventListener("message",i._handleMessage),window.removeEventListener("beforeunload",i.disconnect)),i._publicKey&&(i._publicKey=null,i.emit("disconnect")),i._responsePromises.forEach(function(s,o){var a=AU(s,2);a[0];var c=a[1];i._responsePromises.delete(o),c("Wallet disconnected")})},i._sendRequest=function(s,o){return e7(i,void 0,void 0,function(){var a,c=this;return t7(this,function(l){if(s!=="connect"&&!this.connected)throw new Error("Wallet not connected");return a=this._nextRequestId,++this._nextRequestId,[2,new Promise(function(u,h){c._responsePromises.set(a,[u,h]),c._injectedProvider?c._injectedProvider.postMessage({jsonrpc:"2.0",id:a,method:s,params:r7({network:c._network},o)}):(c._popup.postMessage({jsonrpc:"2.0",id:a,method:s,params:o},c._providerUrl.origin),c.autoApprove||c._popup.focus())})]})})},i.connect=function(){return i._popup&&i._popup.close(),i._handleConnect()},i.disconnect=function(){return e7(i,void 0,void 0,function(){return t7(this,function(s){switch(s.label){case 0:return this._injectedProvider?[4,this._sendRequest("disconnect",{})]:[3,2];case 1:s.sent(),s.label=2;case 2:return this._popup&&this._popup.close(),this._handleDisconnect(),[2]}})})},i.sign=function(s,o){return e7(i,void 0,void 0,function(){var a,c,l;return t7(this,function(u){switch(u.label){case 0:if(!(s instanceof Uint8Array))throw new Error("Data must be an instance of Uint8Array");return[4,this._sendRequest("sign",{data:s,display:o})];case 1:return a=u.sent(),c=Pa.decode(a.signature),l=new ht(a.publicKey),[2,{signature:c,publicKey:l}]}})})},nse(t))i._injectedProvider=t;else if(rse(t))i._providerUrl=new URL(t),i._providerUrl.hash=new URLSearchParams({origin:window.location.origin,network:n}).toString();else throw new Error("provider parameter must be an injected provider or a URL string.");return i._network=n,i._publicKey=null,i._autoApprove=!1,i._popup=null,i._handlerAdded=!1,i._nextRequestId=1,i._responsePromises=new Map,i}return Object.defineProperty(e.prototype,"publicKey",{get:function(){return this._publicKey},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connected",{get:function(){return this._publicKey!==null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"autoApprove",{get:function(){return this._autoApprove},enumerable:!1,configurable:!0}),e})(Cu);ose=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),Pf=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},Bf=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ase=(function(r){ose(e,r);function e(t,n,i){var s=r.call(this)||this;return s._instance=null,s.handleMessage=function(o){},s._sendRequest=function(o,a){return Pf(s,void 0,void 0,function(){var c,l;return Bf(this,function(u){switch(u.label){case 0:return!((c=this._instance)===null||c===void 0)&&c.sendRequest?[4,this._instance.sendRequest(o,a)]:[3,2];case 1:return[2,u.sent()];case 2:return!((l=this._instance)===null||l===void 0)&&l._sendRequest?[4,this._instance._sendRequest(o,a)]:[3,4];case 3:return[2,u.sent()];case 4:throw new Error("Unsupported version of `@project-serum/sol-wallet-adapter`")}})})},s._handleConnect=function(){s.emit("connect")},s._handleDisconnect=function(){window.clearInterval(s._pollTimer),s.emit("disconnect")},s._network=n,s._provider=i,s}return Object.defineProperty(e.prototype,"publicKey",{get:function(){return this._instance.publicKey||null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connected",{get:function(){return this._instance.connected||!1},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return Pf(this,void 0,void 0,function(){var t=this;return Bf(this,function(n){switch(n.label){case 0:return this._instance=new tse(this._provider,this._network),this._instance.on("connect",this._handleConnect),this._instance.on("disconnect",this._handleDisconnect),this._pollTimer=window.setInterval(function(){var i,s;((s=(i=t._instance)===null||i===void 0?void 0:i._popup)===null||s===void 0?void 0:s.closed)!==!1&&t._handleDisconnect()},200),[4,this._instance.connect()];case 1:return n.sent(),[2]}})})},e.prototype.disconnect=function(){return Pf(this,void 0,void 0,function(){return Bf(this,function(t){switch(t.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return this._instance.removeAllListeners("connect"),this._instance.removeAllListeners("disconnect"),[4,this._instance.disconnect()];case 1:return t.sent(),[2]}})})},e.prototype.signTransaction=function(t){return Pf(this,void 0,void 0,function(){var n;return Bf(this,function(i){switch(i.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._sendRequest("signTransactionV2",{transaction:Pa.encode(t)})];case 1:return n=i.sent().transaction,[2,Pa.decode(n)]}})})},e.prototype.signAllTransactions=function(t){return Pf(this,void 0,void 0,function(){var n;return Bf(this,function(i){switch(i.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._sendRequest("signAllTransactionsV2",{transactions:t.map(function(s){return Pa.encode(s)})})];case 1:return n=i.sent().transactions,[2,n.map(function(s){return Pa.decode(s)})]}})})},e.prototype.signAndSendTransaction=function(t,n){return Pf(this,void 0,void 0,function(){var i;return Bf(this,function(s){switch(s.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._sendRequest("signAndSendTransaction",{transaction:Pa.encode(t),options:n})];case 1:return i=s.sent(),[2,i.signature]}})})},e.prototype.signMessage=function(t,n){return n===void 0&&(n="hex"),Pf(this,void 0,void 0,function(){var i;return Bf(this,function(s){switch(s.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._instance.sign(t,n)];case 1:return i=s.sent().signature,[2,Uint8Array.from(i)]}})})},e})(xU),cse=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),n7=function(){return n7=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},n7.apply(this,arguments)},dg=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},fg=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},EU=(function(r){cse(e,r);function e(t,n){var i=this,s;return i=r.call(this)||this,i._publicKey=null,i._messageHandlers={},i.handleMessage=function(o){if(i._messageHandlers[o.id]){var a=i._messageHandlers[o.id],c=a.resolve,l=a.reject;delete i._messageHandlers[o.id],o.error?l(o.error):c(o.result)}},i._sendMessage=function(o){if(!i.connected)throw new Error("Wallet not connected");return new Promise(function(a,c){var l,u,h=YA();i._messageHandlers[h]={resolve:a,reject:c},(u=(l=i._iframe)===null||l===void 0?void 0:l.contentWindow)===null||u===void 0||u.postMessage({channel:"solflareWalletAdapterToIframe",data:n7({id:h},o)},"*")})},i._iframe=t,i._publicKey=new ht((s=n?.toString)===null||s===void 0?void 0:s.call(n)),i}return Object.defineProperty(e.prototype,"publicKey",{get:function(){return this._publicKey||null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connected",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return dg(this,void 0,void 0,function(){return fg(this,function(t){return[2]})})},e.prototype.disconnect=function(){return dg(this,void 0,void 0,function(){return fg(this,function(t){switch(t.label){case 0:return[4,this._sendMessage({method:"disconnect"})];case 1:return t.sent(),[2]}})})},e.prototype.signTransaction=function(t){var n;return dg(this,void 0,void 0,function(){var i,s;return fg(this,function(o){switch(o.label){case 0:if(!this.connected)throw new Error("Wallet not connected");o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._sendMessage({method:"signTransaction",params:{transaction:Pa.encode(t)}})];case 2:return i=o.sent(),[2,Pa.decode(i)];case 3:throw s=o.sent(),new Error(((n=s?.toString)===null||n===void 0?void 0:n.call(s))||"Failed to sign transaction");case 4:return[2]}})})},e.prototype.signAllTransactions=function(t){var n;return dg(this,void 0,void 0,function(){var i,s;return fg(this,function(o){switch(o.label){case 0:if(!this.connected)throw new Error("Wallet not connected");o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._sendMessage({method:"signAllTransactions",params:{transactions:t.map(function(a){return Pa.encode(a)})}})];case 2:return i=o.sent(),[2,i.map(function(a){return Pa.decode(a)})];case 3:throw s=o.sent(),new Error(((n=s?.toString)===null||n===void 0?void 0:n.call(s))||"Failed to sign transactions");case 4:return[2]}})})},e.prototype.signAndSendTransaction=function(t,n){var i;return dg(this,void 0,void 0,function(){var s,o;return fg(this,function(a){switch(a.label){case 0:if(!this.connected)throw new Error("Wallet not connected");a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this._sendMessage({method:"signAndSendTransaction",params:{transaction:Pa.encode(t),options:n}})];case 2:return s=a.sent(),[2,s];case 3:throw o=a.sent(),new Error(((i=o?.toString)===null||i===void 0?void 0:i.call(o))||"Failed to sign and send transaction");case 4:return[2]}})})},e.prototype.signMessage=function(t,n){var i;return n===void 0&&(n="hex"),dg(this,void 0,void 0,function(){var s,o;return fg(this,function(a){switch(a.label){case 0:if(!this.connected)throw new Error("Wallet not connected");a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this._sendMessage({method:"signMessage",params:{data:t,display:n}})];case 2:return s=a.sent(),[2,Uint8Array.from(Pa.decode(s))];case 3:throw o=a.sent(),new Error(((i=o?.toString)===null||i===void 0?void 0:i.call(o))||"Failed to sign message");case 4:return[2]}})})},e})(xU);lse="1.4.2",use=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),iy=function(){return iy=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},iy.apply(this,arguments)},Fh=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},$h=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},hse=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},dse=(function(r){use(e,r);function e(t){var n=r.call(this)||this;return n._network="mainnet-beta",n._provider=null,n._iframeParams={},n._adapterInstance=null,n._element=null,n._iframe=null,n._connectHandler=null,n._flutterHandlerInterval=null,n._handleEvent=function(i){var s,o,a,c;switch(i.type){case"connect_native_web":{n._collapseIframe(),n._adapterInstance=new ase(n._iframe,n._network,((s=i.data)===null||s===void 0?void 0:s.provider)||n._provider||"https://solflare.com/provider"),n._adapterInstance.on("connect",n._webConnected),n._adapterInstance.on("disconnect",n._webDisconnected),n._adapterInstance.connect(),n._setPreferredAdapter("native_web");return}case"connect":{n._collapseIframe(),n._adapterInstance=new EU(n._iframe,((o=i.data)===null||o===void 0?void 0:o.publicKey)||""),n._adapterInstance.connect(),n._setPreferredAdapter((a=i.data)===null||a===void 0?void 0:a.adapter),n._connectHandler&&(n._connectHandler.resolve(),n._connectHandler=null),n.emit("connect",n.publicKey);return}case"disconnect":{n._connectHandler&&(n._connectHandler.reject(),n._connectHandler=null),n._disconnected(),n.emit("disconnect");return}case"accountChanged":{!((c=i.data)===null||c===void 0)&&c.publicKey?(n._adapterInstance=new EU(n._iframe,i.data.publicKey),n._adapterInstance.connect(),n.emit("accountChanged",n.publicKey)):n.emit("accountChanged",void 0);return}case"collapse":{n._collapseIframe();return}default:return}},n._handleResize=function(i){i.resizeMode==="full"?i.params.mode==="fullscreen"?n._expandIframe():i.params.mode==="hide"&&n._collapseIframe():i.resizeMode==="coordinates"&&n._iframe&&(n._iframe.style.top=isFinite(i.params.top)?"".concat(i.params.top,"px"):"",n._iframe.style.bottom=isFinite(i.params.bottom)?"".concat(i.params.bottom,"px"):"",n._iframe.style.left=isFinite(i.params.left)?"".concat(i.params.left,"px"):"",n._iframe.style.right=isFinite(i.params.right)?"".concat(i.params.right,"px"):"",n._iframe.style.width=isFinite(i.params.width)?"".concat(i.params.width,"px"):i.params.width,n._iframe.style.height=isFinite(i.params.height)?"".concat(i.params.height,"px"):i.params.height)},n._handleMessage=function(i){var s;if(((s=i.data)===null||s===void 0?void 0:s.channel)==="solflareIframeToWalletAdapter"){var o=i.data.data||{};o.type==="event"?n._handleEvent(o.event):o.type==="resize"?n._handleResize(o):o.type==="response"&&n._adapterInstance&&n._adapterInstance.handleMessage(o)}},n._removeElement=function(){n._flutterHandlerInterval!==null&&(clearInterval(n._flutterHandlerInterval),n._flutterHandlerInterval=null),n._element&&(n._element.remove(),n._element=null)},n._removeDanglingElements=function(){var i,s,o=document.getElementsByClassName("solflare-wallet-adapter-iframe");try{for(var a=hse(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.parentElement&&l.remove()}}catch(u){i={error:u}}finally{try{c&&!c.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}},n._injectElement=function(){n._removeElement(),n._removeDanglingElements();var i=iy(iy({},n._iframeParams),{cluster:n._network||"mainnet-beta",origin:window.location.origin||"",title:document.title||"",version:1,sdkVersion:lse}),s=n._getPreferredAdapter();s&&(i.adapter=s),n._provider&&(i.provider=n._provider);var o=Object.keys(i).map(function(c){return"".concat(c,"=").concat(encodeURIComponent(i[c]))}).join("&"),a="".concat(e.IFRAME_URL,"?").concat(o);n._element=document.createElement("div"),n._element.className="solflare-wallet-adapter-iframe",n._element.innerHTML=`
57
57
  <iframe src='`.concat(a,`' referrerPolicy='strict-origin-when-cross-origin' style='position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; border: none; border-radius: 0; z-index: 99999; color-scheme: auto;' allowtransparency='true'></iframe>
@@ -4927,7 +4927,7 @@ Make sure to test your application with a production build as repeat registratio
4927
4927
  0%, 100% { opacity: 1; }
4928
4928
  50% { opacity: 0.7; }
4929
4929
  }
4930
- `;function rf(r,e){if(!r||!e)return;let t=e.primaryColor||void 0,n=e.secondaryColor||void 0,i=(v,C)=>{C&&r.style.setProperty(v,C)};i("--icpay-primary",t),i("--icpay-secondary",n);let s=v=>{if(!v)return null;let C=v.replace("#",""),N=C.length===3?C.split("").map(D=>D+D).join(""):C,O=parseInt(N,16),L=O>>16&255,j=O>>8&255,q=O&255;return{r:L,g:j,b:q}},c=(v=>{let C=s(v);if(!C)return 0;let N=O=>{let L=O/255;return L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4)};return .2126*N(C.r)+.7152*N(C.g)+.0722*N(C.b)})(t||n)>.6,l=e.surfaceColor||(c?"#f3f4f6":"#1f2937"),u=e.surfaceAltColor||(c?"#e5e7eb":"#374151"),h=e.borderColor||(c?"#d1d5db":"#4b5563"),p=e.textColor||(c?"#111827":"#f9fafb"),w=e.accentColor||n||t||(c?"#6b7280":"#9ca3af"),y=e.mutedTextColor||(c?"#6b7280":"#9ca3af");i("--icpay-accent",w),i("--icpay-text",p),i("--icpay-muted",y),i("--icpay-surface",l),i("--icpay-surface-alt",u),i("--icpay-border",h)}var z9=lc(j9(),1),sU=typeof window<"u";function QA(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}function or(r){if(!sU)return{client:{},quoteUsd:async()=>({tokenAmountDecimals:"0"}),sendUsd:async()=>({transactionId:"0",status:"pending"}),startOnrampUsd:async()=>({transactionId:"0",status:"pending",metadata:{onramp:{sessionId:null}}}),notifyIntentUntilComplete:()=>({stop:()=>{}})};QA(r.debug||!1,"Creating SDK with config:",r);let e={publishableKey:r.publishableKey};r.enableEvents!==void 0?e.enableEvents=r.enableEvents:e.enableEvents=!0,r.apiUrl&&(e.apiUrl=r.apiUrl),r.icHost&&(e.icHost=r.icHost),r.actorProvider&&(e.actorProvider=r.actorProvider),r.connectedWallet&&(e.connectedWallet=r.connectedWallet),r.debug!==void 0&&(e.debug=r.debug),QA(r.debug||!1,"Filtered SDK config:",e);try{let a=function(c,l,u){return n.notifyPaymentIntentOnRamp({paymentIntentId:c,intervalMs:l,orderId:u})};var t=a;QA(r.debug||!1,"typeof Icpay:",typeof z9.Icpay);let n=new z9.Icpay(e);if(sU){let c=n,l=u=>{c.addEventListener(u,h=>{window.dispatchEvent(new CustomEvent(u,{detail:h?.detail??h}))})};["icpay-sdk-error","icpay-sdk-transaction-created","icpay-sdk-transaction-updated","icpay-sdk-transaction-completed","icpay-sdk-transaction-failed","icpay-sdk-method-start","icpay-sdk-method-success","icpay-sdk-method-error"].forEach(l)}async function i(c,l){return n.calculateTokenAmountFromUSD({usdAmount:c,ledgerCanisterId:l})}async function s(c,l,u){return n.sendFundsUsd({usdAmount:c,ledgerCanisterId:l,metadata:u})}async function o(c,l,u){return n.sendFundsUsd({usdAmount:c,ledgerCanisterId:l,metadata:u,onrampPayment:!0})}return{client:n,quoteUsd:i,sendUsd:s,startOnrampUsd:o,notifyIntentUntilComplete:a}}catch(n){throw QA(r.debug||!1,"Error creating SDK:",n),n}}var Oi=r=>(e,t)=>{t!==void 0?t.addInitializer((()=>{customElements.define(r,e)})):customElements.define(r,e)};var Cie={attribute:!0,type:String,converter:Km,reflect:!1,hasChanged:h2},Iie=(r=Cie,e,t)=>{let{kind:n,metadata:i}=t,s=globalThis.litPropertyMetadata.get(i);if(s===void 0&&globalThis.litPropertyMetadata.set(i,s=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),s.set(t.name,r),n==="accessor"){let{name:o}=t;return{set(a){let c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,r)},init(a){return a!==void 0&&this.C(o,void 0,r,a),a}}}if(n==="setter"){let{name:o}=t;return function(a){let c=this[o];e.call(this,a),this.requestUpdate(o,c,r)}}throw Error("Unsupported decorator location: "+n)};function Yt(r){return(e,t)=>typeof t=="object"?Iie(r,e,t):((n,i,s)=>{let o=i.hasOwnProperty(s);return i.constructor.createProperty(s,n),o?Object.getOwnPropertyDescriptor(i,s):void 0})(r,e,t)}function Ce(r){return Yt({...r,state:!0,attribute:!1})}var Mf=(r,e,t)=>(t.configurable=!0,t.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(r,e,t),t);function D9(r,e){return(t,n,i)=>{let s=o=>o.renderRoot?.querySelector(r)??null;if(e){let{get:o,set:a}=typeof n=="object"?t:i??(()=>{let c=Symbol();return{get(){return this[c]},set(l){this[c]=l}}})();return Mf(t,n,{get(){let c=o.call(this);return c===void 0&&(c=s(this),(c!==null||this.hasUpdated)&&a.call(this,c)),c}})}return Mf(t,n,{get(){return s(this)}})}}var q9=lc(j9(),1),to={WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",WALLET_USER_CANCELLED:"WALLET_USER_CANCELLED",WALLET_SIGNATURE_REJECTED:"WALLET_SIGNATURE_REJECTED",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",NETWORK_ERROR:"NETWORK_ERROR",API_ERROR:"API_ERROR",LEDGER_NOT_FOUND:"LEDGER_NOT_FOUND",TRANSACTION_FAILED:"TRANSACTION_FAILED",TRANSACTION_TIMEOUT:"TRANSACTION_TIMEOUT",UNKNOWN_ERROR:"UNKNOWN_ERROR"},_ie={onError:r=>{console.error("[ICPay Widget] Error:",r)},onUserCancelled:()=>{console.log("[ICPay Widget] User cancelled the action")},onInsufficientBalance:r=>{console.warn("[ICPay Widget] Insufficient balance:",r.message)},onWalletError:r=>{console.warn("[ICPay Widget] Wallet error:",r.message)},onNetworkError:r=>{console.error("[ICPay Widget] Network error:",r.message)}};function ro(r,e=_ie){r instanceof q9.IcpayError?(e.onError(r),r.isUserCancelled()?e.onUserCancelled?.():r.isBalanceError()?e.onInsufficientBalance?.(r):r.isWalletError()?e.onWalletError?.(r):r.isNetworkError()&&e.onNetworkError?.(r)):(console.error("[ICPay Widget] Unknown error:",r),e.onError(new q9.IcpayError({code:to.UNKNOWN_ERROR,message:r instanceof Error?r.message:"An unknown error occurred",details:r})))}var Nie={[to.WALLET_NOT_CONNECTED]:"Please connect your wallet to continue",[to.WALLET_USER_CANCELLED]:"User have rejected the transfer",[to.WALLET_SIGNATURE_REJECTED]:"User have rejected the transfer",[to.INSUFFICIENT_BALANCE]:"Insufficient balance for this transaction",[to.NETWORK_ERROR]:"Network error. Please try again",[to.API_ERROR]:"Service temporarily unavailable",[to.LEDGER_NOT_FOUND]:"Selected token is not supported",[to.TRANSACTION_FAILED]:"Transaction failed. Please try again",[to.TRANSACTION_TIMEOUT]:"Transaction timed out. Please try again",[to.UNKNOWN_ERROR]:"Something went wrong. Please try again"};function no(r){return Nie[r.code]||r.message||"An error occurred"}function io(r){return!r.isUserCancelled()}function so(r){if(r.userAction)return r.userAction;switch(r.code){case to.WALLET_NOT_CONNECTED:return"Connect Wallet";case to.INSUFFICIENT_BALANCE:return"Add Funds";case to.NETWORK_ERROR:case to.API_ERROR:return"Try Again";default:return null}}function oo(r){return r.isUserCancelled()?"info":r.isBalanceError()||r.isWalletError()?"warning":"error"}function Ur(r,e,t){r&&(t!==void 0?console.log(e,t):console.log(e))}var Tie=[{key:"wallet",label:"Connect Wallet",tooltip:"Awaiting wallet connection",status:"pending"},{key:"init",label:"Initialising ICPay",tooltip:"Initializing payment",status:"pending"},{key:"await",label:"Awaiting payment confirmation",tooltip:"Preparing payment",status:"pending"},{key:"transfer",label:"Transferring funds",tooltip:"Submitting payment",status:"pending"},{key:"verify",label:"Verifying payment",tooltip:"Confirming payment",status:"pending"},{key:"confirm",label:"Payment confirmed",tooltip:"Payment completed",status:"pending"}],Sn=class extends pn{constructor(){super(...arguments);this.open=!1;this.steps=Tie;this.amount=0;this.currency="";this.ledgerSymbol="";this.debug=!1;this.activeIndex=0;this.completed=!1;this.failed=!1;this.errorMessage=null;this.showSuccess=!1;this.showConfetti=!1;this.currentSteps=[];this.currentAmount=0;this.currentCurrency="";this.currentLedgerSymbol="";this.confirmLoadingStartedAt=null;this.progressionTimer=null;this.onMethodStart=t=>{let n=t?.detail?.name||"",i=t?.detail?.type||"";if(Ur(this.debug,"ICPay Progress: Method start event received:",t.detail),n==="sendFunds"||n==="sendFundsUsd"||n==="sendUsd"||n==="pay"||n==="unlock"||n==="tip"||n==="donate"||n==="order"){if(this.open=!0,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.currentSteps=this.currentSteps.map(s=>({...s,status:"pending"})),i==="onramp"){let s=this.getStepIndexByKey("wallet");s>=0&&(this.currentSteps[s]={...this.currentSteps[s],label:"Transak Started",tooltip:"Awaiting Transak information"})}this.setLoadingByKey("wallet"),t?.detail?.amount!==void 0&&(this.currentAmount=t.detail.amount,this.amount=t.detail.amount,Ur(this.debug,"ICPay Progress: Amount updated to:",t.detail.amount)),t?.detail?.currency&&(this.currentCurrency=t.detail.currency,this.currency=t.detail.currency,Ur(this.debug,"ICPay Progress: Currency updated to:",t.detail.currency)),t?.detail?.ledgerSymbol&&(this.currentLedgerSymbol=t.detail.ledgerSymbol,this.ledgerSymbol=t.detail.ledgerSymbol,Ur(this.debug,"ICPay Progress: Current state after method start:",{activeIndex:this.activeIndex,currentAmount:this.currentAmount,currentCurrency:this.currentCurrency,currentLedgerSymbol:this.currentLedgerSymbol})),Ur(this.debug,"ICPay Progress: Waiting for wallet confirmation before starting progression"),this.requestUpdate()}!this.failed&&!this.completed&&(n==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")):n==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")))};this.onMethodSuccess=t=>{let n=t?.detail?.name||"";(n==="sendFunds"||n==="sendFundsUsd"||n==="sendUsd"||n==="pay"||n==="unlock"||n==="tip"||n==="donate"||n==="order")&&this.dispatchEvent(new CustomEvent("icpay-progress-method-success",{detail:{methodName:n,step:this.activeIndex},bubbles:!0})),!this.failed&&!this.completed&&(n==="getLedgerBalance"?(this.completeByKey("wallet"),this.completeByKey("init"),this.setLoadingByKey("await")):n==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):n==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.completeByKey("verify"),this.setLoadingByKey("confirm")))};this.onTransactionCreated=t=>{let n=t?.detail?.transactionId||t?.detail?.id;Ur(this.debug,"ICPay Progress: Transaction created event received:",t.detail),!this.failed&&!this.completed&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")),this.dispatchEvent(new CustomEvent("icpay-progress-transaction-created",{detail:{transactionId:n,step:this.activeIndex},bubbles:!0}))};this.onTransactionUpdated=t=>{let n=t?.detail?.status||"pending",i=t?.detail?.transactionId||t?.detail?.id;Ur(this.debug,"ICPay Progress: Transaction updated event received:",t.detail),!this.failed&&this.completed,this.dispatchEvent(new CustomEvent("icpay-progress-transaction-updated",{detail:{status:n,transactionId:i,step:this.activeIndex},bubbles:!0}))};this.onTransactionCompleted=t=>{let n=t?.detail?.transactionId||t?.detail?.id,i=t?.detail?.status||"completed";Ur(this.debug,"ICPay Progress: Transaction completed event received:",t.detail),Ur(this.debug,"ICPay Progress: Current state when transaction completed:",{activeIndex:this.activeIndex,completed:this.completed,failed:this.failed,showSuccess:this.showSuccess}),this.completeByKey("transfer"),this.completeByKey("await"),this.completeByKey("init"),this.completeByKey("verify"),this.completeByKey("confirm"),this.completed=!0,this.showSuccess=!0,this.showConfetti=!0,this.dispatchEvent(new CustomEvent("icpay-progress-completed",{detail:{transactionId:n,status:i,amount:this.currentAmount||this.amount,currency:this.currentCurrency||this.currency,ledgerSymbol:this.currentLedgerSymbol||this.ledgerSymbol},bubbles:!0})),setTimeout(()=>{this.showConfetti=!1},3e3)};this.onTransactionFailed=t=>{let n=t?.detail?.message||t?.detail?.error?.message||"Transaction failed",i=t?.detail?.error?.code||t?.detail?.code||"UNKNOWN_ERROR",s=t?.detail?.transactionId||t?.detail?.id;Ur(this.debug,"ICPay Progress: Transaction failed event received:",t.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",n),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:n,errorCode:i,transactionId:s,step:this.activeIndex},bubbles:!0}))};this.onTransactionMismatched=t=>{let n=t?.detail?.requestedAmount,i=t?.detail?.paidAmount,s=t?.detail?.transactionId||t?.detail?.id;this.failed=!0;let o=n!=null?String(n):"unknown",a=i!=null?String(i):"unknown";this.errorMessage=`Amount mismatch. Requested ${o}, paid ${a}.`,this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:"MISMATCHED_AMOUNT",transactionId:s,step:this.activeIndex,requestedAmount:n,paidAmount:i},bubbles:!0}))};this.onMethodError=t=>{let n=t?.detail?.name||"",i=t?.detail?.error?.message||t?.detail?.message||"An error occurred",s=t?.detail?.error?.code||t?.detail?.code||"METHOD_ERROR";Ur(this.debug,"ICPay Progress: Method error event received:",t.detail),(n?.startsWith("sendFunds")||n==="sendUsd"||n==="pay"||n==="unlock"||n==="tip"||n==="donate"||n==="order")&&(this.failed=!0,this.errorMessage=this.transformErrorMessage(i),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",i),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-error",{detail:{methodName:n,errorMessage:i,errorCode:s,step:this.activeIndex},bubbles:!0})))};this.onSDKError=t=>{let n=t?.detail?.message||"SDK error occurred",i=t?.detail?.code||"SDK_ERROR";Ur(this.debug,"ICPay Progress: SDK error event received:",t.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",n),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-sdk-error",{detail:{errorMessage:n,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWalletConnected=t=>{let n=t?.detail?.walletType||"unknown";Ur(this.debug,"ICPay Progress: Wallet connected event received:",t.detail),this.completeByKey("wallet"),this.setLoadingByKey("init"),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-connected",{detail:{walletType:n,step:this.activeIndex},bubbles:!0}))};this.onWalletDisconnected=t=>{let n=t?.detail?.walletType||"unknown";Ur(this.debug,"ICPay Progress: Wallet disconnected event received:",t.detail),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-disconnected",{detail:{walletType:n,step:this.activeIndex},bubbles:!0}))};this.onBalanceCheck=t=>{let n=t?.detail?.hasBalance||!1,i=t?.detail?.balance||0;Ur(this.debug,"ICPay Progress: Balance check event received:",t.detail),n||(this.failed=!0,this.errorMessage="Insufficient balance for transaction",this.updateStepStatus(this.activeIndex,"error","Insufficient balance for transaction"),this.stopAutomaticProgression(),this.dispatchEvent(new CustomEvent("icpay-progress-insufficient-balance",{detail:{balance:i,required:this.currentAmount||this.amount,step:this.activeIndex},bubbles:!0})))};this.onLedgerVerified=t=>{let n=t?.detail?.ledgerId||t?.detail?.canisterId,i=t?.detail?.symbol||"unknown";Ur(this.debug,"ICPay Progress: Ledger verified event received:",t.detail),i&&i!=="unknown"&&(this.currentLedgerSymbol=i,this.ledgerSymbol=i),this.dispatchEvent(new CustomEvent("icpay-progress-ledger-verified",{detail:{ledgerId:n,symbol:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetPayment=t=>{let n=t?.detail?.amount,i=t?.detail?.currency,s=t?.detail?.ledgerSymbol;if(Ur(this.debug,"ICPay Progress: Widget payment event received:",t.detail),n!==void 0&&(this.currentAmount=n,this.amount=n),i&&(this.currentCurrency=i,this.currency=i),s&&(this.currentLedgerSymbol=s,this.ledgerSymbol=s),!this.failed){for(let o=this.activeIndex;o<this.currentSteps.length;o++)this.updateStepStatus(o,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-payment",{detail:{amount:n,currency:i,ledgerSymbol:s,step:this.activeIndex},bubbles:!0}))};this.onWidgetError=t=>{let n=t?.detail?.message||"Widget error occurred",i=t?.detail?.code||"WIDGET_ERROR";Ur(this.debug,"ICPay Progress: Widget error event received:",t.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",n),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-widget-error",{detail:{errorMessage:n,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetUnlock=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget unlock event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-unlock",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetTip=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget tip event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-tip",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetDonation=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget donation event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-donation",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetCoffee=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget coffee event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-coffee",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))}}connectedCallback(){super.connectedCallback();try{rf(this,this.theme)}catch{}this.currentSteps=[...this.steps],this.currentAmount=this.amount,this.currentCurrency=this.currency,this.currentLedgerSymbol=this.ledgerSymbol,this.attachSDKEventListeners()}disconnectedCallback(){super.disconnectedCallback(),this.detachSDKEventListeners(),this.stopAutomaticProgression()}updated(t){if(t.has("theme"))try{rf(this,this.theme)}catch{}}attachSDKEventListeners(){window.addEventListener("icpay-sdk-method-start",this.onMethodStart),window.addEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.addEventListener("icpay-sdk-method-error",this.onMethodError),window.addEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.addEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.addEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.addEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.addEventListener("icpay-sdk-error",this.onSDKError),window.addEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.addEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.addEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.addEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.addEventListener("icpay-pay",this.onWidgetPayment),window.addEventListener("icpay-error",this.onWidgetError),window.addEventListener("icpay-unlock",this.onWidgetUnlock),window.addEventListener("icpay-tip",this.onWidgetTip),window.addEventListener("icpay-donation",this.onWidgetDonation),window.addEventListener("icpay-coffee",this.onWidgetCoffee)}detachSDKEventListeners(){window.removeEventListener("icpay-sdk-method-start",this.onMethodStart),window.removeEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.removeEventListener("icpay-sdk-method-error",this.onMethodError),window.removeEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.removeEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.removeEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.removeEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.removeEventListener("icpay-sdk-error",this.onSDKError),window.removeEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.removeEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.removeEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.removeEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.removeEventListener("icpay-pay",this.onWidgetPayment),window.removeEventListener("icpay-error",this.onWidgetError),window.removeEventListener("icpay-unlock",this.onWidgetUnlock),window.removeEventListener("icpay-tip",this.onWidgetTip),window.removeEventListener("icpay-donation",this.onWidgetDonation),window.removeEventListener("icpay-coffee",this.onWidgetCoffee)}startAutomaticProgression(){this.progressionTimer&&clearInterval(this.progressionTimer),this.activeIndex=1,this.updateStepStatus(this.activeIndex,"loading"),Ur(this.debug,"ICPay Progress: Starting automatic progression from step:",this.activeIndex),this.progressionTimer=setInterval(()=>{if(this.failed||this.completed){this.stopAutomaticProgression();return}Ur(this.debug,"ICPay Progress: Processing step:",this.activeIndex),this.updateStepStatus(this.activeIndex,"completed"),this.activeIndex<this.currentSteps.length-1?(this.activeIndex++,this.updateStepStatus(this.activeIndex,"loading"),Ur(this.debug,"ICPay Progress: Auto-progressed to step:",this.activeIndex)):(this.stopAutomaticProgression(),Ur(this.debug,"ICPay Progress: All steps completed, waiting for transaction completion")),this.requestUpdate()},3e3)}stopAutomaticProgression(){this.progressionTimer&&(clearInterval(this.progressionTimer),this.progressionTimer=null)}updateStepStatus(t,n,i){if(t>=0&&t<this.currentSteps.length){let s=this.currentSteps[t],o=s.status;s.status=n,n==="completed"&&(s.timestamp=this.getCurrentTime()),n==="error"&&i&&(s.errorMessage=this.transformErrorMessage(i)),Ur(this.debug,`ICPay Progress: Step ${t} (${s.label}) status changed from ${o} to ${n}`),this.requestUpdate()}}getCurrentTime(){return new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}progressPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let n=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,n))}verticalPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let n=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,n))}getStepIcon(t){switch(t.status){case"loading":return Ue`<div class="spinner"></div>`;case"completed":return"\u2713";case"error":return"\u2717";default:return"\u25CB"}}getStepIndexByKey(t){return this.currentSteps.findIndex(n=>n.key===t)}setLoadingByKey(t){let n=this.getStepIndexByKey(t);n>=0&&(this.activeIndex=n,this.updateStepStatus(n,"loading"),t==="confirm"&&(this.confirmLoadingStartedAt=Date.now()))}completeByKey(t){let n=this.getStepIndexByKey(t);n>=0&&(this.updateStepStatus(n,"completed"),this.activeIndex=n)}transformErrorMessage(t){let n=String(t||"").toLowerCase();return n.includes("user rejected")||n.includes("user cancelled")||n.includes("user canceled")||n.includes("signature rejected")?"User have rejected the transfer":t}renderConfetti(){if(!this.showConfetti)return"";let t=Array.from({length:50},(i,s)=>s),n=["#0066FF","#ef4444","#10b981","#f59e0b","#8b5cf6"];return Ue`
4930
+ `;function rf(r,e){if(!r||!e)return;let t=e.primaryColor||void 0,n=e.secondaryColor||void 0,i=(v,C)=>{C&&r.style.setProperty(v,C)};i("--icpay-primary",t),i("--icpay-secondary",n);let s=v=>{if(!v)return null;let C=v.replace("#",""),N=C.length===3?C.split("").map(D=>D+D).join(""):C,O=parseInt(N,16),L=O>>16&255,j=O>>8&255,q=O&255;return{r:L,g:j,b:q}},c=(v=>{let C=s(v);if(!C)return 0;let N=O=>{let L=O/255;return L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4)};return .2126*N(C.r)+.7152*N(C.g)+.0722*N(C.b)})(t||n)>.6,l=e.surfaceColor||(c?"#f3f4f6":"#1f2937"),u=e.surfaceAltColor||(c?"#e5e7eb":"#374151"),h=e.borderColor||(c?"#d1d5db":"#4b5563"),p=e.textColor||(c?"#111827":"#f9fafb"),w=e.accentColor||n||t||(c?"#6b7280":"#9ca3af"),y=e.mutedTextColor||(c?"#6b7280":"#9ca3af");i("--icpay-accent",w),i("--icpay-text",p),i("--icpay-muted",y),i("--icpay-surface",l),i("--icpay-surface-alt",u),i("--icpay-border",h)}var z9=lc(j9(),1),sU=typeof window<"u";function QA(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}function or(r){if(!sU)return{client:{},quoteUsd:async()=>({tokenAmountDecimals:"0"}),sendUsd:async()=>({transactionId:"0",status:"pending"}),startOnrampUsd:async()=>({transactionId:"0",status:"pending",metadata:{onramp:{sessionId:null}}}),notifyIntentUntilComplete:()=>({stop:()=>{}})};QA(r.debug||!1,"Creating SDK with config:",r);let e={publishableKey:r.publishableKey};r.enableEvents!==void 0?e.enableEvents=r.enableEvents:e.enableEvents=!0,r.apiUrl&&(e.apiUrl=r.apiUrl),r.icHost&&(e.icHost=r.icHost),r.actorProvider&&(e.actorProvider=r.actorProvider),r.connectedWallet&&(e.connectedWallet=r.connectedWallet),r.onrampDisabled!==void 0&&(e.onrampDisabled=r.onrampDisabled),r.debug!==void 0&&(e.debug=r.debug),QA(r.debug||!1,"Filtered SDK config:",e);try{let a=function(c,l,u){return n.notifyPaymentIntentOnRamp({paymentIntentId:c,intervalMs:l,orderId:u})};var t=a;QA(r.debug||!1,"typeof Icpay:",typeof z9.Icpay);let n=new z9.Icpay(e);if(sU){let c=n,l=u=>{c.addEventListener(u,h=>{window.dispatchEvent(new CustomEvent(u,{detail:h?.detail??h}))})};["icpay-sdk-error","icpay-sdk-transaction-created","icpay-sdk-transaction-updated","icpay-sdk-transaction-completed","icpay-sdk-transaction-failed","icpay-sdk-method-start","icpay-sdk-method-success","icpay-sdk-method-error"].forEach(l)}async function i(c,l){return n.calculateTokenAmountFromUSD({usdAmount:c,ledgerCanisterId:l})}async function s(c,l,u){return n.createPaymentUsd({usdAmount:c,ledgerCanisterId:l,metadata:u})}async function o(c,l,u){return n.createPaymentUsd({usdAmount:c,ledgerCanisterId:l,metadata:u,onrampPayment:!0})}return{client:n,quoteUsd:i,sendUsd:s,startOnrampUsd:o,notifyIntentUntilComplete:a}}catch(n){throw QA(r.debug||!1,"Error creating SDK:",n),n}}var Oi=r=>(e,t)=>{t!==void 0?t.addInitializer((()=>{customElements.define(r,e)})):customElements.define(r,e)};var Cie={attribute:!0,type:String,converter:Km,reflect:!1,hasChanged:h2},Iie=(r=Cie,e,t)=>{let{kind:n,metadata:i}=t,s=globalThis.litPropertyMetadata.get(i);if(s===void 0&&globalThis.litPropertyMetadata.set(i,s=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),s.set(t.name,r),n==="accessor"){let{name:o}=t;return{set(a){let c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,r)},init(a){return a!==void 0&&this.C(o,void 0,r,a),a}}}if(n==="setter"){let{name:o}=t;return function(a){let c=this[o];e.call(this,a),this.requestUpdate(o,c,r)}}throw Error("Unsupported decorator location: "+n)};function Yt(r){return(e,t)=>typeof t=="object"?Iie(r,e,t):((n,i,s)=>{let o=i.hasOwnProperty(s);return i.constructor.createProperty(s,n),o?Object.getOwnPropertyDescriptor(i,s):void 0})(r,e,t)}function Ce(r){return Yt({...r,state:!0,attribute:!1})}var Mf=(r,e,t)=>(t.configurable=!0,t.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(r,e,t),t);function D9(r,e){return(t,n,i)=>{let s=o=>o.renderRoot?.querySelector(r)??null;if(e){let{get:o,set:a}=typeof n=="object"?t:i??(()=>{let c=Symbol();return{get(){return this[c]},set(l){this[c]=l}}})();return Mf(t,n,{get(){let c=o.call(this);return c===void 0&&(c=s(this),(c!==null||this.hasUpdated)&&a.call(this,c)),c}})}return Mf(t,n,{get(){return s(this)}})}}var q9=lc(j9(),1),to={WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",WALLET_USER_CANCELLED:"WALLET_USER_CANCELLED",WALLET_SIGNATURE_REJECTED:"WALLET_SIGNATURE_REJECTED",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",NETWORK_ERROR:"NETWORK_ERROR",API_ERROR:"API_ERROR",LEDGER_NOT_FOUND:"LEDGER_NOT_FOUND",TRANSACTION_FAILED:"TRANSACTION_FAILED",TRANSACTION_TIMEOUT:"TRANSACTION_TIMEOUT",UNKNOWN_ERROR:"UNKNOWN_ERROR"},_ie={onError:r=>{console.error("[ICPay Widget] Error:",r)},onUserCancelled:()=>{console.log("[ICPay Widget] User cancelled the action")},onInsufficientBalance:r=>{console.warn("[ICPay Widget] Insufficient balance:",r.message)},onWalletError:r=>{console.warn("[ICPay Widget] Wallet error:",r.message)},onNetworkError:r=>{console.error("[ICPay Widget] Network error:",r.message)}};function ro(r,e=_ie){r instanceof q9.IcpayError?(e.onError(r),r.isUserCancelled()?e.onUserCancelled?.():r.isBalanceError()?e.onInsufficientBalance?.(r):r.isWalletError()?e.onWalletError?.(r):r.isNetworkError()&&e.onNetworkError?.(r)):(console.error("[ICPay Widget] Unknown error:",r),e.onError(new q9.IcpayError({code:to.UNKNOWN_ERROR,message:r instanceof Error?r.message:"An unknown error occurred",details:r})))}var Nie={[to.WALLET_NOT_CONNECTED]:"Please connect your wallet to continue",[to.WALLET_USER_CANCELLED]:"User have rejected the transfer",[to.WALLET_SIGNATURE_REJECTED]:"User have rejected the transfer",[to.INSUFFICIENT_BALANCE]:"Insufficient balance for this transaction",[to.NETWORK_ERROR]:"Network error. Please try again",[to.API_ERROR]:"Service temporarily unavailable",[to.LEDGER_NOT_FOUND]:"Selected token is not supported",[to.TRANSACTION_FAILED]:"Transaction failed. Please try again",[to.TRANSACTION_TIMEOUT]:"Transaction timed out. Please try again",[to.UNKNOWN_ERROR]:"Something went wrong. Please try again"};function no(r){return Nie[r.code]||r.message||"An error occurred"}function io(r){return!r.isUserCancelled()}function so(r){if(r.userAction)return r.userAction;switch(r.code){case to.WALLET_NOT_CONNECTED:return"Connect Wallet";case to.INSUFFICIENT_BALANCE:return"Add Funds";case to.NETWORK_ERROR:case to.API_ERROR:return"Try Again";default:return null}}function oo(r){return r.isUserCancelled()?"info":r.isBalanceError()||r.isWalletError()?"warning":"error"}function Ur(r,e,t){r&&(t!==void 0?console.log(e,t):console.log(e))}var Tie=[{key:"wallet",label:"Connect Wallet",tooltip:"Awaiting wallet connection",status:"pending"},{key:"init",label:"Initialising ICPay",tooltip:"Initializing payment",status:"pending"},{key:"await",label:"Awaiting payment confirmation",tooltip:"Preparing payment",status:"pending"},{key:"transfer",label:"Transferring funds",tooltip:"Submitting payment",status:"pending"},{key:"verify",label:"Verifying payment",tooltip:"Confirming payment",status:"pending"},{key:"confirm",label:"Payment confirmed",tooltip:"Payment completed",status:"pending"}],Sn=class extends pn{constructor(){super(...arguments);this.open=!1;this.steps=Tie;this.amount=0;this.currency="";this.ledgerSymbol="";this.debug=!1;this.activeIndex=0;this.completed=!1;this.failed=!1;this.errorMessage=null;this.showSuccess=!1;this.showConfetti=!1;this.currentSteps=[];this.currentAmount=0;this.currentCurrency="";this.currentLedgerSymbol="";this.confirmLoadingStartedAt=null;this.progressionTimer=null;this.onMethodStart=t=>{let n=t?.detail?.name||"",i=t?.detail?.type||"";if(Ur(this.debug,"ICPay Progress: Method start event received:",t.detail),n==="createPayment"||n==="createPaymentUsd"||n==="sendUsd"||n==="pay"||n==="unlock"||n==="tip"||n==="donate"||n==="order"){if(this.open=!0,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.currentSteps=this.currentSteps.map(s=>({...s,status:"pending"})),i==="onramp"){let s=this.getStepIndexByKey("wallet");s>=0&&(this.currentSteps[s]={...this.currentSteps[s],label:"Transak Started",tooltip:"Awaiting Transak information"})}this.setLoadingByKey("wallet"),t?.detail?.amount!==void 0&&(this.currentAmount=t.detail.amount,this.amount=t.detail.amount,Ur(this.debug,"ICPay Progress: Amount updated to:",t.detail.amount)),t?.detail?.currency&&(this.currentCurrency=t.detail.currency,this.currency=t.detail.currency,Ur(this.debug,"ICPay Progress: Currency updated to:",t.detail.currency)),t?.detail?.ledgerSymbol&&(this.currentLedgerSymbol=t.detail.ledgerSymbol,this.ledgerSymbol=t.detail.ledgerSymbol,Ur(this.debug,"ICPay Progress: Current state after method start:",{activeIndex:this.activeIndex,currentAmount:this.currentAmount,currentCurrency:this.currentCurrency,currentLedgerSymbol:this.currentLedgerSymbol})),Ur(this.debug,"ICPay Progress: Waiting for wallet confirmation before starting progression"),this.requestUpdate()}!this.failed&&!this.completed&&(n==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")):n==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")))};this.onMethodSuccess=t=>{let n=t?.detail?.name||"";(n==="createPayment"||n==="createPaymentUsd"||n==="sendUsd"||n==="pay"||n==="unlock"||n==="tip"||n==="donate"||n==="order")&&this.dispatchEvent(new CustomEvent("icpay-progress-method-success",{detail:{methodName:n,step:this.activeIndex},bubbles:!0})),!this.failed&&!this.completed&&(n==="getLedgerBalance"?(this.completeByKey("wallet"),this.completeByKey("init"),this.setLoadingByKey("await")):n==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):n==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.completeByKey("verify"),this.setLoadingByKey("confirm")))};this.onTransactionCreated=t=>{let n=t?.detail?.transactionId||t?.detail?.id;Ur(this.debug,"ICPay Progress: Transaction created event received:",t.detail),!this.failed&&!this.completed&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")),this.dispatchEvent(new CustomEvent("icpay-progress-transaction-created",{detail:{transactionId:n,step:this.activeIndex},bubbles:!0}))};this.onTransactionUpdated=t=>{let n=t?.detail?.status||"pending",i=t?.detail?.transactionId||t?.detail?.id;Ur(this.debug,"ICPay Progress: Transaction updated event received:",t.detail),!this.failed&&this.completed,this.dispatchEvent(new CustomEvent("icpay-progress-transaction-updated",{detail:{status:n,transactionId:i,step:this.activeIndex},bubbles:!0}))};this.onTransactionCompleted=t=>{let n=t?.detail?.transactionId||t?.detail?.id,i=t?.detail?.status||"completed";Ur(this.debug,"ICPay Progress: Transaction completed event received:",t.detail),Ur(this.debug,"ICPay Progress: Current state when transaction completed:",{activeIndex:this.activeIndex,completed:this.completed,failed:this.failed,showSuccess:this.showSuccess}),this.completeByKey("transfer"),this.completeByKey("await"),this.completeByKey("init"),this.completeByKey("verify"),this.completeByKey("confirm"),this.completed=!0,this.showSuccess=!0,this.showConfetti=!0,this.dispatchEvent(new CustomEvent("icpay-progress-completed",{detail:{transactionId:n,status:i,amount:this.currentAmount||this.amount,currency:this.currentCurrency||this.currency,ledgerSymbol:this.currentLedgerSymbol||this.ledgerSymbol},bubbles:!0})),setTimeout(()=>{this.showConfetti=!1},3e3)};this.onTransactionFailed=t=>{let n=t?.detail?.message||t?.detail?.error?.message||"Transaction failed",i=t?.detail?.error?.code||t?.detail?.code||"UNKNOWN_ERROR",s=t?.detail?.transactionId||t?.detail?.id;Ur(this.debug,"ICPay Progress: Transaction failed event received:",t.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",n),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:n,errorCode:i,transactionId:s,step:this.activeIndex},bubbles:!0}))};this.onTransactionMismatched=t=>{let n=t?.detail?.requestedAmount,i=t?.detail?.paidAmount,s=t?.detail?.transactionId||t?.detail?.id;this.failed=!0;let o=n!=null?String(n):"unknown",a=i!=null?String(i):"unknown";this.errorMessage=`Amount mismatch. Requested ${o}, paid ${a}.`,this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:"MISMATCHED_AMOUNT",transactionId:s,step:this.activeIndex,requestedAmount:n,paidAmount:i},bubbles:!0}))};this.onMethodError=t=>{let n=t?.detail?.name||"",i=t?.detail?.error?.message||t?.detail?.message||"An error occurred",s=t?.detail?.error?.code||t?.detail?.code||"METHOD_ERROR";Ur(this.debug,"ICPay Progress: Method error event received:",t.detail),(n?.startsWith("createPayment")||n==="sendUsd"||n==="pay"||n==="unlock"||n==="tip"||n==="donate"||n==="order")&&(this.failed=!0,this.errorMessage=this.transformErrorMessage(i),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",i),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-error",{detail:{methodName:n,errorMessage:i,errorCode:s,step:this.activeIndex},bubbles:!0})))};this.onSDKError=t=>{let n=t?.detail?.message||"SDK error occurred",i=t?.detail?.code||"SDK_ERROR";Ur(this.debug,"ICPay Progress: SDK error event received:",t.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",n),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-sdk-error",{detail:{errorMessage:n,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWalletConnected=t=>{let n=t?.detail?.walletType||"unknown";Ur(this.debug,"ICPay Progress: Wallet connected event received:",t.detail),this.completeByKey("wallet"),this.setLoadingByKey("init"),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-connected",{detail:{walletType:n,step:this.activeIndex},bubbles:!0}))};this.onWalletDisconnected=t=>{let n=t?.detail?.walletType||"unknown";Ur(this.debug,"ICPay Progress: Wallet disconnected event received:",t.detail),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-disconnected",{detail:{walletType:n,step:this.activeIndex},bubbles:!0}))};this.onBalanceCheck=t=>{let n=t?.detail?.hasBalance||!1,i=t?.detail?.balance||0;Ur(this.debug,"ICPay Progress: Balance check event received:",t.detail),n||(this.failed=!0,this.errorMessage="Insufficient balance for transaction",this.updateStepStatus(this.activeIndex,"error","Insufficient balance for transaction"),this.stopAutomaticProgression(),this.dispatchEvent(new CustomEvent("icpay-progress-insufficient-balance",{detail:{balance:i,required:this.currentAmount||this.amount,step:this.activeIndex},bubbles:!0})))};this.onLedgerVerified=t=>{let n=t?.detail?.ledgerId||t?.detail?.canisterId,i=t?.detail?.symbol||"unknown";Ur(this.debug,"ICPay Progress: Ledger verified event received:",t.detail),i&&i!=="unknown"&&(this.currentLedgerSymbol=i,this.ledgerSymbol=i),this.dispatchEvent(new CustomEvent("icpay-progress-ledger-verified",{detail:{ledgerId:n,symbol:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetPayment=t=>{let n=t?.detail?.amount,i=t?.detail?.currency,s=t?.detail?.ledgerSymbol;if(Ur(this.debug,"ICPay Progress: Widget payment event received:",t.detail),n!==void 0&&(this.currentAmount=n,this.amount=n),i&&(this.currentCurrency=i,this.currency=i),s&&(this.currentLedgerSymbol=s,this.ledgerSymbol=s),!this.failed){for(let o=this.activeIndex;o<this.currentSteps.length;o++)this.updateStepStatus(o,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-payment",{detail:{amount:n,currency:i,ledgerSymbol:s,step:this.activeIndex},bubbles:!0}))};this.onWidgetError=t=>{let n=t?.detail?.message||"Widget error occurred",i=t?.detail?.code||"WIDGET_ERROR";Ur(this.debug,"ICPay Progress: Widget error event received:",t.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",n),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-widget-error",{detail:{errorMessage:n,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetUnlock=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget unlock event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-unlock",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetTip=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget tip event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-tip",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetDonation=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget donation event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-donation",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetCoffee=t=>{let n=t?.detail?.amount,i=t?.detail?.currency;if(Ur(this.debug,"ICPay Progress: Widget coffee event received:",t.detail),!this.failed){for(let s=this.activeIndex;s<this.currentSteps.length;s++)this.updateStepStatus(s,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-coffee",{detail:{amount:n,currency:i,step:this.activeIndex},bubbles:!0}))}}connectedCallback(){super.connectedCallback();try{rf(this,this.theme)}catch{}this.currentSteps=[...this.steps],this.currentAmount=this.amount,this.currentCurrency=this.currency,this.currentLedgerSymbol=this.ledgerSymbol,this.attachSDKEventListeners()}disconnectedCallback(){super.disconnectedCallback(),this.detachSDKEventListeners(),this.stopAutomaticProgression()}updated(t){if(t.has("theme"))try{rf(this,this.theme)}catch{}}attachSDKEventListeners(){window.addEventListener("icpay-sdk-method-start",this.onMethodStart),window.addEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.addEventListener("icpay-sdk-method-error",this.onMethodError),window.addEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.addEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.addEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.addEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.addEventListener("icpay-sdk-error",this.onSDKError),window.addEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.addEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.addEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.addEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.addEventListener("icpay-pay",this.onWidgetPayment),window.addEventListener("icpay-error",this.onWidgetError),window.addEventListener("icpay-unlock",this.onWidgetUnlock),window.addEventListener("icpay-tip",this.onWidgetTip),window.addEventListener("icpay-donation",this.onWidgetDonation),window.addEventListener("icpay-coffee",this.onWidgetCoffee)}detachSDKEventListeners(){window.removeEventListener("icpay-sdk-method-start",this.onMethodStart),window.removeEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.removeEventListener("icpay-sdk-method-error",this.onMethodError),window.removeEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.removeEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.removeEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.removeEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.removeEventListener("icpay-sdk-error",this.onSDKError),window.removeEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.removeEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.removeEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.removeEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.removeEventListener("icpay-pay",this.onWidgetPayment),window.removeEventListener("icpay-error",this.onWidgetError),window.removeEventListener("icpay-unlock",this.onWidgetUnlock),window.removeEventListener("icpay-tip",this.onWidgetTip),window.removeEventListener("icpay-donation",this.onWidgetDonation),window.removeEventListener("icpay-coffee",this.onWidgetCoffee)}startAutomaticProgression(){this.progressionTimer&&clearInterval(this.progressionTimer),this.activeIndex=1,this.updateStepStatus(this.activeIndex,"loading"),Ur(this.debug,"ICPay Progress: Starting automatic progression from step:",this.activeIndex),this.progressionTimer=setInterval(()=>{if(this.failed||this.completed){this.stopAutomaticProgression();return}Ur(this.debug,"ICPay Progress: Processing step:",this.activeIndex),this.updateStepStatus(this.activeIndex,"completed"),this.activeIndex<this.currentSteps.length-1?(this.activeIndex++,this.updateStepStatus(this.activeIndex,"loading"),Ur(this.debug,"ICPay Progress: Auto-progressed to step:",this.activeIndex)):(this.stopAutomaticProgression(),Ur(this.debug,"ICPay Progress: All steps completed, waiting for transaction completion")),this.requestUpdate()},3e3)}stopAutomaticProgression(){this.progressionTimer&&(clearInterval(this.progressionTimer),this.progressionTimer=null)}updateStepStatus(t,n,i){if(t>=0&&t<this.currentSteps.length){let s=this.currentSteps[t],o=s.status;s.status=n,n==="completed"&&(s.timestamp=this.getCurrentTime()),n==="error"&&i&&(s.errorMessage=this.transformErrorMessage(i)),Ur(this.debug,`ICPay Progress: Step ${t} (${s.label}) status changed from ${o} to ${n}`),this.requestUpdate()}}getCurrentTime(){return new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}progressPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let n=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,n))}verticalPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let n=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,n))}getStepIcon(t){switch(t.status){case"loading":return Ue`<div class="spinner"></div>`;case"completed":return"\u2713";case"error":return"\u2717";default:return"\u25CB"}}getStepIndexByKey(t){return this.currentSteps.findIndex(n=>n.key===t)}setLoadingByKey(t){let n=this.getStepIndexByKey(t);n>=0&&(this.activeIndex=n,this.updateStepStatus(n,"loading"),t==="confirm"&&(this.confirmLoadingStartedAt=Date.now()))}completeByKey(t){let n=this.getStepIndexByKey(t);n>=0&&(this.updateStepStatus(n,"completed"),this.activeIndex=n)}transformErrorMessage(t){let n=String(t||"").toLowerCase();return n.includes("user rejected")||n.includes("user cancelled")||n.includes("user canceled")||n.includes("signature rejected")?"User have rejected the transfer":t}renderConfetti(){if(!this.showConfetti)return"";let t=Array.from({length:50},(i,s)=>s),n=["#0066FF","#ef4444","#10b981","#f59e0b","#8b5cf6"];return Ue`
4931
4931
  <div class="confetti">
4932
4932
  ${t.map(i=>Ue`
4933
4933
  <div
@@ -5378,7 +5378,7 @@ Make sure to test your application with a production build as repeat registratio
5378
5378
  `}
5379
5379
  </div>
5380
5380
  </div>
5381
- `}var rM=typeof window<"u",Om=null;function Fd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Hn=class extends pn{constructor(){super(...arguments);this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Om||(Om=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Om(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),rM&&(Fd(this.config?.debug||!1,"Premium content connected",{config:this.config}),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="pay"&&this.onPay()},0)}}async loadVerifiedLedgers(){if(!(!rM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}async onPay(){if(rM&&!(this.processing||this.unlocked)){Fd(this.config?.debug||!1,"Premium content payment started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Fd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Om||(Om=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Om(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Fd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="pay",this.showWalletModal=!0;return}catch(o){Fd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Fd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Fd(this.config?.debug||!1,"Payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.config.priceUsd,i,{context:"premium-content"});Fd(this.config?.debug||!1,"Payment completed",{resp:s}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.config.priceUsd,i,{context:"premium:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}select(t){this.selectedSymbol=t}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="pay"&&setTimeout(()=>this.onPay(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5381
+ `}var rM=typeof window<"u",Om=null;function Fd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Hn=class extends pn{constructor(){super(...arguments);this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Om||(Om=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Om(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),rM&&(Fd(this.config?.debug||!1,"Premium content connected",{config:this.config}),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="pay"&&this.onPay()},0)}}async loadVerifiedLedgers(){if(!(!rM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}async onPay(){if(rM&&!(this.processing||this.unlocked)){Fd(this.config?.debug||!1,"Premium content payment started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Fd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Om||(Om=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Om(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Fd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="pay",this.showWalletModal=!0;return}catch(o){Fd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Fd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Fd(this.config?.debug||!1,"Payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.config.priceUsd,i,{context:"premium-content"});Fd(this.config?.debug||!1,"Payment completed",{resp:s}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.config.priceUsd,i,{context:"premium:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}select(t){this.selectedSymbol=t}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="pay"&&setTimeout(()=>this.onPay(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5382
5382
  <div class="icpay-card icpay-section">
5383
5383
  ${this.config?.progressBar?.enabled!==!1?Ue`
5384
5384
  <icpay-progress-bar
@@ -5422,7 +5422,7 @@ Make sure to test your application with a production build as repeat registratio
5422
5422
  `:""}
5423
5423
  </div>
5424
5424
  `:""}
5425
- ${(()=>{let n=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:n,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let s=Number(this.config?.priceUsd||0);return s>0&&s<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-s).toFixed(2)} more.`:null})()})})()}
5425
+ ${(()=>{let n=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:n,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let s=Number(this.config?.priceUsd||0);return s>0&&s<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-s).toFixed(2)} more.`:null})()})})()}
5426
5426
 
5427
5427
  ${this.showOnrampModal?_s({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
5428
5428
  </div>
@@ -5477,7 +5477,7 @@ Make sure to test your application with a production build as repeat registratio
5477
5477
  border-color: rgba(239, 68, 68, 0.3);
5478
5478
  color: #ef4444;
5479
5479
  }
5480
- `],we([Yt({type:Object})],Hn.prototype,"config",2),we([Ce()],Hn.prototype,"selectedSymbol",2),we([Ce()],Hn.prototype,"unlocked",2),we([Ce()],Hn.prototype,"succeeded",2),we([Ce()],Hn.prototype,"processing",2),we([Ce()],Hn.prototype,"availableLedgers",2),we([Ce()],Hn.prototype,"errorMessage",2),we([Ce()],Hn.prototype,"errorSeverity",2),we([Ce()],Hn.prototype,"errorAction",2),we([Ce()],Hn.prototype,"walletConnected",2),we([Ce()],Hn.prototype,"pendingAction",2),we([Ce()],Hn.prototype,"showWalletModal",2),we([Ce()],Hn.prototype,"showOnrampModal",2),we([Ce()],Hn.prototype,"onrampSessionId",2),we([Ce()],Hn.prototype,"onrampPaymentIntentId",2),we([Ce()],Hn.prototype,"onrampErrorMessage",2),Hn=we([Oi("icpay-premium-content")],Hn);var nM=typeof window<"u",Pm=null;function $d(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Mn=class extends pn{constructor(){super(...arguments);this.selectedAmount=1;this.selectedSymbol="ICP";this.total=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Pm||(Pm=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Pm(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[1,5,10]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),nM&&($d(this.config?.debug||!1,"Tip jar connected",{config:this.config}),this.config&&this.config.defaultAmountUsd&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="tip"&&this.tip()},0)}}async loadVerifiedLedgers(){if(!(!nM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.config?.cryptoOptions&&this.config.cryptoOptions.length===1&&(this.selectedSymbol=this.config.cryptoOptions[0].symbol),!this.selectedSymbol&&this.availableLedgers.length>0&&(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0].symbol)}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(t){this.selectedAmount=t}selectSymbol(t){this.selectedSymbol=t}get fillPercentage(){return Math.min(this.total/50*100,100)}async tip(){if(nM&&($d(this.config?.debug||!1,"Tip button clicked!",{config:this.config,processing:this.processing}),!this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="tip",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){$d(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Pm||(Pm=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Pm(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if($d(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="tip",this.showWalletModal=!0;return}catch(o){$d(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}$d(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);$d(this.config?.debug||!1,"Tip payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.selectedAmount,i,{context:"tip-jar"});$d(this.config?.debug||!1,"Tip payment completed",{resp:s}),this.total+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status,total:this.total}),this.dispatchEvent(new CustomEvent("icpay-tip",{detail:{amount:this.selectedAmount,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.selectedAmount,i,{context:"tip:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="tip"&&setTimeout(()=>this.tip(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){if(!this.config)return Ue`<div class="icpay-card icpay-section">Loading...</div>`;let n=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,s=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",o=s!=="none"&&(n||s==="dropdown"),a=s==="dropdown"?"dropdown":n?"buttons":"none";return Ue`
5480
+ `],we([Yt({type:Object})],Hn.prototype,"config",2),we([Ce()],Hn.prototype,"selectedSymbol",2),we([Ce()],Hn.prototype,"unlocked",2),we([Ce()],Hn.prototype,"succeeded",2),we([Ce()],Hn.prototype,"processing",2),we([Ce()],Hn.prototype,"availableLedgers",2),we([Ce()],Hn.prototype,"errorMessage",2),we([Ce()],Hn.prototype,"errorSeverity",2),we([Ce()],Hn.prototype,"errorAction",2),we([Ce()],Hn.prototype,"walletConnected",2),we([Ce()],Hn.prototype,"pendingAction",2),we([Ce()],Hn.prototype,"showWalletModal",2),we([Ce()],Hn.prototype,"showOnrampModal",2),we([Ce()],Hn.prototype,"onrampSessionId",2),we([Ce()],Hn.prototype,"onrampPaymentIntentId",2),we([Ce()],Hn.prototype,"onrampErrorMessage",2),Hn=we([Oi("icpay-premium-content")],Hn);var nM=typeof window<"u",Pm=null;function $d(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Mn=class extends pn{constructor(){super(...arguments);this.selectedAmount=1;this.selectedSymbol="ICP";this.total=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Pm||(Pm=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Pm(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[1,5,10]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),nM&&($d(this.config?.debug||!1,"Tip jar connected",{config:this.config}),this.config&&this.config.defaultAmountUsd&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="tip"&&this.tip()},0)}}async loadVerifiedLedgers(){if(!(!nM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.config?.cryptoOptions&&this.config.cryptoOptions.length===1&&(this.selectedSymbol=this.config.cryptoOptions[0].symbol),!this.selectedSymbol&&this.availableLedgers.length>0&&(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0].symbol)}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(t){this.selectedAmount=t}selectSymbol(t){this.selectedSymbol=t}get fillPercentage(){return Math.min(this.total/50*100,100)}async tip(){if(nM&&($d(this.config?.debug||!1,"Tip button clicked!",{config:this.config,processing:this.processing}),!this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="tip",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){$d(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Pm||(Pm=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Pm(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if($d(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="tip",this.showWalletModal=!0;return}catch(o){$d(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}$d(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);$d(this.config?.debug||!1,"Tip payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.selectedAmount,i,{context:"tip-jar"});$d(this.config?.debug||!1,"Tip payment completed",{resp:s}),this.total+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status,total:this.total}),this.dispatchEvent(new CustomEvent("icpay-tip",{detail:{amount:this.selectedAmount,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.selectedAmount,i,{context:"tip:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="tip"&&setTimeout(()=>this.tip(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){if(!this.config)return Ue`<div class="icpay-card icpay-section">Loading...</div>`;let n=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,s=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",o=s!=="none"&&(n||s==="dropdown"),a=s==="dropdown"?"dropdown":n?"buttons":"none";return Ue`
5481
5481
  <div class="icpay-card icpay-section" style="text-align:center;">
5482
5482
  ${this.config?.progressBar?.enabled!==!1?Ue`
5483
5483
  <icpay-progress-bar
@@ -5558,7 +5558,7 @@ Make sure to test your application with a production build as repeat registratio
5558
5558
  border-color: rgba(239, 68, 68, 0.3);
5559
5559
  color: #ef4444;
5560
5560
  }
5561
- `],we([Yt({type:Object})],Mn.prototype,"config",2),we([Ce()],Mn.prototype,"selectedAmount",2),we([Ce()],Mn.prototype,"selectedSymbol",2),we([Ce()],Mn.prototype,"total",2),we([Ce()],Mn.prototype,"processing",2),we([Ce()],Mn.prototype,"succeeded",2),we([Ce()],Mn.prototype,"availableLedgers",2),we([Ce()],Mn.prototype,"errorMessage",2),we([Ce()],Mn.prototype,"errorSeverity",2),we([Ce()],Mn.prototype,"errorAction",2),we([Ce()],Mn.prototype,"walletConnected",2),we([Ce()],Mn.prototype,"pendingAction",2),we([Ce()],Mn.prototype,"showWalletModal",2),we([Ce()],Mn.prototype,"showOnrampModal",2),we([Ce()],Mn.prototype,"onrampSessionId",2),we([Ce()],Mn.prototype,"onrampPaymentIntentId",2),we([Ce()],Mn.prototype,"onrampErrorMessage",2),Mn=we([Oi("icpay-tip-jar")],Mn);var iM=typeof window<"u",Bm=null;function Wd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var fn=class extends pn{constructor(){super(...arguments);this.title="Article Title";this.preview="";this.lockedContent="";this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get obfuscatedLockedContent(){try{return(this.lockedContent||"").replace(/[^\s]/g,"x")}catch{return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Bm||(Bm=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Bm(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.config.priceUsd,i,{context:"article:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),iM&&(Wd(this.config?.debug||!1,"Article paywall connected",{config:this.config}),this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="unlock"&&this.unlock()},0)}}async loadVerifiedLedgers(){if(!(!iM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectSymbol(t){this.selectedSymbol=t}async unlock(){if(iM&&!(this.processing||this.unlocked)){Wd(this.config?.debug||!1,"Article paywall unlock started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="unlock",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Wd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Bm||(Bm=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Bm(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Wd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="unlock",this.showWalletModal=!0;return}catch(o){Wd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Wd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Wd(this.config?.debug||!1,"Article payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.config.priceUsd,i,{context:"article"});Wd(this.config?.debug||!1,"Article payment completed",{resp:s}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="unlock"&&setTimeout(()=>this.unlock(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5561
+ `],we([Yt({type:Object})],Mn.prototype,"config",2),we([Ce()],Mn.prototype,"selectedAmount",2),we([Ce()],Mn.prototype,"selectedSymbol",2),we([Ce()],Mn.prototype,"total",2),we([Ce()],Mn.prototype,"processing",2),we([Ce()],Mn.prototype,"succeeded",2),we([Ce()],Mn.prototype,"availableLedgers",2),we([Ce()],Mn.prototype,"errorMessage",2),we([Ce()],Mn.prototype,"errorSeverity",2),we([Ce()],Mn.prototype,"errorAction",2),we([Ce()],Mn.prototype,"walletConnected",2),we([Ce()],Mn.prototype,"pendingAction",2),we([Ce()],Mn.prototype,"showWalletModal",2),we([Ce()],Mn.prototype,"showOnrampModal",2),we([Ce()],Mn.prototype,"onrampSessionId",2),we([Ce()],Mn.prototype,"onrampPaymentIntentId",2),we([Ce()],Mn.prototype,"onrampErrorMessage",2),Mn=we([Oi("icpay-tip-jar")],Mn);var iM=typeof window<"u",Bm=null;function Wd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var fn=class extends pn{constructor(){super(...arguments);this.title="Article Title";this.preview="";this.lockedContent="";this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get obfuscatedLockedContent(){try{return(this.lockedContent||"").replace(/[^\s]/g,"x")}catch{return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Bm||(Bm=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Bm(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.config.priceUsd,i,{context:"article:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),iM&&(Wd(this.config?.debug||!1,"Article paywall connected",{config:this.config}),this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="unlock"&&this.unlock()},0)}}async loadVerifiedLedgers(){if(!(!iM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectSymbol(t){this.selectedSymbol=t}async unlock(){if(iM&&!(this.processing||this.unlocked)){Wd(this.config?.debug||!1,"Article paywall unlock started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="unlock",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Wd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Bm||(Bm=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Bm(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Wd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="unlock",this.showWalletModal=!0;return}catch(o){Wd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Wd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Wd(this.config?.debug||!1,"Article payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.config.priceUsd,i,{context:"article"});Wd(this.config?.debug||!1,"Article payment completed",{resp:s}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="unlock"&&setTimeout(()=>this.unlock(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5562
5562
  <div class="icpay-card icpay-section">
5563
5563
  ${this.config?.progressBar?.enabled!==!1?Ue`
5564
5564
  <icpay-progress-bar
@@ -5600,7 +5600,7 @@ Make sure to test your application with a production build as repeat registratio
5600
5600
  `:""}
5601
5601
  </div>
5602
5602
  `:""}
5603
- ${(()=>{let n=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:n,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let s=Number(this.config?.priceUsd||0);return s>0&&s<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-s).toFixed(2)} more.`:null})()})})()}
5603
+ ${(()=>{let n=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:n,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let s=Number(this.config?.priceUsd||0);return s>0&&s<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-s).toFixed(2)} more.`:null})()})})()}
5604
5604
 
5605
5605
  ${this.showOnrampModal?_s({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
5606
5606
  </div>
@@ -5636,7 +5636,7 @@ Make sure to test your application with a production build as repeat registratio
5636
5636
  border-color: rgba(239, 68, 68, 0.3);
5637
5637
  color: #ef4444;
5638
5638
  }
5639
- `],we([Yt({type:Object})],fn.prototype,"config",2),we([Yt({type:String})],fn.prototype,"title",2),we([Yt({type:String})],fn.prototype,"preview",2),we([Yt({type:String})],fn.prototype,"lockedContent",2),we([Ce()],fn.prototype,"selectedSymbol",2),we([Ce()],fn.prototype,"unlocked",2),we([Ce()],fn.prototype,"succeeded",2),we([Ce()],fn.prototype,"processing",2),we([Ce()],fn.prototype,"availableLedgers",2),we([Ce()],fn.prototype,"errorMessage",2),we([Ce()],fn.prototype,"errorSeverity",2),we([Ce()],fn.prototype,"errorAction",2),we([Ce()],fn.prototype,"walletConnected",2),we([Ce()],fn.prototype,"pendingAction",2),we([Ce()],fn.prototype,"showWalletModal",2),we([Ce()],fn.prototype,"showOnrampModal",2),we([Ce()],fn.prototype,"onrampSessionId",2),we([Ce()],fn.prototype,"onrampPaymentIntentId",2),we([Ce()],fn.prototype,"onrampErrorMessage",2),fn=we([Oi("icpay-article-paywall")],fn);var sM=typeof window<"u",oM=null;function Vd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var ri=class extends pn{constructor(){super(...arguments);this.selectedIndex=0;this.selectedSymbol="ICP";this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),sM&&(Vd(this.config?.debug||!1,"Coffee shop connected",{config:this.config}),this.config&&typeof this.config.defaultItemIndex=="number"&&(this.selectedIndex=this.config.defaultItemIndex),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="order"&&this.order()},0)}}async loadVerifiedLedgers(){if(!(!sM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectItem(t){this.selectedIndex=t}selectSymbol(t){this.selectedSymbol=t}get selectedItem(){return this.config?.items?.[this.selectedIndex]||{name:"Loading...",priceUsd:0}}async order(){if(sM&&!this.processing){Vd(this.config?.debug||!1,"Coffee order started",{selectedItem:this.selectedItem,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:this.selectedItem.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="order",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Vd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{oM||(oM=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new oM(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Vd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="order",this.showWalletModal=!0;return}catch(o){Vd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Vd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Vd(this.config?.debug||!1,"Coffee order payment details",{item:this.selectedItem.name,priceUsd:this.selectedItem.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.selectedItem.priceUsd,i,{context:"coffee",item:this.selectedItem.name});Vd(this.config?.debug||!1,"Coffee order payment completed",{resp:s}),this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status,item:this.selectedItem.name}),this.dispatchEvent(new CustomEvent("icpay-coffee",{detail:{item:this.selectedItem,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.selectedItem.priceUsd,i,{context:"coffee:onramp",item:this.selectedItem.name}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="order"&&setTimeout(()=>this.order(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5639
+ `],we([Yt({type:Object})],fn.prototype,"config",2),we([Yt({type:String})],fn.prototype,"title",2),we([Yt({type:String})],fn.prototype,"preview",2),we([Yt({type:String})],fn.prototype,"lockedContent",2),we([Ce()],fn.prototype,"selectedSymbol",2),we([Ce()],fn.prototype,"unlocked",2),we([Ce()],fn.prototype,"succeeded",2),we([Ce()],fn.prototype,"processing",2),we([Ce()],fn.prototype,"availableLedgers",2),we([Ce()],fn.prototype,"errorMessage",2),we([Ce()],fn.prototype,"errorSeverity",2),we([Ce()],fn.prototype,"errorAction",2),we([Ce()],fn.prototype,"walletConnected",2),we([Ce()],fn.prototype,"pendingAction",2),we([Ce()],fn.prototype,"showWalletModal",2),we([Ce()],fn.prototype,"showOnrampModal",2),we([Ce()],fn.prototype,"onrampSessionId",2),we([Ce()],fn.prototype,"onrampPaymentIntentId",2),we([Ce()],fn.prototype,"onrampErrorMessage",2),fn=we([Oi("icpay-article-paywall")],fn);var sM=typeof window<"u",oM=null;function Vd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var ri=class extends pn{constructor(){super(...arguments);this.selectedIndex=0;this.selectedSymbol="ICP";this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),sM&&(Vd(this.config?.debug||!1,"Coffee shop connected",{config:this.config}),this.config&&typeof this.config.defaultItemIndex=="number"&&(this.selectedIndex=this.config.defaultItemIndex),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="order"&&this.order()},0)}}async loadVerifiedLedgers(){if(!(!sM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectItem(t){this.selectedIndex=t}selectSymbol(t){this.selectedSymbol=t}get selectedItem(){return this.config?.items?.[this.selectedIndex]||{name:"Loading...",priceUsd:0}}async order(){if(sM&&!this.processing){Vd(this.config?.debug||!1,"Coffee order started",{selectedItem:this.selectedItem,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:this.selectedItem.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="order",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Vd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{oM||(oM=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new oM(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Vd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="order",this.showWalletModal=!0;return}catch(o){Vd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Vd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Vd(this.config?.debug||!1,"Coffee order payment details",{item:this.selectedItem.name,priceUsd:this.selectedItem.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.selectedItem.priceUsd,i,{context:"coffee",item:this.selectedItem.name});Vd(this.config?.debug||!1,"Coffee order payment completed",{resp:s}),this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status,item:this.selectedItem.name}),this.dispatchEvent(new CustomEvent("icpay-coffee",{detail:{item:this.selectedItem,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.selectedItem.priceUsd,i,{context:"coffee:onramp",item:this.selectedItem.name}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="order"&&setTimeout(()=>this.order(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5640
5640
  <div class="icpay-card icpay-section">
5641
5641
  ${this.config?.progressBar?.enabled!==!1?Ue`
5642
5642
  <icpay-progress-bar
@@ -5681,7 +5681,7 @@ Make sure to test your application with a production build as repeat registratio
5681
5681
  `:""}
5682
5682
  </div>
5683
5683
  `:""}
5684
- ${(()=>{let n=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:n,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let s=this.config?.defaultItemIndex??0,o=Number(this.config?.items?.[s]?.priceUsd||0);return o>0&&o<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-o).toFixed(2)} more.`:null})()})})()}
5684
+ ${(()=>{let n=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:n,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let s=this.config?.defaultItemIndex??0,o=Number(this.config?.items?.[s]?.priceUsd||0);return o>0&&o<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-o).toFixed(2)} more.`:null})()})})()}
5685
5685
 
5686
5686
  ${this.showOnrampModal?_s({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
5687
5687
  </div>
@@ -5716,7 +5716,7 @@ Make sure to test your application with a production build as repeat registratio
5716
5716
  border-color: rgba(239, 68, 68, 0.3);
5717
5717
  color: #ef4444;
5718
5718
  }
5719
- `],we([Yt({type:Object})],ri.prototype,"config",2),we([Ce()],ri.prototype,"selectedIndex",2),we([Ce()],ri.prototype,"selectedSymbol",2),we([Ce()],ri.prototype,"processing",2),we([Ce()],ri.prototype,"availableLedgers",2),we([Ce()],ri.prototype,"errorMessage",2),we([Ce()],ri.prototype,"errorSeverity",2),we([Ce()],ri.prototype,"errorAction",2),we([Ce()],ri.prototype,"walletConnected",2),we([Ce()],ri.prototype,"pendingAction",2),we([Ce()],ri.prototype,"showWalletModal",2),we([Ce()],ri.prototype,"showOnrampModal",2),we([Ce()],ri.prototype,"onrampSessionId",2),we([Ce()],ri.prototype,"onrampPaymentIntentId",2),we([Ce()],ri.prototype,"onrampErrorMessage",2),ri=we([Oi("icpay-coffee-shop")],ri);var aM=typeof window<"u",Rm=null;function Kd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Pn=class extends pn{constructor(){super(...arguments);this.selectedAmount=10;this.selectedSymbol="ICP";this.raised=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Rm||(Rm=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Rm(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[10,25,50,100,250,500]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),aM&&(Kd(this.config?.debug||!1,"Donation thermometer connected",{config:this.config}),this.config&&typeof this.config.defaultAmountUsd=="number"&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="donate"&&this.donate()},0)}}async loadVerifiedLedgers(){if(!(!aM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(t){this.selectedAmount=t}selectSymbol(t){this.selectedSymbol=t}get fillPercentage(){let t=Number(this.config?.goalUsd??1e3),n=t>0?t:1e3;return Math.min(this.raised/n*100,100)}async donate(){if(aM&&!this.processing){Kd(this.config?.debug||!1,"Donation started",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="donate",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Kd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Rm||(Rm=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Rm(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Kd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="donate",this.showWalletModal=!0;return}catch(o){Kd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Kd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Kd(this.config?.debug||!1,"Donation payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.selectedAmount,i,{context:"donation"});Kd(this.config?.debug||!1,"Donation payment completed",{resp:s}),this.raised+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status,raised:this.raised}),this.dispatchEvent(new CustomEvent("icpay-donation",{detail:{amount:this.selectedAmount,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.selectedAmount,i,{context:"donation:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="donate"&&setTimeout(()=>this.donate(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5719
+ `],we([Yt({type:Object})],ri.prototype,"config",2),we([Ce()],ri.prototype,"selectedIndex",2),we([Ce()],ri.prototype,"selectedSymbol",2),we([Ce()],ri.prototype,"processing",2),we([Ce()],ri.prototype,"availableLedgers",2),we([Ce()],ri.prototype,"errorMessage",2),we([Ce()],ri.prototype,"errorSeverity",2),we([Ce()],ri.prototype,"errorAction",2),we([Ce()],ri.prototype,"walletConnected",2),we([Ce()],ri.prototype,"pendingAction",2),we([Ce()],ri.prototype,"showWalletModal",2),we([Ce()],ri.prototype,"showOnrampModal",2),we([Ce()],ri.prototype,"onrampSessionId",2),we([Ce()],ri.prototype,"onrampPaymentIntentId",2),we([Ce()],ri.prototype,"onrampErrorMessage",2),ri=we([Oi("icpay-coffee-shop")],ri);var aM=typeof window<"u",Rm=null;function Kd(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Pn=class extends pn{constructor(){super(...arguments);this.selectedAmount=10;this.selectedSymbol="ICP";this.raised=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let t=localStorage.getItem("icpay:pnp");if(!t)return;let n=JSON.parse(t);if(!n?.provider||!n?.principal)return;Rm||(Rm=(await Promise.resolve().then(()=>(nc(),rc))).PNP);let i=new Rm(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:n.principal,principal:n.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[10,25,50,100,250,500]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),aM&&(Kd(this.config?.debug||!1,"Donation thermometer connected",{config:this.config}),this.config&&typeof this.config.defaultAmountUsd=="number"&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="donate"&&this.donate()},0)}}async loadVerifiedLedgers(){if(!(!aM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(t){console.warn("Failed to load verified ledgers:",t),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(t){this.selectedAmount=t}selectSymbol(t){this.selectedSymbol=t}get fillPercentage(){let t=Number(this.config?.goalUsd??1e3),n=t>0?t:1e3;return Math.min(this.raised/n*100,100)}async donate(){if(aM&&!this.processing){Kd(this.config?.debug||!1,"Donation started",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="donate",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Kd(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Rm||(Rm=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new Rm(this.config?.plugNPlay||{});let o=this.pnp.getEnabledWallets();if(Kd(this.config?.debug||!1,"Available wallets",o),!o?.length)throw new Error("No wallets available");this.pendingAction="donate",this.showWalletModal=!0;return}catch(o){Kd(this.config?.debug||!1,"Wallet connection error:",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error";return}}Kd(this.config?.debug||!1,"Creating SDK for payment");let t=or(this.config),i=this.cryptoOptions.find(o=>o.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Kd(this.config?.debug||!1,"Donation payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let s=await t.sendUsd(this.selectedAmount,i,{context:"donation"});Kd(this.config?.debug||!1,"Donation payment completed",{resp:s}),this.raised+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:s.transactionId,status:s.status,raised:this.raised}),this.dispatchEvent(new CustomEvent("icpay-donation",{detail:{amount:this.selectedAmount,tx:s},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),i=this.cryptoOptions.find(l=>l.symbol===this.selectedSymbol).canisterId||await t.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),s=await t.startOnrampUsd(this.selectedAmount,i,{context:"donation:onramp"}),o=s?.metadata?.onramp?.sessionId||s?.metadata?.onramp?.session_id||null,a=s?.metadata?.paymentIntentId||s?.paymentIntentId||null,c=s?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=a,o?(this.onrampSessionId=o,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="donate"&&setTimeout(()=>this.donate(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?Ue`
5720
5720
  <div class="icpay-card icpay-section" style="text-align:center;">
5721
5721
  ${this.config?.progressBar?.enabled!==!1?Ue`
5722
5722
  <icpay-progress-bar
@@ -5795,7 +5795,7 @@ Make sure to test your application with a production build as repeat registratio
5795
5795
  border-color: rgba(239, 68, 68, 0.3);
5796
5796
  color: #ef4444;
5797
5797
  }
5798
- `],we([Yt({type:Object})],Pn.prototype,"config",2),we([Ce()],Pn.prototype,"selectedAmount",2),we([Ce()],Pn.prototype,"selectedSymbol",2),we([Ce()],Pn.prototype,"raised",2),we([Ce()],Pn.prototype,"processing",2),we([Ce()],Pn.prototype,"succeeded",2),we([Ce()],Pn.prototype,"availableLedgers",2),we([Ce()],Pn.prototype,"errorMessage",2),we([Ce()],Pn.prototype,"errorSeverity",2),we([Ce()],Pn.prototype,"errorAction",2),we([Ce()],Pn.prototype,"walletConnected",2),we([Ce()],Pn.prototype,"pendingAction",2),we([Ce()],Pn.prototype,"showWalletModal",2),we([Ce()],Pn.prototype,"showOnrampModal",2),we([Ce()],Pn.prototype,"onrampSessionId",2),we([Ce()],Pn.prototype,"onrampPaymentIntentId",2),we([Ce()],Pn.prototype,"onrampErrorMessage",2),Pn=we([Oi("icpay-donation-thermometer")],Pn);var cM=typeof window<"u",lM=null;function e2(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var ni=class extends pn{constructor(){super(...arguments);this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.onrampPollTimer=null;this.transakMessageHandlerBound=null;this.pnp=null;this.sdk=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}getSdk(){return this.sdk||(this.sdk=or(this.config)),this.sdk}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),cM&&(e2(this.config?.debug||!1,"Pay button connected",{config:this.config}),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="pay"&&this.pay()},0)}t.has("config")&&(this.sdk=null)}async loadVerifiedLedgers(){if(!(!cM||!this.config?.publishableKey))try{let n=await this.getSdk().client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(t){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:t},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}selectSymbol(t){this.selectedSymbol=t}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{lM||(lM=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new lM(this.config?.plugNPlay||{});let t=this.pnp.getEnabledWallets();if(e2(this.config?.debug||!1,"Available wallets",t),!t?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(t){return this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(e2(this.config?.debug||!1,"Connecting to wallet",{walletId:t}),!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(e2(this.config?.debug||!1,"Wallet connect result",n),!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="pay"&&setTimeout(()=>this.pay(),0)}catch(n){e2(this.config?.debug||!1,"Wallet connection error",n),this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}renderWalletModal(){if(!this.showWalletModal||!this.pnp)return null;let n=(this.pnp.getEnabledWallets()||[]).map(u=>({id:this.getWalletId(u),label:this.getWalletLabel(u),icon:this.getWalletIcon(u)})),i=this.config?.onramp?.enabled!==!1,s=5,o=Number(this.config?.amountUsd??0),a=i&&o>0&&o<s,c=Math.max(0,s-o),l=a?`Note: Minimum card amount is $${s}. You will pay about $${c.toFixed(2)} more.`:null;return So({visible:this.showWalletModal,wallets:n,isConnecting:!1,onSelect:u=>this.connectWithWallet(u),onClose:()=>{this.showWalletModal=!1},onCreditCard:i?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:i,creditCardTooltip:l})}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=Number(this.config?.amountUsd??0),n=this.getSdk(),i=this.selectedSymbol||"ICP",o=this.cryptoOptions.find(h=>h.symbol===i)?.canisterId||await n.client.getLedgerCanisterIdBySymbol(i),a=await n.startOnrampUsd(t,o,{context:"pay-button:onramp"}),c=a?.metadata?.onramp?.sessionId||a?.metadata?.onramp?.session_id||null,l=a?.metadata?.onramp?.errorMessage||null;this.onrampErrorMessage=l||null;let u=a?.metadata?.paymentIntentId||a?.paymentIntentId||null;this.onrampPaymentIntentId=u,c?(this.onrampSessionId=c,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||null,this.showOnrampModal=!0,ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"getLedgerBalance"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"sendFundsToLedger"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"notifyLedgerTransaction"}}))}catch{}this.showOnrampModal=!1,this.startOnrampPolling(s||void 0)}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=this.getSdk(),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1},o=a=>{s()};try{window.addEventListener("icpay-sdk-transaction-completed",o,{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}async pay(){if(!(!cM||this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config?.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let n=this.getSdk(),i=this.selectedSymbol||"ICP",o=this.cryptoOptions.find(u=>u.symbol===i)?.canisterId||await n.client.getLedgerCanisterIdBySymbol(i),a=Number(this.config?.amountUsd??0),c={context:"pay-button"},l=await n.sendUsd(a,o,c);this.config.onSuccess&&this.config.onSuccess({id:l.transactionId,status:l.status}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-pay",{detail:{amount:a,tx:l},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}render(){if(!this.config)return Ue`<div class="icpay-card icpay-section">Loading...</div>`;let n=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,s=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",o=s!=="none"&&(n||s==="dropdown"),a=s==="dropdown"?"dropdown":n?"buttons":"none",c=this.selectedSymbol||this.config?.defaultSymbol||"ICP",l=typeof this.config?.amountUsd=="number"?`${Number(this.config.amountUsd).toFixed(2)}`:"",h=(this.config?.buttonLabel||(typeof this.config?.amountUsd=="number"?"Pay ${amount} with {symbol}":"Pay with {symbol}")).replace("{amount}",l||"$0.00").replace("{symbol}",c),w=this.config?.progressBar?.enabled!==!1;return Ue`
5798
+ `],we([Yt({type:Object})],Pn.prototype,"config",2),we([Ce()],Pn.prototype,"selectedAmount",2),we([Ce()],Pn.prototype,"selectedSymbol",2),we([Ce()],Pn.prototype,"raised",2),we([Ce()],Pn.prototype,"processing",2),we([Ce()],Pn.prototype,"succeeded",2),we([Ce()],Pn.prototype,"availableLedgers",2),we([Ce()],Pn.prototype,"errorMessage",2),we([Ce()],Pn.prototype,"errorSeverity",2),we([Ce()],Pn.prototype,"errorAction",2),we([Ce()],Pn.prototype,"walletConnected",2),we([Ce()],Pn.prototype,"pendingAction",2),we([Ce()],Pn.prototype,"showWalletModal",2),we([Ce()],Pn.prototype,"showOnrampModal",2),we([Ce()],Pn.prototype,"onrampSessionId",2),we([Ce()],Pn.prototype,"onrampPaymentIntentId",2),we([Ce()],Pn.prototype,"onrampErrorMessage",2),Pn=we([Oi("icpay-donation-thermometer")],Pn);var cM=typeof window<"u",lM=null;function e2(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var ni=class extends pn{constructor(){super(...arguments);this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.onrampPollTimer=null;this.transakMessageHandlerBound=null;this.pnp=null;this.sdk=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}getSdk(){return this.sdk||(this.sdk=or(this.config)),this.sdk}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),cM&&(e2(this.config?.debug||!1,"Pay button connected",{config:this.config}),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(t){if(t.has("config")&&this.pendingAction&&this.config?.actorProvider){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="pay"&&this.pay()},0)}t.has("config")&&(this.sdk=null)}async loadVerifiedLedgers(){if(!(!cM||!this.config?.publishableKey))try{let n=await this.getSdk().client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(t){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:t},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}selectSymbol(t){this.selectedSymbol=t}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{lM||(lM=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new lM(this.config?.plugNPlay||{});let t=this.pnp.getEnabledWallets();if(e2(this.config?.debug||!1,"Available wallets",t),!t?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(t){return this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(e2(this.config?.debug||!1,"Connecting to wallet",{walletId:t}),!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(e2(this.config?.debug||!1,"Wallet connect result",n),!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="pay"&&setTimeout(()=>this.pay(),0)}catch(n){e2(this.config?.debug||!1,"Wallet connection error",n),this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}renderWalletModal(){if(!this.showWalletModal||!this.pnp)return null;let n=(this.pnp.getEnabledWallets()||[]).map(u=>({id:this.getWalletId(u),label:this.getWalletLabel(u),icon:this.getWalletIcon(u)})),i=this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,s=5,o=Number(this.config?.amountUsd??0),a=i&&o>0&&o<s,c=Math.max(0,s-o),l=a?`Note: Minimum card amount is $${s}. You will pay about $${c.toFixed(2)} more.`:null;return So({visible:this.showWalletModal,wallets:n,isConnecting:!1,onSelect:u=>this.connectWithWallet(u),onClose:()=>{this.showWalletModal=!1},onCreditCard:i?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:i,creditCardTooltip:l})}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=Number(this.config?.amountUsd??0),n=this.getSdk(),i=this.selectedSymbol||"ICP",o=this.cryptoOptions.find(h=>h.symbol===i)?.canisterId||await n.client.getLedgerCanisterIdBySymbol(i),a=await n.startOnrampUsd(t,o,{context:"pay-button:onramp"}),c=a?.metadata?.onramp?.sessionId||a?.metadata?.onramp?.session_id||null,l=a?.metadata?.onramp?.errorMessage||null;this.onrampErrorMessage=l||null;let u=a?.metadata?.paymentIntentId||a?.paymentIntentId||null;this.onrampPaymentIntentId=u,c?(this.onrampSessionId=c,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||null,this.showOnrampModal=!0,ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"getLedgerBalance"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"sendFundsToLedger"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"notifyLedgerTransaction"}}))}catch{}this.showOnrampModal=!1,this.startOnrampPolling(s||void 0)}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=this.getSdk(),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1},o=a=>{s()};try{window.addEventListener("icpay-sdk-transaction-completed",o,{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}async pay(){if(!(!cM||this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config?.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let n=this.getSdk(),i=this.selectedSymbol||"ICP",o=this.cryptoOptions.find(u=>u.symbol===i)?.canisterId||await n.client.getLedgerCanisterIdBySymbol(i),a=Number(this.config?.amountUsd??0),c={context:"pay-button"},l=await n.sendUsd(a,o,c);this.config.onSuccess&&this.config.onSuccess({id:l.transactionId,status:l.status}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-pay",{detail:{amount:a,tx:l},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}render(){if(!this.config)return Ue`<div class="icpay-card icpay-section">Loading...</div>`;let n=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,s=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",o=s!=="none"&&(n||s==="dropdown"),a=s==="dropdown"?"dropdown":n?"buttons":"none",c=this.selectedSymbol||this.config?.defaultSymbol||"ICP",l=typeof this.config?.amountUsd=="number"?`${Number(this.config.amountUsd).toFixed(2)}`:"",h=(this.config?.buttonLabel||(typeof this.config?.amountUsd=="number"?"Pay ${amount} with {symbol}":"Pay with {symbol}")).replace("{amount}",l||"$0.00").replace("{symbol}",c),w=this.config?.progressBar?.enabled!==!1;return Ue`
5799
5799
  <div class="icpay-card icpay-section">
5800
5800
  ${w?Ue`
5801
5801
  <icpay-progress-bar
@@ -5840,7 +5840,7 @@ Make sure to test your application with a production build as repeat registratio
5840
5840
  .error-message.info { background: rgba(59,130,246,0.1); border-color: rgba(59,130,246,0.3); color: #3b82f6; }
5841
5841
  .error-message.warning { background: rgba(245,158,11,0.1); border-color: rgba(245,158,11,0.3); color: #f59e0b; }
5842
5842
  .error-message.error { background: rgba(239,68,68,0.1); border-color: rgba(239,68,68,0.3); color: #ef4444; }
5843
- `],we([Yt({type:Object})],ni.prototype,"config",2),we([Ce()],ni.prototype,"selectedSymbol",2),we([Ce()],ni.prototype,"processing",2),we([Ce()],ni.prototype,"succeeded",2),we([Ce()],ni.prototype,"availableLedgers",2),we([Ce()],ni.prototype,"errorMessage",2),we([Ce()],ni.prototype,"errorSeverity",2),we([Ce()],ni.prototype,"errorAction",2),we([Ce()],ni.prototype,"walletConnected",2),we([Ce()],ni.prototype,"pendingAction",2),we([Ce()],ni.prototype,"showWalletModal",2),we([Ce()],ni.prototype,"showOnrampModal",2),we([Ce()],ni.prototype,"onrampSessionId",2),we([Ce()],ni.prototype,"onrampPaymentIntentId",2),we([Ce()],ni.prototype,"onrampErrorMessage",2),ni=we([Oi("icpay-pay-button")],ni);var uM=typeof window<"u",hM=null;function ULe(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Bn=class extends pn{constructor(){super(...arguments);this.amountUsd=0;this.hasUserAmount=!1;this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.pnp=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),uM&&(ULe(this.config?.debug||!1,"Amount input connected",{config:this.config}),this.amountUsd=Number(this.config?.defaultAmountUsd??0),this.hasUserAmount=!1,this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(t){if(t.has("config")&&(!this.hasUserAmount&&typeof this.config?.defaultAmountUsd=="number"&&(this.amountUsd===0||this.amountUsd==null||Number.isNaN(this.amountUsd))&&(this.amountUsd=Number(this.config.defaultAmountUsd)),!this.selectedSymbol&&this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol),!(this.config?.cryptoOptions&&this.config.cryptoOptions.length>0)&&this.availableLedgers.length===0&&this.loadVerifiedLedgers(),this.pendingAction&&this.config?.actorProvider)){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="pay"&&this.pay()},0)}}async loadVerifiedLedgers(){if(!(!uM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(t){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:t},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}onInputChange(t){let n=Number(this.config?.stepUsd??.5),i=Math.max(0,Number(t.target.value||0)),s=Math.round(i/n)*n;this.amountUsd=Number(s.toFixed(2)),this.hasUserAmount=!0}selectSymbol(t){this.selectedSymbol=t}isValidAmount(){let t=Number(this.config?.minUsd??.5),n=this.config?.maxUsd!==void 0?Number(this.config.maxUsd):1/0;return this.amountUsd>=t&&this.amountUsd<=n}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{if(hM||(hM=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new hM(this.config?.plugNPlay||{}),!this.pnp.getEnabledWallets()?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(t){return this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="pay"&&setTimeout(()=>this.pay(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),n=this.selectedSymbol||"ICP",s=this.cryptoOptions.find(h=>h.symbol===n)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(n),o=Number(this.amountUsd),a=await t.startOnrampUsd(o,s,{context:"amount-input:onramp"}),c=a?.metadata?.onramp?.sessionId||a?.metadata?.onramp?.session_id||null,l=a?.metadata?.paymentIntentId||a?.paymentIntentId||null,u=a?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,c?(this.onrampSessionId=c,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=u||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}async pay(){if(!(!uM||this.processing)){if(this.errorMessage=null,this.errorSeverity=null,this.errorAction=null,!this.isValidAmount()){this.errorMessage="Please enter a valid amount",this.errorSeverity="warning";return}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let n=or(this.config),i=this.selectedSymbol||"ICP",o=this.cryptoOptions.find(u=>u.symbol===i)?.canisterId||await n.client.getLedgerCanisterIdBySymbol(i),a=Number(this.amountUsd),c={context:"amount-input"},l=await n.sendUsd(a,o,c);this.config.onSuccess&&this.config.onSuccess({id:l.transactionId,status:l.status,amountUsd:a}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-amount-pay",{detail:{amount:a,tx:l},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}render(){if(!this.config)return Ue`<div class="icpay-card icpay-section">Loading...</div>`;let t=this.config?.placeholder||"Enter amount in USD",i=(this.config?.buttonLabel||"Pay ${amount} with {symbol}").replace("{amount}",this.amountUsd?`${Number(this.amountUsd).toFixed(2)}`:"$0.00").replace("{symbol}",this.selectedSymbol||this.config?.defaultSymbol||"ICP"),s=this.cryptoOptions.find(v=>v.symbol===(this.selectedSymbol||""))?.label||this.cryptoOptions[0]?.label||this.config?.defaultSymbol||"ICP",o=this.config?.progressBar?.mode||"modal",a=this.config?.showLedgerDropdown,c=a==="buttons"?"buttons":a==="none"?"none":"dropdown",u=(this.cryptoOptions?.length||0)>1,h=c!=="none"&&(u||c==="dropdown"),p=c==="dropdown"?"dropdown":u?"buttons":"none",y=this.config?.progressBar?.enabled!==!1&&(o==="modal"?!0:this.processing);return Ue`
5843
+ `],we([Yt({type:Object})],ni.prototype,"config",2),we([Ce()],ni.prototype,"selectedSymbol",2),we([Ce()],ni.prototype,"processing",2),we([Ce()],ni.prototype,"succeeded",2),we([Ce()],ni.prototype,"availableLedgers",2),we([Ce()],ni.prototype,"errorMessage",2),we([Ce()],ni.prototype,"errorSeverity",2),we([Ce()],ni.prototype,"errorAction",2),we([Ce()],ni.prototype,"walletConnected",2),we([Ce()],ni.prototype,"pendingAction",2),we([Ce()],ni.prototype,"showWalletModal",2),we([Ce()],ni.prototype,"showOnrampModal",2),we([Ce()],ni.prototype,"onrampSessionId",2),we([Ce()],ni.prototype,"onrampPaymentIntentId",2),we([Ce()],ni.prototype,"onrampErrorMessage",2),ni=we([Oi("icpay-pay-button")],ni);var uM=typeof window<"u",hM=null;function ULe(r,e,t){r&&(t!==void 0?console.log(`[ICPay Widget] ${e}`,t):console.log(`[ICPay Widget] ${e}`))}var Bn=class extends pn{constructor(){super(...arguments);this.amountUsd=0;this.hasUserAmount=!1;this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.pnp=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),uM&&(ULe(this.config?.debug||!1,"Amount input connected",{config:this.config}),this.amountUsd=Number(this.config?.defaultAmountUsd??0),this.hasUserAmount=!1,this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(t){if(t.has("config")&&(!this.hasUserAmount&&typeof this.config?.defaultAmountUsd=="number"&&(this.amountUsd===0||this.amountUsd==null||Number.isNaN(this.amountUsd))&&(this.amountUsd=Number(this.config.defaultAmountUsd)),!this.selectedSymbol&&this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol),!(this.config?.cryptoOptions&&this.config.cryptoOptions.length>0)&&this.availableLedgers.length===0&&this.loadVerifiedLedgers(),this.pendingAction&&this.config?.actorProvider)){let n=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{n==="pay"&&this.pay()},0)}}async loadVerifiedLedgers(){if(!(!uM||!this.config?.publishableKey))try{let n=await or(this.config).client.getVerifiedLedgers();this.availableLedgers=n.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(t){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:t},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}onInputChange(t){let n=Number(this.config?.stepUsd??.5),i=Math.max(0,Number(t.target.value||0)),s=Math.round(i/n)*n;this.amountUsd=Number(s.toFixed(2)),this.hasUserAmount=!0}selectSymbol(t){this.selectedSymbol=t}isValidAmount(){let t=Number(this.config?.minUsd??.5),n=this.config?.maxUsd!==void 0?Number(this.config.maxUsd):1/0;return this.amountUsd>=t&&this.amountUsd<=n}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{if(hM||(hM=(await Promise.resolve().then(()=>(nc(),rc))).PNP),this.pnp=new hM(this.config?.plugNPlay||{}),!this.pnp.getEnabledWallets()?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(t){return this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(t){return t&&(t.id||t.provider||t.key)||""}getWalletLabel(t){return t&&(t.label||t.name||t.title||t.id)||"Wallet"}getWalletIcon(t){return t&&(t.icon||t.logo||t.image)||null}async connectWithWallet(t){if(this.pnp)try{if(!t)throw new Error("No wallet ID provided");let n=await this.pnp.connect(t);if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:t}}))}catch{}this.config={...this.config,connectedWallet:n,actorProvider:(o,a)=>this.pnp.getActor({canisterId:o,idl:a,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let s=this.pendingAction;this.pendingAction=null,s==="pay"&&setTimeout(()=>this.pay(),0)}catch(n){this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=t=>this.onTransakMessage(t);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(t){let n=t?.data,i=n?.event_id||n?.eventId||n?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let s=n?.data?.id||n?.id||n?.webhookData?.id||null;this.startOnrampPolling(s||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=or(this.config),n=this.selectedSymbol||"ICP",s=this.cryptoOptions.find(h=>h.symbol===n)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(n),o=Number(this.amountUsd),a=await t.startOnrampUsd(o,s,{context:"amount-input:onramp"}),c=a?.metadata?.onramp?.sessionId||a?.metadata?.onramp?.session_id||null,l=a?.metadata?.paymentIntentId||a?.paymentIntentId||null,u=a?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,c?(this.onrampSessionId=c,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=u||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(t){this.onrampSessionId=null,this.onrampErrorMessage=t?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(t){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let n=this.onrampPaymentIntentId;if(!n)return;let i=or(this.config),s=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>s()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(n,5e3,t),this.onrampPollTimer=1}async pay(){if(!(!uM||this.processing)){if(this.errorMessage=null,this.errorSeverity=null,this.errorAction=null,!this.isValidAmount()){this.errorMessage="Please enter a valid amount",this.errorSeverity="warning";return}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let n=or(this.config),i=this.selectedSymbol||"ICP",o=this.cryptoOptions.find(u=>u.symbol===i)?.canisterId||await n.client.getLedgerCanisterIdBySymbol(i),a=Number(this.amountUsd),c={context:"amount-input"},l=await n.sendUsd(a,o,c);this.config.onSuccess&&this.config.onSuccess({id:l.transactionId,status:l.status,amountUsd:a}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-amount-pay",{detail:{amount:a,tx:l},bubbles:!0}))}catch(t){ro(t,{onError:n=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:n,bubbles:!0})),io(n)&&(this.errorMessage=no(n),this.errorSeverity=oo(n),this.errorAction=so(n))}})}finally{this.processing=!1}}}render(){if(!this.config)return Ue`<div class="icpay-card icpay-section">Loading...</div>`;let t=this.config?.placeholder||"Enter amount in USD",i=(this.config?.buttonLabel||"Pay ${amount} with {symbol}").replace("{amount}",this.amountUsd?`${Number(this.amountUsd).toFixed(2)}`:"$0.00").replace("{symbol}",this.selectedSymbol||this.config?.defaultSymbol||"ICP"),s=this.cryptoOptions.find(v=>v.symbol===(this.selectedSymbol||""))?.label||this.cryptoOptions[0]?.label||this.config?.defaultSymbol||"ICP",o=this.config?.progressBar?.mode||"modal",a=this.config?.showLedgerDropdown,c=a==="buttons"?"buttons":a==="none"?"none":"dropdown",u=(this.cryptoOptions?.length||0)>1,h=c!=="none"&&(u||c==="dropdown"),p=c==="dropdown"?"dropdown":u?"buttons":"none",y=this.config?.progressBar?.enabled!==!1&&(o==="modal"?!0:this.processing);return Ue`
5844
5844
  <div class="icpay-card icpay-section">
5845
5845
  ${y?Ue`
5846
5846
  <icpay-progress-bar
@@ -5882,7 +5882,7 @@ Make sure to test your application with a production build as repeat registratio
5882
5882
  ${this.errorAction?Ue`<button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">${this.errorAction}</button>`:""}
5883
5883
  </div>
5884
5884
  `:""}
5885
- ${(()=>{let C=(this.pnp?.getEnabledWallets?.()||[]).map(N=>({id:this.getWalletId(N),label:this.getWalletLabel(N),icon:this.getWalletIcon(N)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:C,isConnecting:!1,onSelect:N=>this.connectWithWallet(N),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let O=Number(this.amountUsd||0);return O>0&&O<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-O).toFixed(2)} more.`:null})()})})()}
5885
+ ${(()=>{let C=(this.pnp?.getEnabledWallets?.()||[]).map(N=>({id:this.getWalletId(N),label:this.getWalletLabel(N),icon:this.getWalletIcon(N)}));return So({visible:!!(this.showWalletModal&&this.pnp),wallets:C,isConnecting:!1,onSelect:N=>this.connectWithWallet(N),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let O=Number(this.amountUsd||0);return O>0&&O<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-O).toFixed(2)} more.`:null})()})})()}
5886
5886
 
5887
5887
  ${this.showOnrampModal?_s({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
5888
5888
  </div>