coinley-pay 0.0.7 → 0.0.8

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.
package/dist/index.umd.js CHANGED
@@ -19,5 +19,5 @@ const zb=BigInt(0),qb=BigInt(1);function $b(e,t){const r=t.negate();return e?r:t
19
19
  const S_=(e,t)=>(e+(e>=0?t:-t)/P_)/t;function C_(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function I_(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return eb(r.lowS,"lowS"),eb(r.prehash,"prehash"),void 0!==r.format&&C_(r.format),r}class E_ extends Error{constructor(e=""){super(e)}}const A_={Err:E_,_tlv:{encode:(e,t)=>{const{Err:r}=A_;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=rb(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const o=n>127?rb(i.length/2|128):"";return rb(e)+o+i+t},decode(e,t){const{Err:r}=A_;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let o=0;if(!!(128&i)){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const s=t.subarray(n,n+e);if(s.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===s[0])throw new r("tlv.decode(long): zero leftmost byte");for(const t of s)o=o<<8|t;if(n+=e,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=i;const s=t.subarray(n,n+o);if(s.length!==o)throw new r("tlv.decode: wrong value length");return{v:s,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=A_;if(e<N_)throw new t("integer: negative integers are not allowed");let r=rb(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=A_;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return ib(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=A_,i=cb("signature",e),{v:o,l:s}=n.decode(48,i);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=A_,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},N_=BigInt(0),M_=BigInt(1),P_=BigInt(2),T_=BigInt(3),O_=BigInt(4);function B_(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let i=cb("private key",t);try{n=e.fromBytes(i)}catch(ud){throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function R_(e,t={}){const r=tw("weierstrass",e,t),{Fp:n,Fn:i}=r;let o=r.CURVE;const{h:s,n:a}=o;fb(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(o.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=L_(n,i);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,r){const{x:i,y:o}=t.toAffine(),s=n.toBytes(i);if(eb(r,"isCompressed"),r){u();return Kg(j_(!n.isOdd(o)),s)}return Kg(Uint8Array.of(4),s,n.toBytes(o))},h=t.fromBytes||function(e){tb(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=l,i=e.length,o=e[0],s=e.subarray(1);if(i!==t||2!==o&&3!==o){if(i===r&&4===o){const e=n.BYTES,t=n.fromBytes(s.subarray(0,e)),r=n.fromBytes(s.subarray(e,2*e));if(!f(t,r))throw new Error("bad point: is not on curve");return{x:t,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${r}`)}{const e=n.fromBytes(s);if(!n.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=p(e);let r;try{r=n.sqrt(t)}catch(a){const e=a instanceof Error?": "+a.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}u();return!(1&~o)!==n.isOdd(r)&&(r=n.neg(r)),{x:e,y:r}}};function p(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,o.a)),o.b)}function f(e,t){const r=n.sqr(t),i=p(e);return n.eql(r,i)}if(!f(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const m=n.mul(n.pow(o.a,T_),O_),g=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(m,g)))throw new Error("bad curve params: a or b");function y(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function v(e){if(!(e instanceof _))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,r){const[[n,i],[o,s]]=t,a=S_(s*e,r),c=S_(-i*e,r);let l=e-a*n-c*o,u=-a*i-c*s;const d=l<N_,h=u<N_;d&&(l=-l),h&&(u=-u);const p=pb(Math.ceil(hb(r)/2))+M_;if(l<N_||l>=p||u<N_||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,i.ORDER)}const w=mb((e,t)=>{const{X:r,Y:i,Z:o}=e;if(n.eql(o,n.ONE))return{x:r,y:i};const s=e.is0();null==t&&(t=s?n.ONE:n.inv(o));const a=n.mul(r,t),c=n.mul(i,t),l=n.mul(o,t);if(s)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),x=mb(e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:i}=e.toAffine();if(!n.isValid(r)||!n.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(r,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(e,t,r,i,o){return r=new _(n.mul(r.X,e),r.Y,r.Z),t=$b(i,t),r=$b(o,r),t.add(r)}class _{constructor(e,t,r){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof _)throw new Error("projective point not allowed");return n.is0(t)&&n.is0(r)?_.ZERO:new _(t,r,n.ONE)}static fromBytes(e){const t=_.fromAffine(h(tb(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return _.fromBytes(cb("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return C.createCache(this,e),t||this.multiply(T_),this}assertValidity(){x(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){v(e);const{X:t,Y:r,Z:i}=this,{X:o,Y:s,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(o,i)),l=n.eql(n.mul(r,a),n.mul(s,i));return c&&l}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=o,r=n.mul(t,T_),{X:i,Y:s,Z:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,d=n.mul(i,i),h=n.mul(s,s),p=n.mul(a,a),f=n.mul(i,s);return f=n.add(f,f),u=n.mul(i,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,p),l=n.add(c,l),c=n.sub(h,l),l=n.add(h,l),l=n.mul(c,l),c=n.mul(f,c),u=n.mul(r,u),p=n.mul(e,p),f=n.sub(d,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(d,d),d=n.add(u,d),d=n.add(d,p),d=n.mul(d,f),l=n.add(l,d),p=n.mul(s,a),p=n.add(p,p),d=n.mul(p,f),c=n.sub(c,d),u=n.mul(p,h),u=n.add(u,u),u=n.add(u,u),new _(c,l,u)}add(e){v(e);const{X:t,Y:r,Z:i}=this,{X:s,Y:a,Z:c}=e;let l=n.ZERO,u=n.ZERO,d=n.ZERO;const h=o.a,p=n.mul(o.b,T_);let f=n.mul(t,s),m=n.mul(r,a),g=n.mul(i,c),y=n.add(t,r),b=n.add(s,a);y=n.mul(y,b),b=n.add(f,m),y=n.sub(y,b),b=n.add(t,i);let w=n.add(s,c);return b=n.mul(b,w),w=n.add(f,g),b=n.sub(b,w),w=n.add(r,i),l=n.add(a,c),w=n.mul(w,l),l=n.add(m,g),w=n.sub(w,l),d=n.mul(h,b),l=n.mul(p,g),d=n.add(l,d),l=n.sub(m,d),d=n.add(m,d),u=n.mul(l,d),m=n.add(f,f),m=n.add(m,f),g=n.mul(h,g),b=n.mul(p,b),m=n.add(m,g),g=n.sub(f,g),g=n.mul(h,g),b=n.add(b,g),f=n.mul(m,b),u=n.add(u,f),f=n.mul(w,b),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,m),d=n.mul(w,d),d=n.add(d,f),new _(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(_.ZERO)}multiply(e){const{endo:r}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let n,o;const s=e=>C.cached(this,e,e=>Wb(_,e));if(r){const{k1neg:t,k1:i,k2neg:a,k2:c}=b(e),{p:l,f:u}=s(i),{p:d,f:h}=s(c);o=u.add(h),n=k(r.beta,l,d,t,a)}else{const{p:t,f:r}=s(e);n=t,o=r}return Wb(_,[n,o])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===N_||n.is0())return _.ZERO;if(e===M_)return n;if(C.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:i,k2neg:o,k2:s}=b(e),{p1:a,p2:c}=function(e,t,r,n){let i=t,o=e.ZERO,s=e.ZERO;for(;r>zb||n>zb;)r&qb&&(o=o.add(i)),n&qb&&(s=s.add(i)),i=i.double(),r>>=qb,n>>=qb;return{p1:o,p2:s}}(_,n,i,s);return k(r.beta,a,c,t,o)}return C.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===M_||(e?e(_,this):C.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===M_?this:e?e(_,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return eb(e,"isCompressed"),this.assertValidity(),d(_,this,e)}toHex(e=!0){return Dg(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return Wb(_,e)}static msm(e,t){return Qb(_,i,e,t)}static fromPrivateKey(e){return _.BASE.multiply(B_(i,e))}}_.BASE=new _(o.Gx,o.Gy,n.ONE),_.ZERO=new _(n.ZERO,n.ONE,n.ZERO),_.Fp=n,_.Fn=i;const S=i.BITS,C=new Xb(_,t.endo?Math.ceil(S/2):S);return _.BASE.precompute(8),_}function j_(e){return Uint8Array.of(e?2:3)}function L_(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function D_(e,t={}){const{Fn:r}=e,n=t.randomBytes||Jg,i=Object.assign(L_(e.Fp,r),{seed:Fb(r.ORDER)});function o(e){try{return!!B_(r,e)}catch(ud){return!1}}function s(e=n(i.seed)){return function(e,t,r=!1){const n=e.length,i=Ub(t),o=Fb(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);const s=Ib(r?ob(e):ib(e),t-yb)+yb;return r?ab(s,i):sb(s,i)}(tb(e,i.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(B_(r,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:o,publicKeyUncompressed:s}=i;if(r.allowedLengths||n===o)return;const a=cb("key",t).length;return a===o||a===s}const l={isValidSecretKey:o,isValidPublicKey:function(t,r){const{publicKey:n,publicKeyUncompressed:o}=i;try{const i=t.length;return(!0!==r||i===n)&&((!1!==r||i===o)&&!!e.fromBytes(t))}catch(ud){return!1}},randomSecretKey:s,isValidPrivateKey:o,randomPrivateKey:s,normPrivateKeyToScalar:e=>B_(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,n,i=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(n))throw new Error("second arg must be public key");const o=B_(r,t);return e.fromHex(n).multiply(o).toBytes(i)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:i})}function U_(e,t,r={}){Ag(t),fb(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Jg,i=r.hmac||((e,...r)=>zv(t,e,Kg(...r))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=D_(e,r),f={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},m="compact";function g(e){return e>a>>M_}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class v{constructor(e,t,r){this.r=y("r",e),this.s=y("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t=m){let r;if(function(e,t){C_(t);const r=p.signature;tb(e,"compact"===t?r:"recovered"===t?r+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:r}=A_.toSig(tb(e));return new v(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=s.BYTES,i=e.subarray(0,n),o=e.subarray(n,2*n);return new v(s.fromBytes(i),s.fromBytes(o),r)}static fromHex(e,t){return this.fromBytes(Gg(e),t)}addRecoveryBit(e){return new v(this.r,this.s,e)}recoverPublicKey(t){const r=o.ORDER,{r:n,s:i,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*P_<r&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!o.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=o.toBytes(l),d=e.fromBytes(Kg(j_(!(1&c)),u)),h=s.inv(l),p=w(cb("msgHash",t)),f=s.create(-p*h),m=s.create(i*h),g=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(m));if(g.is0())throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=m){if(C_(e),"der"===e)return Gg(A_.hexFromSig(this));const t=s.toBytes(this.r),r=s.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return Kg(Uint8Array.of(this.recovery),t,r)}return Kg(t,r)}toHex(e){return Dg(this.toBytes(e))}assertValidity(){}static fromCompact(e){return v.fromBytes(cb("sig",e),"compact")}static fromDER(e){return v.fromBytes(cb("sig",e),"der")}normalizeS(){return this.hasHighS()?new v(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Dg(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Dg(this.toBytes("compact"))}}const b=r.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=ib(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},w=r.bits2int_modN||function(e){return s.create(b(e))},x=pb(c);function k(e){return db("num < 2^"+c,e,N_,x),s.toBytes(e)}function _(e,r){return tb(e,void 0,"message"),r?tb(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:e,sign:function(r,o,a={}){r=cb("message",r);const{seed:c,k2sig:l}=function(t,r,i){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");const{lowS:o,prehash:a,extraEntropy:c}=I_(i,f);t=_(t,a);const l=w(t),u=B_(s,r),d=[k(u),k(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;d.push(cb("extraEntropy",e))}const h=Kg(...d),m=l;return{seed:h,k2sig:function(t){const r=b(t);if(!s.isValidNot0(r))return;const n=s.inv(r),i=e.BASE.multiply(r).toAffine(),a=s.create(i.x);if(a===N_)return;const c=s.create(n*s.create(m+a*u));if(c===N_)return;let l=(i.x===a?0:2)|Number(i.y&M_),d=c;return o&&g(c)&&(d=s.neg(c),l^=1),new v(a,d,l)}}}(r,o,a);return function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");const n=e=>new Uint8Array(e),i=e=>Uint8Array.of(e);let o=n(e),s=n(e),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},l=(...e)=>r(s,o,...e),u=(e=n(0))=>{s=l(i(0),e),o=l(),0!==e.length&&(s=l(i(1),e),o=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){o=l();const t=o.slice();r.push(t),e+=o.length}return Kg(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(d()));)u();return c(),r}}(t.outputLen,s.BYTES,i)(c,l)},verify:function(t,r,n,i={}){const{lowS:o,prehash:a,format:c}=I_(i,f);if(n=cb("publicKey",n),r=_(cb("message",r),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const r="string"==typeof e||Cg(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new v(e.r,e.s);else if(r){try{t=v.fromBytes(cb("sig",e),"der")}catch(i){if(!(i instanceof A_.Err))throw i}if(!t)try{t=v.fromBytes(cb("sig",e),"compact")}catch(ud){return!1}}return t||!1}(t):v.fromBytes(cb("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(o&&l.hasHighS())return!1;const{r:i,s:a}=l,c=w(r),u=s.inv(a),d=s.create(c*u),h=s.create(i*u),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(p.is0())return!1;return s.create(p.x)===i}catch(u){return!1}},recoverPublicKey:function(e,t,r={}){const{prehash:n}=I_(r,f);return t=_(t,n),v.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:v,hash:t})}function F_(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:Db(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function z_(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:i}=F_(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,Lb(r.Fn.ORDER,r.Fn.BITS))})}(e,U_(R_(t,r),n,i))}
20
20
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
21
21
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
22
- const q_={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},$_={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},W_=BigInt(2);const H_=Db(q_.p,{sqrt:function(e){const t=q_.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Eb(u,r,t)*u%t,h=Eb(d,r,t)*u%t,p=Eb(h,W_,t)*l%t,f=Eb(p,i,t)*p%t,m=Eb(f,o,t)*f%t,g=Eb(m,a,t)*m%t,y=Eb(g,c,t)*g%t,v=Eb(y,a,t)*m%t,b=Eb(v,r,t)*u%t,w=Eb(b,s,t)*f%t,x=Eb(w,n,t)*l%t,k=Eb(x,W_,t);if(!H_.eql(H_.sqr(k),e))throw new Error("Cannot find square root");return k}}),G_=function(e,t){const r=t=>z_({...e,hash:t});return{...r(t),create:r}}({...q_,Fp:H_,lowS:!0,endo:$_},Ny);function V_(e){try{return bw.ExtendedPoint.fromHex(e),!0}catch{return!1}}bw.utils.randomPrivateKey,bw.getPublicKey;const K_=bw.verify,Z_=e=>N.isBuffer(e)?e:e instanceof Uint8Array?N.from(e.buffer,e.byteOffset,e.byteLength):N.from(e);class Y_{constructor(e){Object.assign(this,e)}encode(){return N.from(cx(J_,this))}static decode(e){return dx(J_,this,e)}static decodeUnchecked(e){return Zw(J_,this,e)}}const J_=new Map;var X_;const Q_=32;let eS=1;class tS extends Y_{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=Pw.decode(e);if(t.length!=Q_)throw new Error("Invalid public key input");this._bn=new Iw(t)}else this._bn=new Iw(e);if(this._bn.byteLength()>Q_)throw new Error("Invalid public key input")}}static unique(){const e=new tS(eS);return eS+=1,new tS(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Pw.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(N);if(e.length===Q_)return e;const t=N.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,r){const n=N.concat([e.toBuffer(),N.from(t),r.toBuffer()]),i=Py(n);return new tS(i)}static createProgramAddressSync(e,t){let r=N.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");r=N.concat([r,Z_(e)])}),r=N.concat([r,t.toBuffer(),N.from("ProgramDerivedAddress")]);const n=Py(r);if(V_(n))throw new Error("Invalid seeds, address must fall off the curve");return new tS(n)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let r,n=255;for(;0!=n;){try{const i=e.concat(N.from([n]));r=this.createProgramAddressSync(i,t)}catch(yA){if(yA instanceof TypeError)throw yA;n--;continue}return[r,n]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return V_(new tS(e).toBytes())}}X_=tS,tS.default=new X_("11111111111111111111111111111111"),J_.set(tS,{kind:"struct",fields:[["_bn","u256"]]}),new tS("BPFLoader1111111111111111111111111111111111");const rS=1232;class nS extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(nS.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class iS extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(iS.prototype,"name",{value:"TransactionExpiredTimeoutError"});class oS extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(oS.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class sS{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,r)=>{t.set(e.toBase58(),r)});const r=e=>{const r=t.get(e.toBase58());if(void 0===r)throw new Error("Encountered an unknown instruction account key during compilation");return r};return e.map(e=>({programIdIndex:r(e.programId),accountKeyIndexes:e.keys.map(e=>r(e.pubkey)),data:e.data}))}}const aS=(e="publicKey")=>ik(32,e),cS=(e="string")=>{const t=rk([Qx("length"),Qx("lengthPadding"),ik(Yx(Qx(),-8),"chars")],e),r=t.decode.bind(t),n=t.encode.bind(t),i=t;return i.decode=(e,t)=>r(e,t).chars.toString(),i.encode=(e,t,r)=>{const i={chars:N.from(e,"utf8")};return n(i,t,r)},i.alloc=e=>Qx().span+Qx().span+N.from(e,"utf8").length,i};function lS(e,t){const r=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const n=t[e.property];if(Array.isArray(n))return n.length*r(e.elementLayout)}else if("fields"in e)return lS({layout:e},t[e.property]);return 0};let n=0;return e.layout.fields.forEach(e=>{n+=r(e)}),n}function uS(e){let t=0,r=0;for(;;){let n=e.shift();if(t|=(127&n)<<7*r,r+=1,!(128&n))break}return t}function dS(e,t){let r=t;for(;;){let t=127&r;if(r>>=7,0==r){e.push(t);break}t|=128,e.push(t)}}function hS(e,t){if(!e)throw new Error(t||"Assertion failed")}class pS{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const r=new Map,n=e=>{const t=e.toBase58();let n=r.get(t);return void 0===n&&(n={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(t,n)),n},i=n(t);i.isSigner=!0,i.isWritable=!0;for(const o of e){n(o.programId).isInvoked=!0;for(const e of o.keys){const t=n(e.pubkey);t.isSigner||(t.isSigner=e.isSigner),t.isWritable||(t.isWritable=e.isWritable)}}return new pS(t,r)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];hS(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),r=e.filter(([,e])=>e.isSigner&&!e.isWritable),n=e.filter(([,e])=>!e.isSigner&&e.isWritable),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),o={numRequiredSignatures:t.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:i.length};{hS(t.length>0,"Expected at least one writable signer key");const[e]=t[0];hS(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new tS(e)),...r.map(([e])=>new tS(e)),...n.map(([e])=>new tS(e)),...i.map(([e])=>new tS(e))]]}extractTableLookup(e){const[t,r]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[n,i]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==n.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:n},{writable:r,readonly:i}]}drainKeysFoundInLookupTable(e,t){const r=new Array,n=new Array;for(const[i,o]of this.keyMetaMap.entries())if(t(o)){const t=new tS(i),o=e.findIndex(e=>e.equals(t));o>=0&&(hS(o<256,"Max lookup table index exceeded"),r.push(o),n.push(t),this.keyMetaMap.delete(i))}return[r,n]}}const fS="Reached end of buffer unexpectedly";function mS(e){if(0===e.length)throw new Error(fS);return e.shift()}function gS(e,...t){const[r]=t;if(2===t.length?r+(t[1]??0)>e.length:r>=e.length)throw new Error(fS);return e.splice(...t)}class yS{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new tS(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Pw.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new sS(this.staticAccountKeys)}static compile(e){const t=pS.compile(e.instructions,e.payerKey),[r,n]=t.getMessageComponents(),i=new sS(n).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Pw.encode(e.data)}));return new yS({header:r,accountKeys:n,recentBlockhash:e.recentBlockhash,instructions:i})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];dS(t,e);const r=this.instructions.map(e=>{const{accounts:t,programIdIndex:r}=e,n=Array.from(Pw.decode(e.data));let i=[];dS(i,t.length);let o=[];return dS(o,n.length),{programIdIndex:r,keyIndicesCount:N.from(i),keyIndices:t,dataLength:N.from(o),data:n}});let n=[];dS(n,r.length);let i=N.alloc(rS);N.from(n).copy(i);let o=n.length;r.forEach(e=>{const t=rk([Jx("programIdIndex"),ik(e.keyIndicesCount.length,"keyIndicesCount"),nk(Jx("keyIndex"),e.keyIndices.length,"keyIndices"),ik(e.dataLength.length,"dataLength"),nk(Jx("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=rk([ik(1,"numRequiredSignatures"),ik(1,"numReadonlySignedAccounts"),ik(1,"numReadonlyUnsignedAccounts"),ik(t.length,"keyCount"),nk(aS("key"),e,"keys"),aS("recentBlockhash")]),a={numRequiredSignatures:N.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:N.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:N.from([this.header.numReadonlyUnsignedAccounts]),keyCount:N.from(t),keys:this.accountKeys.map(e=>Z_(e.toBytes())),recentBlockhash:Pw.decode(this.recentBlockhash)};let c=N.alloc(2048);const l=s.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const r=mS(t);if(r!==(127&r))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const n=mS(t),i=mS(t),o=uS(t);let s=[];for(let d=0;d<o;d++){const e=gS(t,0,Q_);s.push(new tS(N.from(e)))}const a=gS(t,0,Q_),c=uS(t);let l=[];for(let d=0;d<c;d++){const e=mS(t),r=gS(t,0,uS(t)),n=gS(t,0,uS(t)),i=Pw.encode(N.from(n));l.push({programIdIndex:e,accounts:r,data:i})}const u={header:{numRequiredSignatures:r,numReadonlySignedAccounts:n,numReadonlyUnsignedAccounts:i},recentBlockhash:Pw.encode(N.from(a)),accountKeys:s,instructions:l};return new yS(u)}}class vS{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new sS(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,r=this.staticAccountKeys.length;if(e>=r){return e-r<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<r-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const r of this.addressTableLookups){const n=e.find(e=>e.key.equals(r.accountKey));if(!n)throw new Error(`Failed to find address lookup table account for table key ${r.accountKey.toBase58()}`);for(const e of r.writableIndexes){if(!(e<n.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${r.accountKey.toBase58()}`);t.writable.push(n.state.addresses[e])}for(const e of r.readonlyIndexes){if(!(e<n.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${r.accountKey.toBase58()}`);t.readonly.push(n.state.addresses[e])}}return t}static compile(e){const t=pS.compile(e.instructions,e.payerKey),r=new Array,n={writable:new Array,readonly:new Array},i=e.addressLookupTableAccounts||[];for(const c of i){const e=t.extractTableLookup(c);if(void 0!==e){const[t,{writable:i,readonly:o}]=e;r.push(t),n.writable.push(...i),n.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new sS(s,n).compileInstructions(e.instructions);return new vS({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:r})}serialize(){const e=Array();dS(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),r=Array();dS(r,this.compiledInstructions.length);const n=this.serializeAddressTableLookups(),i=Array();dS(i,this.addressTableLookups.length);const o=rk([Jx("prefix"),rk([Jx("numRequiredSignatures"),Jx("numReadonlySignedAccounts"),Jx("numReadonlyUnsignedAccounts")],"header"),ik(e.length,"staticAccountKeysLength"),nk(aS(),this.staticAccountKeys.length,"staticAccountKeys"),aS("recentBlockhash"),ik(r.length,"instructionsLength"),ik(t.length,"serializedInstructions"),ik(i.length,"addressTableLookupsLength"),ik(n.length,"serializedAddressTableLookups")]),s=new Uint8Array(rS),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Pw.decode(this.recentBlockhash),instructionsLength:new Uint8Array(r),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:n},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(rS);for(const r of this.compiledInstructions){const n=Array();dS(n,r.accountKeyIndexes.length);const i=Array();dS(i,r.data.length);e+=rk([Jx("programIdIndex"),ik(n.length,"encodedAccountKeyIndexesLength"),nk(Jx(),r.accountKeyIndexes.length,"accountKeyIndexes"),ik(i.length,"encodedDataLength"),ik(r.data.length,"data")]).encode({programIdIndex:r.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(n),accountKeyIndexes:r.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:r.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(rS);for(const r of this.addressTableLookups){const n=Array();dS(n,r.writableIndexes.length);const i=Array();dS(i,r.readonlyIndexes.length);e+=rk([aS("accountKey"),ik(n.length,"encodedWritableIndexesLength"),nk(Jx(),r.writableIndexes.length,"writableIndexes"),ik(i.length,"encodedReadonlyIndexesLength"),nk(Jx(),r.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:r.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(n),writableIndexes:r.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:r.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const r=mS(t),n=127&r;hS(r!==n,"Expected versioned message but received legacy message");hS(0===n,`Expected versioned message with version 0 but found version ${n}`);const i={numRequiredSignatures:mS(t),numReadonlySignedAccounts:mS(t),numReadonlyUnsignedAccounts:mS(t)},o=[],s=uS(t);for(let h=0;h<s;h++)o.push(new tS(gS(t,0,Q_)));const a=Pw.encode(gS(t,0,Q_)),c=uS(t),l=[];for(let h=0;h<c;h++){const e=mS(t),r=gS(t,0,uS(t)),n=uS(t),i=new Uint8Array(gS(t,0,n));l.push({programIdIndex:e,accountKeyIndexes:r,data:i})}const u=uS(t),d=[];for(let h=0;h<u;h++){const e=new tS(gS(t,0,Q_)),r=gS(t,0,uS(t)),n=gS(t,0,uS(t));d.push({accountKey:e,writableIndexes:r,readonlyIndexes:n})}return new vS({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}let bS=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const wS=N.alloc(64).fill(0);class xS{constructor(e){this.keys=void 0,this.programId=void 0,this.data=N.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:r})=>({pubkey:e.toJSON(),isSigner:t,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class kS{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:r}=e;this.minNonceContextSlot=t,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:r}=e;this.recentBlockhash=t,this.lastValidBlockHeight=r}else{const{recentBlockhash:t,nonceInfo:r}=e;r&&(this.nonceInfo=r),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new xS(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,r;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length<1&&console.warn("No instructions provided"),this.feePayer)r=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");r=this.signatures[0].publicKey}for(let f=0;f<t.length;f++)if(void 0===t[f].programId)throw new Error(`Transaction instruction index ${f} has undefined program id`);const n=[],i=[];t.forEach(e=>{e.keys.forEach(e=>{i.push({...e})});const t=e.programId.toString();n.includes(t)||n.push(t)}),n.forEach(e=>{i.push({pubkey:new tS(e),isSigner:!1,isWritable:!1})});const o=[];i.forEach(e=>{const t=e.pubkey.toString(),r=o.findIndex(e=>e.pubkey.toString()===t);r>-1?(o[r].isWritable=o[r].isWritable||e.isWritable,o[r].isSigner=o[r].isSigner||e.isSigner):o.push(e)}),o.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=o.findIndex(e=>e.pubkey.equals(r));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const f of this.signatures){const e=o.findIndex(e=>e.pubkey.equals(f.publicKey));if(!(e>-1))throw new Error(`unknown signer: ${f.publicKey.toString()}`);o[e].isSigner||(o[e].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."))}let a=0,c=0,l=0;const u=[],d=[];o.forEach(({pubkey:e,isSigner:t,isWritable:r})=>{t?(u.push(e.toString()),a+=1,r||(c+=1)):(d.push(e.toString()),r||(l+=1))});const h=u.concat(d),p=t.map(e=>{const{data:t,programId:r}=e;return{programIdIndex:h.indexOf(r.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:Pw.encode(t)}});return p.forEach(e=>{hS(e.programIdIndex>=0),e.accounts.forEach(e=>hS(e>=0))}),new yS({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:l},accountKeys:h,recentBlockhash:e,instructions:p})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,r)=>t[r].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const r=e.toString();return!t.has(r)&&(t.add(r),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,r=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),r.push(i))}this.signatures=r.map(e=>({signature:null,publicKey:e.publicKey}));const n=this._compile();this._partialSign(n,...r)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,r=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),r.push(i))}const n=this._compile();this._partialSign(n,...r)}_partialSign(e,...t){const r=e.serialize();t.forEach(e=>{const t=((e,t)=>bw.sign(e,t.slice(0,32)))(r,e.secretKey);this._addSignature(e.publicKey,Z_(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){hS(64===t.length);const r=this.signatures.findIndex(t=>e.equals(t.publicKey));if(r<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[r].signature=N.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const r={};for(const{signature:n,publicKey:i}of this.signatures)null===n?t&&(r.missing||(r.missing=[])).push(i):K_(n,e,i.toBytes())||(r.invalid||(r.invalid=[])).push(i);return r.invalid||r.missing?r:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),n=this.serializeMessage();if(r){const e=this._getMessageSignednessErrors(n,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(n)}_serialize(e){const{signatures:t}=this,r=[];dS(r,t.length);const n=r.length+64*t.length+e.length,i=N.alloc(n);return hS(t.length<256),N.from(r).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(hS(64===e.length,"signature has invalid length"),N.from(e).copy(i,r.length+64*t))}),e.copy(i,r.length+64*t.length),hS(i.length<=rS,`Transaction too large: ${i.length} > 1232`),i}get keys(){return hS(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return hS(1===this.instructions.length),this.instructions[0].programId}get data(){return hS(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const r=uS(t);let n=[];for(let i=0;i<r;i++){const e=gS(t,0,64);n.push(Pw.encode(N.from(e)))}return kS.populate(yS.from(t),n)}static populate(e,t=[]){const r=new kS;return r.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(r.feePayer=e.accountKeys[0]),t.forEach((t,n)=>{const i={signature:t==Pw.encode(wS)?null:Pw.decode(t),publicKey:e.accountKeys[n]};r.signatures.push(i)}),e.instructions.forEach(t=>{const n=t.accounts.map(t=>{const n=e.accountKeys[t];return{pubkey:n,isSigner:r.signatures.some(e=>e.publicKey.toString()===n.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});r.instructions.push(new xS({keys:n,programId:e.accountKeys[t.programIdIndex],data:Pw.decode(t.data)}))}),r._message=e,r._json=r.toJSON(),r}}new tS("SysvarC1ock11111111111111111111111111111111"),new tS("SysvarEpochSchedu1e111111111111111111111111"),new tS("Sysvar1nstructions1111111111111111111111111");const _S=new tS("SysvarRecentB1ockHashes11111111111111111111"),SS=new tS("SysvarRent111111111111111111111111111111111");new tS("SysvarRewards111111111111111111111111111111"),new tS("SysvarS1otHashes111111111111111111111111111"),new tS("SysvarS1otHistory11111111111111111111111111"),new tS("SysvarStakeHistory1111111111111111111111111");class CS extends Error{constructor({action:e,signature:t,transactionMessage:r,logs:n}){const i=n?`Logs: \n${JSON.stringify(n.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${r}. `+i+o;break;case"simulate":s=`Simulation failed. \nMessage: ${r}. \n`+i+o;break;default:s=`Unknown action '${(e=>e)(e)}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=r,this.transactionLogs=n||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,r)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const r=e.meta.logMessages;this.transactionLogs=r,t(r)}else r(new Error("Log messages not found"))}).catch(r)})),await this.transactionLogs}}class IS extends Error{constructor({code:e,message:t,data:r},n){super(null!=n?`${n}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=r,this.name="SolanaJSONRPCError"}}function ES(e){return new Promise(t=>setTimeout(t,e))}function AS(e,t){const r=e.layout.span>=0?e.layout.span:lS(e,t),n=N.alloc(r),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,n),n}const NS=ek("lamportsPerSignature"),MS=rk([Qx("version"),Qx("state"),aS("authorizedPubkey"),aS("nonce"),rk([NS],"feeCalculator")]),PS=MS.span;class TS{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=MS.decode(Z_(e),0);return new TS({authorizedPubkey:new tS(t.authorizedPubkey),nonce:new tS(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function OS(e){const t=ik(8,e),r=t.decode.bind(t),n=t.encode.bind(t),i=t,o=pk();return i.decode=(e,t)=>{const n=r(e,t);return o.decode(n)},i.encode=(e,t,r)=>{const i=o.encode(e);return n(i,t,r)},i}const BS=Object.freeze({Create:{index:0,layout:rk([Qx("instruction"),tk("lamports"),tk("space"),aS("programId")])},Assign:{index:1,layout:rk([Qx("instruction"),aS("programId")])},Transfer:{index:2,layout:rk([Qx("instruction"),OS("lamports")])},CreateWithSeed:{index:3,layout:rk([Qx("instruction"),aS("base"),cS("seed"),tk("lamports"),tk("space"),aS("programId")])},AdvanceNonceAccount:{index:4,layout:rk([Qx("instruction")])},WithdrawNonceAccount:{index:5,layout:rk([Qx("instruction"),tk("lamports")])},InitializeNonceAccount:{index:6,layout:rk([Qx("instruction"),aS("authorized")])},AuthorizeNonceAccount:{index:7,layout:rk([Qx("instruction"),aS("authorized")])},Allocate:{index:8,layout:rk([Qx("instruction"),tk("space")])},AllocateWithSeed:{index:9,layout:rk([Qx("instruction"),aS("base"),cS("seed"),tk("space"),aS("programId")])},AssignWithSeed:{index:10,layout:rk([Qx("instruction"),aS("base"),cS("seed"),aS("programId")])},TransferWithSeed:{index:11,layout:rk([Qx("instruction"),OS("lamports"),cS("seed"),aS("programId")])},UpgradeNonceAccount:{index:12,layout:rk([Qx("instruction")])}});class RS{constructor(){}static createAccount(e){const t=AS(BS.Create,{lamports:e.lamports,space:e.space,programId:Z_(e.programId.toBuffer())});return new xS({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,r;if("basePubkey"in e){t=AS(BS.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=AS(BS.Transfer,{lamports:BigInt(e.lamports)}),r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new xS({keys:r,programId:this.programId,data:t})}static assign(e){let t,r;if("basePubkey"in e){t=AS(BS.AssignWithSeed,{base:Z_(e.basePubkey.toBuffer()),seed:e.seed,programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=AS(BS.Assign,{programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new xS({keys:r,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=AS(BS.CreateWithSeed,{base:Z_(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Z_(e.programId.toBuffer())});let r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||r.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new xS({keys:r,programId:this.programId,data:t})}static createNonceAccount(e){const t=new kS;"basePubkey"in e&&"seed"in e?t.add(RS.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:PS,programId:this.programId})):t.add(RS.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:PS,programId:this.programId}));const r={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(r)),t}static nonceInitialize(e){const t=AS(BS.InitializeNonceAccount,{authorized:Z_(e.authorizedPubkey.toBuffer())}),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:_S,isSigner:!1,isWritable:!1},{pubkey:SS,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new xS(r)}static nonceAdvance(e){const t=AS(BS.AdvanceNonceAccount),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:_S,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new xS(r)}static nonceWithdraw(e){const t=AS(BS.WithdrawNonceAccount,{lamports:e.lamports});return new xS({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:_S,isSigner:!1,isWritable:!1},{pubkey:SS,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=AS(BS.AuthorizeNonceAccount,{authorized:Z_(e.newAuthorizedPubkey.toBuffer())});return new xS({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,r;if("basePubkey"in e){t=AS(BS.AllocateWithSeed,{base:Z_(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=AS(BS.Allocate,{space:e.space}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new xS({keys:r,programId:this.programId,data:t})}}function jS(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var LS,DS;function US(){if(DS)return LS;DS=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};function r(n,i){var o,s,a,c,l,u,d;if(!0===n)return"true";if(!1===n)return"false";switch(typeof n){case"object":if(null===n)return null;if(n.toJSON&&"function"==typeof n.toJSON)return r(n.toJSON(),i);if("[object Array]"===(d=e.call(n))){for(a="[",s=n.length-1,o=0;o<s;o++)a+=r(n[o],!0)+",";return s>-1&&(a+=r(n[o],!0)),a+"]"}if("[object Object]"===d){for(s=(c=t(n).sort()).length,a="",o=0;o<s;)void 0!==(u=r(n[l=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),o++;return"{"+a+"}"}return JSON.stringify(n);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(n);default:return isFinite(n)?n:null}}return LS=function(e){var t=r(e,!1);if(void 0!==t)return""+t}}RS.programId=new tS("11111111111111111111111111111111"),new tS("BPFLoader2111111111111111111111111111111111");var FS=jS(US());function zS(e){let t=0;for(;e>1;)e/=2,t++;return t}class qS{constructor(e,t,r,n,i){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=r,this.firstNormalEpoch=n,this.firstNormalSlot=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const r=zS(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-zS(32)-1;return[r,e-(this.getSlotsInEpoch(r)-32)]}{const t=e-this.firstNormalSlot,r=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+r,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+zS(32)):this.slotsPerEpoch}}var $S=globalThis.fetch;class WS extends __{constructor(e,t,r){super(e=>{const r=function(e,t){return new x_(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in r?r.socket:r,r},e,t,r),this.underlyingSocket=void 0}call(...e){var t;const r=null==(t=this.underlyingSocket)?void 0:t.readyState;return 1===r?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+r+")"))}notify(...e){var t;const r=null==(t=this.underlyingSocket)?void 0:t.readyState;return 1===r?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+r+")"))}}class HS{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let r;try{r=e.layout.decode(t)}catch(yA){throw new Error("invalid instruction; "+yA)}if(r.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${r.typeIndex} != ${e.index}`);return r}(GS,e),r=e.length-56;hS(r>=0,"lookup table is invalid"),hS(r%32==0,"lookup table is invalid");const n=r/32,{addresses:i}=rk([nk(aS(),n,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new tS(t.authority[0]):void 0,addresses:i.map(e=>new tS(e))}}}const GS={index:1,layout:rk([Qx("typeIndex"),OS("deactivationSlot"),ek("lastExtendedSlot"),Jx("lastExtendedStartIndex"),Jx(),nk(aS(),Yx(Jx(),-1),"authority")])},VS=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const KS=Uk(Ak(tS),Bk(),e=>new tS(e)),ZS=Rk([Bk(),Nk("base64")]),YS=Uk(Ak(N),ZS,e=>N.from(e[0],"base64"));function JS(e){let t,r;if("string"==typeof e)t=e;else if(e){const{commitment:n,...i}=e;t=n,r=i}return{commitment:t,config:r}}function XS(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function QS(e){return Lk([jk({jsonrpc:Nk("2.0"),id:Bk(),result:e}),jk({jsonrpc:Nk("2.0"),id:Bk(),error:jk({code:Dk(),message:Bk(),data:Tk(Ck("any",()=>!0))})})])}const eC=QS(Dk());function tC(e){return Uk(QS(e),eC,t=>"error"in t?t:{...t,result:kk(t.result,e)})}function rC(e){return tC(jk({context:jk({slot:Pk()}),value:e}))}function nC(e){return jk({context:jk({slot:Pk()}),value:e})}function iC(e,t){return 0===e?new vS({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new tS(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Pw.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new yS(t)}const oC=jk({foundation:Pk(),foundationTerm:Pk(),initial:Pk(),taper:Pk(),terminal:Pk()}),sC=tC(Ik(Mk(jk({epoch:Pk(),effectiveSlot:Pk(),amount:Pk(),postBalance:Pk(),commission:Tk(Mk(Pk()))})))),aC=Ik(jk({slot:Pk(),prioritizationFee:Pk()})),cC=jk({total:Pk(),validator:Pk(),foundation:Pk(),epoch:Pk()}),lC=jk({epoch:Pk(),slotIndex:Pk(),slotsInEpoch:Pk(),absoluteSlot:Pk(),blockHeight:Tk(Pk()),transactionCount:Tk(Pk())}),uC=jk({slotsPerEpoch:Pk(),leaderScheduleSlotOffset:Pk(),warmup:Ek(),firstNormalEpoch:Pk(),firstNormalSlot:Pk()}),dC=Ok(Bk(),Ik(Pk())),hC=Mk(Lk([jk({}),Bk()])),pC=jk({err:hC}),fC=Nk("receivedSignature"),mC=jk({"solana-core":Bk(),"feature-set":Tk(Pk())}),gC=jk({program:Bk(),programId:KS,parsed:Dk()}),yC=jk({programId:KS,accounts:Ik(KS),data:Bk()}),vC=rC(jk({err:Mk(Lk([jk({}),Bk()])),logs:Mk(Ik(Bk())),accounts:Tk(Mk(Ik(Mk(jk({executable:Ek(),owner:Bk(),lamports:Pk(),data:Ik(Bk()),rentEpoch:Tk(Pk())}))))),unitsConsumed:Tk(Pk()),returnData:Tk(Mk(jk({programId:Bk(),data:Rk([Bk(),Nk("base64")])}))),innerInstructions:Tk(Mk(Ik(jk({index:Pk(),instructions:Ik(Lk([gC,yC]))}))))})),bC=rC(jk({byIdentity:Ok(Bk(),Ik(Pk())),range:jk({firstSlot:Pk(),lastSlot:Pk()})}));const wC=tC(oC),xC=tC(cC),kC=tC(aC),_C=tC(lC),SC=tC(uC),CC=tC(dC),IC=tC(Pk()),EC=rC(jk({total:Pk(),circulating:Pk(),nonCirculating:Pk(),nonCirculatingAccounts:Ik(KS)})),AC=jk({amount:Bk(),uiAmount:Mk(Pk()),decimals:Pk(),uiAmountString:Tk(Bk())}),NC=rC(Ik(jk({address:KS,amount:Bk(),uiAmount:Mk(Pk()),decimals:Pk(),uiAmountString:Tk(Bk())}))),MC=rC(Ik(jk({pubkey:KS,account:jk({executable:Ek(),owner:KS,lamports:Pk(),data:YS,rentEpoch:Pk()})}))),PC=jk({program:Bk(),parsed:Dk(),space:Pk()}),TC=rC(Ik(jk({pubkey:KS,account:jk({executable:Ek(),owner:KS,lamports:Pk(),data:PC,rentEpoch:Pk()})}))),OC=rC(Ik(jk({lamports:Pk(),address:KS}))),BC=jk({executable:Ek(),owner:KS,lamports:Pk(),data:YS,rentEpoch:Pk()}),RC=jk({pubkey:KS,account:BC}),jC=Uk(Lk([Ak(N),PC]),Lk([ZS,PC]),e=>Array.isArray(e)?kk(e,YS):e),LC=jk({executable:Ek(),owner:KS,lamports:Pk(),data:jC,rentEpoch:Pk()}),DC=jk({pubkey:KS,account:LC}),UC=jk({state:Lk([Nk("active"),Nk("inactive"),Nk("activating"),Nk("deactivating")]),active:Pk(),inactive:Pk()}),FC=tC(Ik(jk({signature:Bk(),slot:Pk(),err:hC,memo:Mk(Bk()),blockTime:Tk(Mk(Pk()))}))),zC=tC(Ik(jk({signature:Bk(),slot:Pk(),err:hC,memo:Mk(Bk()),blockTime:Tk(Mk(Pk()))}))),qC=jk({subscription:Pk(),result:nC(BC)}),$C=jk({pubkey:KS,account:BC}),WC=jk({subscription:Pk(),result:nC($C)}),HC=jk({parent:Pk(),slot:Pk(),root:Pk()}),GC=jk({subscription:Pk(),result:HC}),VC=Lk([jk({type:Lk([Nk("firstShredReceived"),Nk("completed"),Nk("optimisticConfirmation"),Nk("root")]),slot:Pk(),timestamp:Pk()}),jk({type:Nk("createdBank"),parent:Pk(),slot:Pk(),timestamp:Pk()}),jk({type:Nk("frozen"),slot:Pk(),timestamp:Pk(),stats:jk({numTransactionEntries:Pk(),numSuccessfulTransactions:Pk(),numFailedTransactions:Pk(),maxTransactionsPerEntry:Pk()})}),jk({type:Nk("dead"),slot:Pk(),timestamp:Pk(),err:Bk()})]),KC=jk({subscription:Pk(),result:VC}),ZC=jk({subscription:Pk(),result:nC(Lk([pC,fC]))}),YC=jk({subscription:Pk(),result:Pk()}),JC=jk({pubkey:Bk(),gossip:Mk(Bk()),tpu:Mk(Bk()),rpc:Mk(Bk()),version:Mk(Bk())}),XC=jk({votePubkey:Bk(),nodePubkey:Bk(),activatedStake:Pk(),epochVoteAccount:Ek(),epochCredits:Ik(Rk([Pk(),Pk(),Pk()])),commission:Pk(),lastVote:Pk(),rootSlot:Mk(Pk())}),QC=tC(jk({current:Ik(XC),delinquent:Ik(XC)})),eI=Lk([Nk("processed"),Nk("confirmed"),Nk("finalized")]),tI=jk({slot:Pk(),confirmations:Mk(Pk()),err:hC,confirmationStatus:Tk(eI)}),rI=rC(Ik(Mk(tI))),nI=tC(Pk()),iI=jk({accountKey:KS,writableIndexes:Ik(Pk()),readonlyIndexes:Ik(Pk())}),oI=jk({signatures:Ik(Bk()),message:jk({accountKeys:Ik(Bk()),header:jk({numRequiredSignatures:Pk(),numReadonlySignedAccounts:Pk(),numReadonlyUnsignedAccounts:Pk()}),instructions:Ik(jk({accounts:Ik(Pk()),data:Bk(),programIdIndex:Pk()})),recentBlockhash:Bk(),addressTableLookups:Tk(Ik(iI))})}),sI=jk({pubkey:KS,signer:Ek(),writable:Ek(),source:Tk(Lk([Nk("transaction"),Nk("lookupTable")]))}),aI=jk({accountKeys:Ik(sI),signatures:Ik(Bk())}),cI=jk({parsed:Dk(),program:Bk(),programId:KS}),lI=jk({accounts:Ik(KS),data:Bk(),programId:KS}),uI=Uk(Lk([lI,cI]),Lk([jk({parsed:Dk(),program:Bk(),programId:Bk()}),jk({accounts:Ik(Bk()),data:Bk(),programId:Bk()})]),e=>kk(e,"accounts"in e?lI:cI)),dI=jk({signatures:Ik(Bk()),message:jk({accountKeys:Ik(sI),instructions:Ik(uI),recentBlockhash:Bk(),addressTableLookups:Tk(Mk(Ik(iI)))})}),hI=jk({accountIndex:Pk(),mint:Bk(),owner:Tk(Bk()),programId:Tk(Bk()),uiTokenAmount:AC}),pI=jk({writable:Ik(KS),readonly:Ik(KS)}),fI=jk({err:hC,fee:Pk(),innerInstructions:Tk(Mk(Ik(jk({index:Pk(),instructions:Ik(jk({accounts:Ik(Pk()),data:Bk(),programIdIndex:Pk()}))})))),preBalances:Ik(Pk()),postBalances:Ik(Pk()),logMessages:Tk(Mk(Ik(Bk()))),preTokenBalances:Tk(Mk(Ik(hI))),postTokenBalances:Tk(Mk(Ik(hI))),loadedAddresses:Tk(pI),computeUnitsConsumed:Tk(Pk()),costUnits:Tk(Pk())}),mI=jk({err:hC,fee:Pk(),innerInstructions:Tk(Mk(Ik(jk({index:Pk(),instructions:Ik(uI)})))),preBalances:Ik(Pk()),postBalances:Ik(Pk()),logMessages:Tk(Mk(Ik(Bk()))),preTokenBalances:Tk(Mk(Ik(hI))),postTokenBalances:Tk(Mk(Ik(hI))),loadedAddresses:Tk(pI),computeUnitsConsumed:Tk(Pk()),costUnits:Tk(Pk())}),gI=Lk([Nk(0),Nk("legacy")]),yI=jk({pubkey:Bk(),lamports:Pk(),postBalance:Mk(Pk()),rewardType:Mk(Bk()),commission:Tk(Mk(Pk()))}),vI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:oI,meta:Mk(fI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),bI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),wI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:aI,meta:Mk(fI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),xI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:dI,meta:Mk(mI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),kI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:aI,meta:Mk(mI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),_I=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),SI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:oI,meta:Mk(fI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk())}))),CI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),signatures:Ik(Bk()),blockTime:Mk(Pk())}))),II=tC(Mk(jk({slot:Pk(),meta:Mk(fI),blockTime:Tk(Mk(Pk())),transaction:oI,version:Tk(gI)}))),EI=tC(Mk(jk({slot:Pk(),transaction:dI,meta:Mk(mI),blockTime:Tk(Mk(Pk())),version:Tk(gI)}))),AI=rC(jk({blockhash:Bk(),lastValidBlockHeight:Pk()})),NI=rC(Ek()),MI=tC(Ik(jk({slot:Pk(),numTransactions:Pk(),numSlots:Pk(),samplePeriodSecs:Pk()}))),PI=rC(Mk(jk({feeCalculator:jk({lamportsPerSignature:Pk()})}))),TI=tC(Bk()),OI=tC(Bk()),BI=jk({err:hC,logs:Ik(Bk()),signature:Bk()}),RI=jk({result:nC(BI),subscription:Pk()}),jI={"solana-client":"js/1.0.0-maintenance"};class LI{constructor(e,t){let r,n,i,o,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:r,config:n}=JS(t),i=this._buildArgs([],r,void 0,n),o=FS(i);return e[o]=e[o]??(async()=>{try{const e=kk(await this._rpcRequest("getBlockHeight",i),tC(Pk()));if("error"in e)throw new IS(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,r=t.wsEndpoint,n=t.httpHeaders,i=t.fetch,o=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=r||function(e){const t=e.match(VS);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[r,n,i,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${s}//${n}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,r,n,i,o){const s=r||$S;let a;null!=o&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments."),n&&(a=async(e,t)=>{const r=await new Promise((r,i)=>{try{n(e,t,(e,t)=>r([e,t]))}catch(ud){i(ud)}});return await s(...r)});const c=new v_(async(r,n)=>{const o={method:"POST",body:r,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},jI)};try{let t,r=5,c=500;for(;t=a?await a(e,o):await s(e,o),429===t.status&&!0!==i&&(r-=1,0!==r);)console.error(`Server responded with ${t.status} ${t.statusText}. Retrying after ${c}ms delay...`),await ES(c),c*=2;const l=await t.text();t.ok?n(null,l):n(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(yA){yA instanceof Error&&n(yA)}},{});return c}(e,n,i,o,s,a),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((r,n)=>{c.request(e,t,(e,t)=>{e?n(e):r(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((r,n)=>{0===t.length&&r([]);const i=t.map(t=>e.request(t.methodName,t.args));e.request(i,(e,t)=>{e?n(e):r(t)})})}(this._rpcClient),this._rpcWebSocket=new WS(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,void 0,n),o=kk(await this._rpcRequest("getBalance",i),rC(Pk()));if("error"in o)throw new IS(o.error,`failed to get balance for ${e.toBase58()}`);return o.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=kk(await this._rpcRequest("getBlockTime",[e]),tC(Mk(Pk())));if("error"in t)throw new IS(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=kk(await this._rpcRequest("minimumLedgerSlot",[]),tC(Pk()));if("error"in e)throw new IS(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=kk(await this._rpcRequest("getFirstAvailableBlock",[]),IC);if("error"in e)throw new IS(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const r=kk(await this._rpcRequest("getSupply",[t]),EC);if("error"in r)throw new IS(r.error,"failed to get supply");return r.result}async getTokenSupply(e,t){const r=this._buildArgs([e.toBase58()],t),n=kk(await this._rpcRequest("getTokenSupply",r),rC(AC));if("error"in n)throw new IS(n.error,"failed to get token supply");return n.result}async getTokenAccountBalance(e,t){const r=this._buildArgs([e.toBase58()],t),n=kk(await this._rpcRequest("getTokenAccountBalance",r),rC(AC));if("error"in n)throw new IS(n.error,"failed to get token account balance");return n.result}async getTokenAccountsByOwner(e,t,r){const{commitment:n,config:i}=JS(r);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,n,"base64",i),a=kk(await this._rpcRequest("getTokenAccountsByOwner",s),MC);if("error"in a)throw new IS(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,r){let n=[e.toBase58()];"mint"in t?n.push({mint:t.mint.toBase58()}):n.push({programId:t.programId.toBase58()});const i=this._buildArgs(n,r,"jsonParsed"),o=kk(await this._rpcRequest("getTokenAccountsByOwner",i),TC);if("error"in o)throw new IS(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},r=t.filter||t.commitment?[t]:[],n=kk(await this._rpcRequest("getLargestAccounts",r),OC);if("error"in n)throw new IS(n.error,"failed to get largest accounts");return n.result}async getTokenLargestAccounts(e,t){const r=this._buildArgs([e.toBase58()],t),n=kk(await this._rpcRequest("getTokenLargestAccounts",r),NC);if("error"in n)throw new IS(n.error,"failed to get token largest accounts");return n.result}async getAccountInfoAndContext(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,"base64",n),o=kk(await this._rpcRequest("getAccountInfo",i),rC(Mk(BC)));if("error"in o)throw new IS(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,"jsonParsed",n),o=kk(await this._rpcRequest("getAccountInfo",i),rC(Mk(LC)));if("error"in o)throw new IS(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(r){throw new Error("failed to get info about account "+e.toBase58()+": "+r)}}async getMultipleParsedAccounts(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],r,"jsonParsed",n),s=kk(await this._rpcRequest("getMultipleAccounts",o),rC(Ik(Mk(LC))));if("error"in s)throw new IS(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],r,"base64",n),s=kk(await this._rpcRequest("getMultipleAccounts",o),rC(Ik(Mk(BC))));if("error"in s)throw new IS(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,r){const{commitment:n,config:i}=JS(t),o=this._buildArgs([e.toBase58()],n,void 0,{...i,epoch:null!=r?r:null==i?void 0:i.epoch}),s=kk(await this._rpcRequest("getStakeActivation",o),tC(UC));if("error"in s)throw new IS(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:r,config:n}=JS(t),{encoding:i,...o}=n||{},s=this._buildArgs([e.toBase58()],r,i||"base64",{...o,...o.filters?{filters:XS(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Ik(RC),l=!0===o.withContext?kk(a,rC(c)):kk(a,tC(c));if("error"in l)throw new IS(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,"jsonParsed",n),o=kk(await this._rpcRequest("getProgramAccounts",i),tC(Ik(DC)));if("error"in o)throw new IS(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.result}async confirmTransaction(e,t){var r;let n,i;if("string"==typeof e)n=e;else{const t=e;if(null==(r=t.abortSignal)?void 0:r.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{i=Pw.decode(n)}catch(yA){throw new Error("signature must be base58 encoded: "+n)}return hS(64===i.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,r)=>{null!=e&&(e.aborted?r(e.reason):e.addEventListener("abort",()=>{r(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let r,n,i=!1;const o=new Promise((o,s)=>{try{r=this.onSignature(t,(e,t)=>{r=void 0;const n={context:t,value:e};o({__type:bS.PROCESSED,response:n})},e);const a=new Promise(e=>{null==r?e():n=this._onSubscriptionStateChange(r,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,i)return;const r=await this.getSignatureStatus(t);if(i)return;if(null==r)return;const{context:n,value:c}=r;if(null!=c)if(null==c?void 0:c.err)s(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}i=!0,o({__type:bS.PROCESSED,response:{context:n,value:c}})}})()}catch(yA){s(yA)}});return{abortConfirmation:()=>{n&&(n(),n=void 0),null!=r&&(this.removeSignatureListener(r),r=void 0)},confirmationPromise:o}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:r,signature:n}}){let i=!1;const o=new Promise(t=>{const n=async()=>{try{return await this.getBlockHeight(e)}catch(t){return-1}};(async()=>{let e=await n();if(!i){for(;e<=r;){if(await ES(1e3),i)return;if(e=await n(),i)return}t({__type:bS.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:n}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,o]);if(e.__type!==bS.PROCESSED)throw new nS(n);l=e.response}finally{i=!0,s()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:r,nonceAccountPubkey:n,nonceValue:i,signature:o}}){let s=!1;const a=new Promise(t=>{let o=i,a=null;const c=async()=>{try{const{context:t,value:i}=await this.getNonceAndContext(n,{commitment:e,minContextSlot:r});return a=t.slot,null==i?void 0:i.nonce}catch(t){return o}};(async()=>{if(o=await c(),!s)for(;;){if(i!==o)return void t({__type:bS.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await ES(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===bS.PROCESSED)d=t.response;else{let n;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??r))){n=e;break}await ES(400)}if(!(null==n?void 0:n.value))throw new oS(o);{const t=e||"finalized",{confirmationStatus:r}=n.value;switch(t){case"processed":case"recent":if("processed"!==r&&"confirmed"!==r&&"finalized"!==r)throw new oS(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==r&&"finalized"!==r)throw new oS(o);break;case"finalized":case"max":case"root":if("finalized"!==r)throw new oS(o)}d={context:n.context,value:{err:n.value.err}}}}}finally{s=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let r;const n=new Promise(t=>{let n=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":n=this._confirmTransactionInitialTimeout||3e4}r=setTimeout(()=>t({__type:bS.TIMED_OUT,timeoutMs:n}),n)}),{abortConfirmation:i,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,n]);if(e.__type!==bS.PROCESSED)throw new iS(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(r),i()}return s}async getClusterNodes(){const e=kk(await this._rpcRequest("getClusterNodes",[]),tC(Ik(JC)));if("error"in e)throw new IS(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),r=kk(await this._rpcRequest("getVoteAccounts",t),QC);if("error"in r)throw new IS(r.error,"failed to get vote accounts");return r.result}async getSlot(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getSlot",n),tC(Pk()));if("error"in i)throw new IS(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getSlotLeader",n),tC(Bk()));if("error"in i)throw new IS(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const r=[e,t],n=kk(await this._rpcRequest("getSlotLeaders",r),tC(Ik(KS)));if("error"in n)throw new IS(n.error,"failed to get slot leaders");return n.result}async getSignatureStatus(e,t){const{context:r,value:n}=await this.getSignatureStatuses([e],t);hS(1===n.length);return{context:r,value:n[0]}}async getSignatureStatuses(e,t){const r=[e];t&&r.push(t);const n=kk(await this._rpcRequest("getSignatureStatuses",r),rI);if("error"in n)throw new IS(n.error,"failed to get signature status");return n.result}async getTransactionCount(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getTransactionCount",n),tC(Pk()));if("error"in i)throw new IS(i.error,"failed to get transaction count");return i.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),r=kk(await this._rpcRequest("getInflationGovernor",t),wC);if("error"in r)throw new IS(r.error,"failed to get inflation");return r.result}async getInflationReward(e,t,r){const{commitment:n,config:i}=JS(r),o=this._buildArgs([e.map(e=>e.toBase58())],n,void 0,{...i,epoch:null!=t?t:null==i?void 0:i.epoch}),s=kk(await this._rpcRequest("getInflationReward",o),sC);if("error"in s)throw new IS(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=kk(await this._rpcRequest("getInflationRate",[]),xC);if("error"in e)throw new IS(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getEpochInfo",n),_C);if("error"in i)throw new IS(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=kk(await this._rpcRequest("getEpochSchedule",[]),SC);if("error"in e)throw new IS(e.error,"failed to get epoch schedule");const t=e.result;return new qS(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=kk(await this._rpcRequest("getLeaderSchedule",[]),CC);if("error"in e)throw new IS(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const r=this._buildArgs([e],t),n=kk(await this._rpcRequest("getMinimumBalanceForRentExemption",r),nI);return"error"in n?(console.warn("Unable to fetch minimum balance for rent exemption"),0):n.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:r}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:r,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=kk(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),MI);if("error"in t)throw new IS(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const r=this._buildArgs([e],t),n=kk(await this._rpcRequest("getFeeCalculatorForBlockhash",r),PI);if("error"in n)throw new IS(n.error,"failed to get fee calculator");const{context:i,value:o}=n.result;return{context:i,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const r=Z_(e.serialize()).toString("base64"),n=this._buildArgs([r],t),i=kk(await this._rpcRequest("getFeeForMessage",n),rC(Mk(Pk())));if("error"in i)throw new IS(i.error,"failed to get fee for message");if(null===i.result)throw new Error("invalid blockhash");return i.result}async getRecentPrioritizationFees(e){var t;const r=null==(t=null==e?void 0:e.lockedWritableAccounts)?void 0:t.map(e=>e.toBase58()),n=(null==r?void 0:r.length)?[r]:[],i=kk(await this._rpcRequest("getRecentPrioritizationFees",n),kC);if("error"in i)throw new IS(i.error,"failed to get recent prioritization fees");return i.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getLatestBlockhash",n),AI);if("error"in i)throw new IS(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e],r,void 0,n),o=kk(await this._rpcRequest("isBlockhashValid",i),NI);if("error"in o)throw new IS(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=kk(await this._rpcRequest("getVersion",[]),tC(mC));if("error"in e)throw new IS(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=kk(await this._rpcRequest("getGenesisHash",[]),tC(Bk()));if("error"in e)throw new IS(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,void 0,n),o=await this._rpcRequest("getBlock",i);try{switch(null==n?void 0:n.transactionDetails){case"accounts":{const e=kk(o,wI);if("error"in e)throw e.error;return e.result}case"none":{const e=kk(o,bI);if("error"in e)throw e.error;return e.result}default:{const e=kk(o,vI);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:r})=>({meta:t,transaction:{...e,message:iC(r,e.message)},version:r}))}:null}}}catch(s){throw new IS(s,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n),o=await this._rpcRequest("getBlock",i);try{switch(null==n?void 0:n.transactionDetails){case"accounts":{const e=kk(o,kI);if("error"in e)throw e.error;return e.result}case"none":{const e=kk(o,_I);if("error"in e)throw e.error;return e.result}default:{const e=kk(o,xI);if("error"in e)throw e.error;return e.result}}}catch(s){throw new IS(s,"failed to get block")}}async getBlockProduction(e){let t,r;if("string"==typeof e)r=e;else if(e){const{commitment:n,...i}=e;r=n,t=i}const n=this._buildArgs([],r,"base64",t),i=kk(await this._rpcRequest("getBlockProduction",n),bC);if("error"in i)throw new IS(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,void 0,n),o=kk(await this._rpcRequest("getTransaction",i),II);if("error"in o)throw new IS(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:iC(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n),o=kk(await this._rpcRequest("getTransaction",i),EI);if("error"in o)throw new IS(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=kk(e,EI);if("error"in t)throw new IS(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],r,void 0,n)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=kk(e,II);if("error"in t)throw new IS(t.error,"failed to get transactions");const r=t.result;return r?{...r,transaction:{...r.transaction,message:iC(r.version,r.transaction.message)}}:r})}async getConfirmedBlock(e,t){const r=this._buildArgsAtLeastConfirmed([e],t),n=kk(await this._rpcRequest("getBlock",r),SI);if("error"in n)throw new IS(n.error,"failed to get confirmed block");const i=n.result;if(!i)throw new Error("Confirmed block "+e+" not found");const o={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const r=new yS(e.message);return{meta:t,transaction:{...e,message:r}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:kS.populate(e.message,e.signatures)}))}}async getBlocks(e,t,r){const n=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],r),i=kk(await this._rpcRequest("getBlocks",n),tC(Ik(Pk())));if("error"in i)throw new IS(i.error,"failed to get blocks");return i.result}async getBlockSignatures(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),n=kk(await this._rpcRequest("getBlock",r),CI);if("error"in n)throw new IS(n.error,"failed to get block");const i=n.result;if(!i)throw new Error("Block "+e+" not found");return i}async getConfirmedBlockSignatures(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),n=kk(await this._rpcRequest("getBlock",r),CI);if("error"in n)throw new IS(n.error,"failed to get confirmed block");const i=n.result;if(!i)throw new Error("Confirmed block "+e+" not found");return i}async getConfirmedTransaction(e,t){const r=this._buildArgsAtLeastConfirmed([e],t),n=kk(await this._rpcRequest("getTransaction",r),II);if("error"in n)throw new IS(n.error,"failed to get transaction");const i=n.result;if(!i)return i;const o=new yS(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:kS.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),n=kk(await this._rpcRequest("getTransaction",r),EI);if("error"in n)throw new IS(n.error,"failed to get confirmed transaction");return n.result}async getParsedConfirmedTransactions(e,t){const r=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(r)).map(e=>{const t=kk(e,EI);if("error"in t)throw new IS(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,r){let n={},i=await this.getFirstAvailableBlock();for(;!("until"in n)&&!(--t<=0||t<i);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(n.until=e.signatures[e.signatures.length-1].toString())}catch(yA){if(yA instanceof Error&&yA.message.includes("skipped"))continue;throw yA}let o=await this.getSlot("finalized");for(;!("before"in n||++r>o);)try{const e=await this.getConfirmedBlockSignatures(r);e.signatures.length>0&&(n.before=e.signatures[e.signatures.length-1].toString())}catch(yA){if(yA instanceof Error&&yA.message.includes("skipped"))continue;throw yA}return(await this.getConfirmedSignaturesForAddress2(e,n)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,r){const n=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,t),i=kk(await this._rpcRequest("getConfirmedSignaturesForAddress2",n),FC);if("error"in i)throw new IS(i.error,"failed to get confirmed signatures for address");return i.result}async getSignaturesForAddress(e,t,r){const n=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,t),i=kk(await this._rpcRequest("getSignaturesForAddress",n),zC);if("error"in i)throw new IS(i.error,"failed to get signatures for address");return i.result}async getAddressLookupTable(e,t){const{context:r,value:n}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==n&&(i=new HS({key:e,state:HS.deserialize(n.data)})),{context:r,value:i}}async getNonceAndContext(e,t){const{context:r,value:n}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==n&&(i=TS.fromAccountData(n.data)),{context:r,value:i}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const r=kk(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),TI);if("error"in r)throw new IS(r.error,`airdrop to ${e.toBase58()} failed`);return r.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await ES(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,r=t?t.blockhash:null;for(let n=0;n<50;n++){const e=await this.getLatestBlockhash("finalized");if(r!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await ES(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,"base64",r),i=kk(await this._rpcRequest("getStakeMinimumDelegation",n),rC(Pk()));if("error"in i)throw new IS(i.error,"failed to get stake minimum delegation");return i.result}async simulateTransaction(e,t,r){if("message"in e){const n=e.serialize(),i=N.from(n).toString("base64");if(Array.isArray(t)||void 0!==r)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[i,o],a=kk(await this._rpcRequest("simulateTransaction",s),vC);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let n;if(e instanceof kS){let t=e;n=new kS,n.feePayer=t.feePayer,n.instructions=e.instructions,n.nonceInfo=t.nonceInfo,n.signatures=t.signatures}else n=kS.populate(e),n._message=n._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const i=t;if(n.nonceInfo&&i)n.sign(...i);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(n.lastValidBlockHeight=t.lastValidBlockHeight,n.recentBlockhash=t.blockhash,!i)break;if(n.sign(...i),!n.signature)throw new Error("!signature");const r=n.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(r)&&!this._blockhashInfo.transactionSignatures.includes(r)){this._blockhashInfo.simulatedSignatures.push(r);break}e=!0}}const o=n._compile(),s=o.serialize(),a=n._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(r){const e=(Array.isArray(r)?r:o.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}i&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=kk(await this._rpcRequest("simulateTransaction",l),vC);if("error"in u){let e;if("data"in u.error&&(e=u.error.data.logs,e&&Array.isArray(e))){const t="\n ",r=t+e.join(t);console.error(u.error.message,r)}throw new CS({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,r){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const r=e.serialize();return await this.sendRawTransaction(r,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const n=t;if(e.nonceInfo)e.sign(...n);else{let t=this._disableBlockhashCaching;for(;;){const r=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=r.lastValidBlockHeight,e.recentBlockhash=r.blockhash,e.sign(...n),!e.signature)throw new Error("!signature");const i=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(i)){this._blockhashInfo.transactionSignatures.push(i);break}t=!0}}const i=e.serialize();return await this.sendRawTransaction(i,r)}async sendRawTransaction(e,t){const r=Z_(e).toString("base64");return await this.sendEncodedTransaction(r,t)}async sendEncodedTransaction(e,t){const r={encoding:"base64"},n=t&&t.skipPreflight,i=!0===n?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(r.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(r.minContextSlot=t.minContextSlot),n&&(r.skipPreflight=n),i&&(r.preflightCommitment=i);const o=[e,r],s=kk(await this._rpcRequest("sendTransaction",o),OI);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new CS({action:n?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){var r;const n=null==(r=this._subscriptionsByHash[e])?void 0:r.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const r=this._subscriptionStateChangeCallbacksByHash[e];r&&r.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){var r;const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const i=(r=this._subscriptionStateChangeCallbacksByHash)[n]||(r[n]=new Set);return i.add(t),()=>{i.delete(t),0===i.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(yA){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const r=this._subscriptionsByHash[e];if(void 0!==r)switch(r.state){case"pending":case"unsubscribed":if(0===r.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===r.state&&delete this._subscriptionCallbacksByServerSubscriptionId[r.serverSubscriptionId],void(await this._updateSubscriptions());await(async()=>{const{args:n,method:i}=r;try{this._setSubscription(e,{...r,state:"subscribing"});const t=await this._rpcWebSocket.call(i,n);this._setSubscription(e,{...r,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=r.callbacks,await this._updateSubscriptions()}catch(o){if(console.error(`Received ${o instanceof Error?"":"JSON-RPC "}error calling \`${i}\``,{args:n,error:o}),!t())return;this._setSubscription(e,{...r,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===r.callbacks.size&&await(async()=>{const{serverSubscriptionId:n,unsubscribeMethod:i}=r;if(this._subscriptionsAutoDisposedByRpc.has(n))this._subscriptionsAutoDisposedByRpc.delete(n);else{this._setSubscription(e,{...r,state:"unsubscribing"}),this._setSubscription(e,{...r,state:"unsubscribing"});try{await this._rpcWebSocket.call(i,[n])}catch(o){if(o instanceof Error&&console.error(`${i} error:`,o.message),!t())return;return this._setSubscription(e,{...r,state:"subscribed"}),void(await this._updateSubscriptions())}}this._setSubscription(e,{...r,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const r=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==r&&r.forEach(e=>{try{e(...t)}catch(r){console.error(r)}})}_wsOnAccountNotification(e){const{result:t,subscription:r}=kk(e,qC);this._handleServerNotification(r,[t.value,t.context])}_makeSubscription(e,t){const r=this._nextClientSubscriptionId++,n=FS([e.method,t]),i=this._subscriptionsByHash[n];return void 0===i?this._subscriptionsByHash[n]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[r]=n,this._subscriptionDisposeFunctionsByClientSubscriptionId[r]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[r],delete this._subscriptionHashByClientSubscriptionId[r];const t=this._subscriptionsByHash[n];hS(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${r}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),r}onAccountChange(e,t,r){const{commitment:n,config:i}=JS(r),o=this._buildArgs([e.toBase58()],n||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:r}=kk(e,WC);this._handleServerNotification(r,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,r,n){const{commitment:i,config:o}=JS(r),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(n?{filters:XS(n)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,r){const n=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],r||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},n)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:r}=kk(e,RI);this._handleServerNotification(r,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:r}=kk(e,GC);this._handleServerNotification(r,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:r}=kk(e,KC);this._handleServerNotification(r,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const r=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];r?await r():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${t}' events could not be found.`)}_buildArgs(e,t,r,n){const i=t||this._commitment;if(i||r||n){let t={};r&&(t.encoding=r),i&&(t.commitment=i),n&&(t=Object.assign(t,n)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,r,n){const i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,r,n)}_wsOnSignatureNotification(e){const{result:t,subscription:r}=kk(e,ZC);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(r),this._handleServerNotification(r,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,r){const n=this._buildArgs([e],r||this._commitment||"finalized"),i=this._makeSubscription({callback:(e,r)=>{if("status"===e.type){t(e.result,r);try{this.removeSignatureListener(i)}catch(n){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},n);return i}onSignatureWithOptions(e,t,r){const{commitment:n,...i}={...r,commitment:r&&r.commitment||this._commitment||"finalized"},o=this._buildArgs([e],n,void 0,i),s=this._makeSubscription({callback:(e,r)=>{t(e,r);try{this.removeSignatureListener(s)}catch(n){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:r}=kk(e,YC);this._handleServerNotification(r,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}var DI;Object.freeze({CreateLookupTable:{index:0,layout:rk([Qx("instruction"),OS("recentSlot"),Jx("bumpSeed")])},FreezeLookupTable:{index:1,layout:rk([Qx("instruction")])},ExtendLookupTable:{index:2,layout:rk([Qx("instruction"),OS(),nk(aS(),Yx(Qx(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:rk([Qx("instruction")])},CloseLookupTable:{index:4,layout:rk([Qx("instruction")])}}),new tS("AddressLookupTab1e1111111111111111111111111"),Object.freeze({RequestUnits:{index:0,layout:rk([Jx("instruction"),Qx("units"),Qx("additionalFee")])},RequestHeapFrame:{index:1,layout:rk([Jx("instruction"),Qx("bytes")])},SetComputeUnitLimit:{index:2,layout:rk([Jx("instruction"),Qx("units")])},SetComputeUnitPrice:{index:3,layout:rk([Jx("instruction"),OS("microLamports")])}}),new tS("ComputeBudget111111111111111111111111111111"),rk([Jx("numSignatures"),Jx("padding"),Xx("signatureOffset"),Xx("signatureInstructionIndex"),Xx("publicKeyOffset"),Xx("publicKeyInstructionIndex"),Xx("messageDataOffset"),Xx("messageDataSize"),Xx("messageInstructionIndex")]),new tS("Ed25519SigVerify111111111111111111111111111"),G_.utils.isValidPrivateKey,rk([Jx("numSignatures"),Xx("signatureOffset"),Jx("signatureInstructionIndex"),Xx("ethAddressOffset"),Jx("ethAddressInstructionIndex"),Xx("messageDataOffset"),Xx("messageDataSize"),Jx("messageInstructionIndex"),ik(20,"ethAddress"),ik(64,"signature"),Jx("recoveryId")]),new tS("KeccakSecp256k11111111111111111111111111111"),new tS("StakeConfig11111111111111111111111111111111");class UI{constructor(e,t,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=r}}DI=UI,UI.default=new DI(0,0,tS.default),Object.freeze({Initialize:{index:0,layout:rk([Qx("instruction"),((e="authorized")=>rk([aS("staker"),aS("withdrawer")],e))(),((e="lockup")=>rk([tk("unixTimestamp"),tk("epoch"),aS("custodian")],e))()])},Authorize:{index:1,layout:rk([Qx("instruction"),aS("newAuthorized"),Qx("stakeAuthorizationType")])},Delegate:{index:2,layout:rk([Qx("instruction")])},Split:{index:3,layout:rk([Qx("instruction"),tk("lamports")])},Withdraw:{index:4,layout:rk([Qx("instruction"),tk("lamports")])},Deactivate:{index:5,layout:rk([Qx("instruction")])},Merge:{index:7,layout:rk([Qx("instruction")])},AuthorizeWithSeed:{index:8,layout:rk([Qx("instruction"),aS("newAuthorized"),Qx("stakeAuthorizationType"),cS("authoritySeed"),aS("authorityOwner")])}}),new tS("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:rk([Qx("instruction"),((e="voteInit")=>rk([aS("nodePubkey"),aS("authorizedVoter"),aS("authorizedWithdrawer"),Jx("commission")],e))()])},Authorize:{index:1,layout:rk([Qx("instruction"),aS("newAuthorized"),Qx("voteAuthorizationType")])},Withdraw:{index:3,layout:rk([Qx("instruction"),tk("lamports")])},UpdateValidatorIdentity:{index:4,layout:rk([Qx("instruction")])},AuthorizeWithSeed:{index:10,layout:rk([Qx("instruction"),((e="voteAuthorizeWithSeedArgs")=>rk([Qx("voteAuthorizationType"),aS("currentAuthorityDerivedKeyOwnerPubkey"),cS("currentAuthorityDerivedKeySeed"),aS("newAuthorized")],e))()])}}),new tS("Vote111111111111111111111111111111111111111"),new tS("Va1idator1nfo111111111111111111111111111111"),jk({name:Bk(),website:Tk(Bk()),details:Tk(Bk()),iconUrl:Tk(Bk()),keybaseUsername:Tk(Bk())}),new tS("Vote111111111111111111111111111111111111111"),rk([aS("nodePubkey"),aS("authorizedWithdrawer"),Jx("commission"),ek(),nk(rk([ek("slot"),Qx("confirmationCount")]),Yx(Qx(),-8),"votes"),Jx("rootSlotValid"),ek("rootSlot"),ek(),nk(rk([ek("epoch"),aS("authorizedVoter")]),Yx(Qx(),-8),"authorizedVoters"),rk([nk(rk([aS("authorizedPubkey"),ek("epochOfLastAuthorizedSwitch"),ek("targetEpoch")]),32,"buf"),ek("idx"),Jx("isEmpty")],"priorVoters"),ek(),nk(rk([ek("epoch"),ek("credits"),ek("prevCredits")]),Yx(Qx(),-8),"epochCredits"),rk([ek("slot"),ek("timestamp")],"lastTimestamp")]);const FI=1e9,zI=Object.freeze(Object.defineProperty({__proto__:null,AddressLookupTableAccount:HS,BLOCKHASH_CACHE_TIMEOUT_MS:3e4,Connection:LI,EpochSchedule:qS,FeeCalculatorLayout:NS,LAMPORTS_PER_SOL:FI,Lockup:UI,MAX_SEED_LENGTH:32,Message:yS,MessageAccountKeys:sS,MessageV0:vS,NONCE_ACCOUNT_LENGTH:PS,NonceAccount:TS,PACKET_DATA_SIZE:rS,PUBLIC_KEY_LENGTH:Q_,PublicKey:tS,SIGNATURE_LENGTH_IN_BYTES:64,SOLANA_SCHEMA:J_,SYSTEM_INSTRUCTION_LAYOUTS:BS,SYSVAR_RECENT_BLOCKHASHES_PUBKEY:_S,SYSVAR_RENT_PUBKEY:SS,SendTransactionError:CS,SolanaJSONRPCError:IS,Struct:Y_,SystemProgram:RS,Transaction:kS,TransactionExpiredBlockheightExceededError:nS,TransactionExpiredNonceInvalidError:oS,TransactionExpiredTimeoutError:iS,TransactionInstruction:xS,TransactionStatus:bS,VERSION_PREFIX_MASK:127},Symbol.toStringTag,{value:"Module"})),qI=new tS("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new tS("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const $I=new tS("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new tS("So11111111111111111111111111111111111111112"),new tS("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const WI=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var HI={};Object.defineProperty(HI,"__esModule",{value:!0});var GI=HI.toBigIntLE=function(e){{const t=I.from(e);t.reverse();const r=t.toString("hex");return 0===r.length?BigInt(0):BigInt(`0x${r}`)}};HI.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}};var VI=HI.toBufferLE=function(e,t){{const r=e.toString(16),n=I.from(r.padStart(2*t,"0").slice(0,2*t),"hex");return n.reverse(),n}};HI.toBufferBE=function(e,t){{const r=e.toString(16);return I.from(r.padStart(2*t,"0").slice(0,2*t),"hex")}};const KI=(ZI=8,e=>{const t=ik(ZI,e),{encode:r,decode:n}=WI(t),i=t;return i.decode=(e,t)=>{const r=n(e,t);return GI(I.from(r))},i.encode=(e,t,n)=>{const i=VI(e,ZI);return r(i,t,n)},i});var ZI;const YI=e=>{const t=Jx(e),{encode:r,decode:n}=WI(t),i=t;return i.decode=(e,t)=>!!n(e,t),i.encode=(e,t,n)=>{const i=Number(e);return r(i,t,n)},i},JI=e=>{const t=ik(32,e),{encode:r,decode:n}=WI(t),i=t;return i.decode=(e,t)=>{const r=n(e,t);return new tS(r)},i.encode=(e,t,n)=>{const i=e.toBuffer();return r(i,t,n)},i};class XI extends Error{constructor(e){super(e)}}class QI extends XI{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class eE extends XI{constructor(){super(...arguments),this.name="TokenInvalidAccountError"}}class tE extends XI{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class rE extends XI{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class nE extends XI{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var iE,oE,sE,aE;(oE=iE||(iE={}))[oE.InitializeMint=0]="InitializeMint",oE[oE.InitializeAccount=1]="InitializeAccount",oE[oE.InitializeMultisig=2]="InitializeMultisig",oE[oE.Transfer=3]="Transfer",oE[oE.Approve=4]="Approve",oE[oE.Revoke=5]="Revoke",oE[oE.SetAuthority=6]="SetAuthority",oE[oE.MintTo=7]="MintTo",oE[oE.Burn=8]="Burn",oE[oE.CloseAccount=9]="CloseAccount",oE[oE.FreezeAccount=10]="FreezeAccount",oE[oE.ThawAccount=11]="ThawAccount",oE[oE.TransferChecked=12]="TransferChecked",oE[oE.ApproveChecked=13]="ApproveChecked",oE[oE.MintToChecked=14]="MintToChecked",oE[oE.BurnChecked=15]="BurnChecked",oE[oE.InitializeAccount2=16]="InitializeAccount2",oE[oE.SyncNative=17]="SyncNative",oE[oE.InitializeAccount3=18]="InitializeAccount3",oE[oE.InitializeMultisig2=19]="InitializeMultisig2",oE[oE.InitializeMint2=20]="InitializeMint2",oE[oE.GetAccountDataSize=21]="GetAccountDataSize",oE[oE.InitializeImmutableOwner=22]="InitializeImmutableOwner",oE[oE.AmountToUiAmount=23]="AmountToUiAmount",oE[oE.UiAmountToAmount=24]="UiAmountToAmount",oE[oE.InitializeMintCloseAuthority=25]="InitializeMintCloseAuthority",oE[oE.TransferFeeExtension=26]="TransferFeeExtension",oE[oE.ConfidentialTransferExtension=27]="ConfidentialTransferExtension",oE[oE.DefaultAccountStateExtension=28]="DefaultAccountStateExtension",oE[oE.Reallocate=29]="Reallocate",oE[oE.MemoTransferExtension=30]="MemoTransferExtension",oE[oE.CreateNativeMint=31]="CreateNativeMint",oE[oE.InitializeNonTransferableMint=32]="InitializeNonTransferableMint",oE[oE.InterestBearingMintExtension=33]="InterestBearingMintExtension",oE[oE.CpiGuardExtension=34]="CpiGuardExtension",oE[oE.InitializePermanentDelegate=35]="InitializePermanentDelegate",oE[oE.TransferHookExtension=36]="TransferHookExtension",oE[oE.MetadataPointerExtension=39]="MetadataPointerExtension",oE[oE.GroupPointerExtension=40]="GroupPointerExtension",oE[oE.GroupMemberPointerExtension=41]="GroupMemberPointerExtension",oE[oE.ScaledUiAmountExtension=43]="ScaledUiAmountExtension",oE[oE.PausableExtension=44]="PausableExtension",(aE=sE||(sE={}))[aE.Uninitialized=0]="Uninitialized",aE[aE.Mint=1]="Mint",aE[aE.Account=2]="Account";const cE=rk([Jx("m"),Jx("n"),YI("isInitialized"),JI("signer1"),JI("signer2"),JI("signer3"),JI("signer4"),JI("signer5"),JI("signer6"),JI("signer7"),JI("signer8"),JI("signer9"),JI("signer10"),JI("signer11")]).span;var lE,uE;(uE=lE||(lE={}))[uE.Uninitialized=0]="Uninitialized",uE[uE.Initialized=1]="Initialized",uE[uE.Frozen=2]="Frozen";const dE=rk([JI("mint"),JI("owner"),KI("amount"),Qx("delegateOption"),JI("delegate"),Jx("state"),Qx("isNativeOption"),KI("isNative"),KI("delegatedAmount"),Qx("closeAuthorityOption"),JI("closeAuthority")]),hE=dE.span;async function pE(e,t,r,n=qI){return function(e,t,r=qI){if(!t)throw new QI;if(!t.owner.equals(r))throw new tE;if(t.data.length<hE)throw new rE;const n=dE.decode(t.data.slice(0,hE));let i=I.alloc(0);if(t.data.length>hE){if(t.data.length===cE)throw new rE;if(t.data[hE]!=sE.Account)throw new eE;i=t.data.slice(hE+1)}return{address:e,mint:n.mint,owner:n.owner,amount:n.amount,delegate:n.delegateOption?n.delegate:null,delegatedAmount:n.delegatedAmount,isInitialized:n.state!==lE.Uninitialized,isFrozen:n.state===lE.Frozen,isNative:!!n.isNativeOption,rentExemptReserve:n.isNativeOption?n.isNative:null,closeAuthority:n.closeAuthorityOption?n.closeAuthority:null,tlvData:i}}(t,await e.getAccountInfo(t,r),n)}async function fE(e,t,r=!1,n=qI,i=$I){if(!r&&!tS.isOnCurve(t.toBuffer()))throw new nE;const[o]=await tS.findProgramAddress([t.toBuffer(),n.toBuffer(),e.toBuffer()],i);return o}function mE(e,t,r,n,i=qI,o=$I){return function(e,t,r,n,i,o=qI,s=$I){const a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:RS.programId,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1}];return new xS({keys:a,programId:s,data:i})}(e,t,r,n,I.alloc(0),i,o)}rk([Qx("mintAuthorityOption"),JI("mintAuthority"),KI("supply"),Jx("decimals"),YI("isInitialized"),Qx("freezeAuthorityOption"),JI("freezeAuthority")]).span;const gE=rk([Jx("instruction"),KI("amount")]);function yE(e,t,r,n,i=[],o=qI){const s=function(e,t,r){if(r.length){e.push({pubkey:t,isSigner:!1,isWritable:!1});for(const t of r)e.push({pubkey:t instanceof tS?t:t.publicKey,isSigner:!0,isWritable:!1})}else e.push({pubkey:t,isSigner:!0,isWritable:!1});return e}([{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0}],r,i),a=I.alloc(gE.span);return gE.encode({instruction:iE.Transfer,amount:BigInt(n)},a),new xS({keys:s,programId:o,data:a})}const vE=(e,t)=>{const[n,i]=r.useState(!1),[o,s]=r.useState(null),[a,c]=r.useState(null),l=r.useRef(0),u=r.useCallback(()=>{const t=Array.isArray(e)?e:[e];if(!t||0===t.length||!t[0])return null;const r=t[l.current%t.length];return new LI(r,"confirmed")},[e]);r.useCallback(()=>{const t=Array.isArray(e)?e:[e];l.current=(l.current+1)%t.length},[e]);const d=r.useCallback(async(e,r)=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const n=u();if(!n)throw new Error("Solana RPC connection not available. Please select a Solana network.");const o=t.adapter,a=Math.floor(r*FI),c=5e-6,l=r+c,d=new tS(t.publicKey),h=await n.getBalance(d)/FI;if(h<l){const e=(l-h).toFixed(6);throw new Error(`Insufficient SOL balance. You have ${h.toFixed(6)} SOL but need ${l.toFixed(6)} SOL (${r} + ~${c} fee). Please add at least ${e} SOL to your wallet.`)}const p=new tS(e),f=(new kS).add(RS.transfer({fromPubkey:d,toPubkey:p,lamports:a})),{blockhash:m,lastValidBlockHeight:g}=await n.getLatestBlockhash();f.recentBlockhash=m,f.feePayer=d;const y=await o.signTransaction(f),v=await n.sendRawTransaction(y.serialize());return s(v),i(!1),{signature:v,success:!0}}catch(yA){throw console.error("❌ SOL transaction failed:",yA),c(yA.message||"Transaction failed"),i(!1),yA}},[t,u]),h=r.useCallback(async(e,r,n,o)=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const c=u();if(!c)throw new Error("Solana RPC connection not available. Please select a Solana network.");const l=t.adapter,d=Math.floor(n*Math.pow(10,o)),h=new tS(t.publicKey),p=new tS(r),f=new tS(e),m=1e-5,g=await c.getBalance(h)/FI;if(g<m)throw new Error(`Insufficient SOL for transaction fee. You have ${g.toFixed(6)} SOL but need at least ${m} SOL for the network fee. Please add SOL to your wallet.`);try{const e=await fE(f,h,!1,qI,$I),t=await c.getTokenAccountBalance(e),r=parseFloat(t.value.uiAmount||0);if(r<n){const e=(n-r).toFixed(o);throw new Error(`Insufficient token balance. You have ${r.toFixed(o)} but need ${n.toFixed(o)}. Please add at least ${e} more tokens to your wallet.`)}}catch(a){if(a.message.includes("Insufficient"))throw a;throw new Error(`You don't have any of this token in your wallet. Please add ${n} tokens to continue.`)}const y=await fE(f,h,!1,qI,$I),v=await fE(f,p,!1,qI,$I),b=(new kS).add(yE(y,v,h,d,[],qI)),{blockhash:w,lastValidBlockHeight:x}=await c.getLatestBlockhash();b.recentBlockhash=w,b.feePayer=h;const k=await l.signTransaction(b),_=await c.sendRawTransaction(k.serialize());return s(_),i(!1),{signature:_,success:!0}}catch(yA){console.error("❌ SPL Token transaction failed:",yA);let t=yA.message||"Transaction failed";throw t.includes("Account not found")?t="Recipient token account not found. They need to have received this token before.":t.includes("insufficient")?t="Insufficient balance":t.includes("User rejected")&&(t="Transaction was rejected"),c(t),i(!1),new Error(t)}},[t,u]),p=r.useCallback(async e=>{try{const r=u();if(!r)return console.warn("⚠️ Cannot fetch SOL balance: RPC connection not available"),0;const n=new tS(e||t.publicKey);return await r.getBalance(n)/FI}catch(yA){return console.error("Error getting SOL balance:",yA),0}},[t,u]),f=r.useCallback(async(e,r)=>{try{const n=u();if(!n)return console.warn("⚠️ Cannot fetch SPL token balance: RPC connection not available"),0;const i=new tS(r||t.publicKey),o=new tS(e),s=await fE(o,i,!1,qI,$I),a=await n.getTokenAccountBalance(s);return parseFloat(a.value.uiAmount||0)}catch(yA){return console.error("Error getting SPL token balance:",yA),0}},[t,u]),m=r.useCallback(async()=>{try{const e=u();if(!e)return 5e-6;await e.getRecentBlockhash();return 5e-6}catch(yA){return console.error("Error estimating fee:",yA),5e-6}},[u]);return{isProcessing:n,txSignature:o,error:a,sendSOL:d,sendSPLToken:h,sendSplitPayment:r.useCallback(async({tokenMintAddress:e,merchantAddress:r,coinleyAddress:n,merchantAmount:o,coinleyAmount:a,decimals:l=6})=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const c=u();if(!c)throw new Error("Solana RPC connection not available. Please select a Solana network.");const p=t.adapter,f=Math.floor(o*Math.pow(10,l)),m=Math.floor(a*Math.pow(10,l)),g=o+a,y=new tS(t.publicKey),v=new tS(r),b=new tS(n),w=new tS(e),x=.01,k=await c.getBalance(y)/FI;if(k<x)throw new Error(`Insufficient SOL for transaction fee. You have ${k.toFixed(6)} SOL but need at least ${x} SOL for the network fee. Please add SOL to your wallet.`);try{const e=await fE(w,y,!1,qI,$I),t=await c.getTokenAccountBalance(e),r=parseFloat(t.value.uiAmount||0);if(r<g){const e=(g-r).toFixed(l);throw new Error(`Insufficient token balance. You have ${r.toFixed(l)} but need ${g.toFixed(l)} for this payment. Please add at least ${e} more tokens to your wallet.`)}}catch(d){if(d.message.includes("Insufficient"))throw d;throw new Error(`You don't have any of this token in your wallet. Please add ${g.toFixed(l)} tokens to continue.`)}const _=await fE(w,y,!1,qI,$I),S=await fE(w,v,!1,qI,$I),C=await fE(w,b,!1,qI,$I),I=new kS;try{await pE(c,S)}catch(h){I.add(mE(y,S,v,w,qI,$I))}try{await pE(c,C)}catch(h){I.add(mE(y,C,b,w,qI,$I))}I.add(yE(_,S,y,f,[],qI)),I.add(yE(_,C,y,m,[],qI));const{blockhash:E,lastValidBlockHeight:A}=await c.getLatestBlockhash();I.recentBlockhash=E,I.feePayer=y;const N=await p.signTransaction(I),M=await c.sendRawTransaction(N.serialize());return s(M),i(!1),{signature:M,success:!0,merchantAmount:o,coinleyAmount:a,totalAmount:g}}catch(yA){console.error("❌ Split payment failed:",yA);let t=yA.message||"Transaction failed";throw t.includes("insufficient")||t.includes("0x1")?t="Insufficient token balance":t.includes("User rejected")&&(t="Transaction was rejected"),c(t),i(!1),new Error(t)}},[t,u]),getSOLBalance:p,getSPLTokenBalance:f,estimateFee:m,resetTransaction:r.useCallback(()=>{i(!1),s(null),c(null)},[]),connection:u()}},bE=({options:e=[],value:n,onChange:i,placeholder:o,renderOption:s,getOptionKey:a,getOptionValue:c,getSearchableText:u,disabled:d=!1})=>{const[h,p]=r.useState(!1),[f,m]=r.useState(""),[g,y]=r.useState({top:0,left:0,width:400,maxHeight:450}),v=r.useRef(null),b=r.useRef(null),w=e.filter(e=>(u?u(e):"").toLowerCase().includes(f.toLowerCase())),x=e.find(e=>c(e)===n),k=()=>{if(b.current){const e=window.innerWidth,t=window.innerHeight,r=Math.min(400,e-40),n=Math.min(450,t-100);y({top:t/2-n/2,left:e/2-r/2,width:r,maxHeight:n})}};r.useEffect(()=>{const e=e=>{v.current&&!v.current.contains(e.target)&&b.current&&!b.current.contains(e.target)&&(p(!1),m(""))},t=()=>{h&&k()};if(h){k();const r=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${r}px`,document.body.style.width="100%",document.addEventListener("mousedown",e),window.addEventListener("resize",t)}return()=>{if(h){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",window.scrollTo(0,-1*parseInt(e||"0"))}document.removeEventListener("mousedown",e),window.removeEventListener("resize",t)}},[h]);const _=h&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-30 transition-opacity",style:{zIndex:999998},onClick:()=>{p(!1),m("")}}),t.jsxs("div",{ref:v,className:"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden",style:{top:g.top,left:g.left,width:g.width,maxHeight:g.maxHeight,zIndex:999999,transform:"translateZ(0)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50",children:[t.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:o||"Select Option"}),t.jsx("button",{onClick:()=>{p(!1),m("")},className:"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsx("div",{className:"p-4 border-b border-gray-200 bg-gray-50",children:t.jsx("input",{type:"text",placeholder:"Search networks and tokens...",value:f,onChange:e=>m(e.target.value),className:"w-full p-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#7042D2]/20 focus:border-[#7042D2] text-base",style:{fontFamily:"Bricolage Grotesque, sans-serif"},autoFocus:!0})}),t.jsx("div",{className:"overflow-y-auto custom-scrollbar",style:{maxHeight:(g.maxHeight||450)-180+"px",minHeight:"200px"},children:0===w.length?t.jsxs("div",{className:"p-8 text-gray-500 text-center",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"text-4xl mb-3",children:"🔍"}),t.jsx("div",{className:"text-lg mb-2",children:"No options found"}),t.jsx("div",{className:"text-sm text-gray-400",children:"Try a different search term"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("span",{className:"font-semibold",children:w.length})," option",1!==w.length?"s":""," available"]}),t.jsx("div",{className:"p-2",children:w.map(e=>t.jsx("button",{type:"button",onClick:()=>{i(c(e)),p(!1),m("")},className:"w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 "+(c(e)===n?"bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30":"text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20"),style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:s(e)},a(e)))})]})}),t.jsx("div",{className:"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center",children:t.jsx("div",{className:"text-xs text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:w.length>5?"↕️ Scroll to see more options":"✨ Select your preferred option"})})]})]});return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"relative",children:t.jsx("button",{ref:b,type:"button",onClick:()=>{d||(h||k(),p(!h))},disabled:d,className:`w-full p-4 border-2 rounded-2xl bg-gradient-to-r from-white to-gray-50 text-left focus:outline-none focus:ring-3 focus:ring-[#7042D2]/20 focus:border-[#7042D2] transition-all duration-300 ease-out shadow-lg hover:shadow-xl ${d?"opacity-50 cursor-not-allowed":"hover:border-[#7042D2]/50 cursor-pointer"} ${h?"border-[#7042D2] ring-3 ring-[#7042D2]/20":"border-gray-200"}`,style:{minHeight:"60px",fontFamily:"Bricolage Grotesque, sans-serif",fontSize:"16px",fontWeight:"500"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center space-x-3",children:x?s(x):t.jsx("span",{className:"text-gray-500",children:o})}),t.jsx("div",{className:"transform transition-transform duration-200 "+(h?"rotate-180":""),children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 text-[#7042D2]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]})})}),"undefined"!=typeof document&&document.body&&l.createPortal(_,document.body),t.jsx("style",{children:"\n .custom-scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #7042D2 #f1f1f1;\n }\n .custom-scrollbar::-webkit-scrollbar {\n width: 12px;\n }\n .custom-scrollbar::-webkit-scrollbar-track {\n background: #f8f9fa;\n border-radius: 10px;\n margin: 4px;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb {\n background: linear-gradient(180deg, #7042D2 0%, #5b34b1 100%);\n border-radius: 10px;\n border: 2px solid #f8f9fa;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb:hover {\n background: linear-gradient(180deg, #5b34b1 0%, #4c2a93 100%);\n }\n .custom-scrollbar::-webkit-scrollbar-corner {\n background: #f8f9fa;\n }\n "})]})},wE=({currentStep:e,targetStep:n,children:i,className:o="",duration:s=300})=>{const[a,c]=r.useState(e===n),[l,u]=r.useState(e===n);return r.useEffect(()=>{e===n?(u(!0),setTimeout(()=>c(!0),10)):(c(!1),setTimeout(()=>u(!1),s))},[e,n,s]),l?t.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${a?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${o}\n `,style:{transitionDuration:`${s}ms`},children:i}):null},xE=e=>parseFloat(e).toFixed(2),kE=({status:e,message:n,theme:i="light",payment:o=null,transactionHash:s=null,selectedPaymentMethod:a=null,selectedNetwork:c=null,merchantName:l="Merchant",onClose:u=null})=>{const[d,h]=r.useState(!1),[p,f]=r.useState(0);r.useEffect(()=>{if("processing"===e){const e=setInterval(()=>{f(e=>e>=90?e:e+15*Math.random())},500);return()=>clearInterval(e)}},[e]);const m=async()=>{if(s)try{await navigator.clipboard.writeText(s),h(!0),setTimeout(()=>h(!1),2e3)}catch(yA){}},g=()=>{switch(e){case"processing":return t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20"}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("div",{className:"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse"})})]});case"success":return t.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return t.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"processing"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Processing Payment"}),t.jsx("p",{className:"text-center text-gray-600 mb-6",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Your transaction has been sent to the blockchain and is being processed..."}),t.jsxs("div",{className:"w-full max-w-xs mb-4",children:[t.jsx("div",{className:"bg-gray-200 rounded-full h-3",children:t.jsx("div",{className:"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out",style:{width:`${p}%`}})}),t.jsxs("div",{className:"text-center mt-2 text-sm text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Processing... ",Math.round(p),"%"]})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Transaction submitted"})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Confirming on blockchain..."})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-gray-300 rounded-full"}),t.jsx("span",{className:"text-sm text-gray-400",children:"Finalizing payment..."})]})]}),t.jsx("div",{className:"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-800 text-center",children:"Please don't close this window. This usually takes 10-30 seconds."})})]}):"success"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Payment Successful!"}),o&&a&&t.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Your payment of ",t.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[o.totalAmount||o.amount," ",a.currency]})," has been completed."]}),s&&t.jsxs("div",{className:"w-full mb-6 px-4",children:[t.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Transaction Details"}),t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100 mb-3",onClick:m,children:[t.jsx("span",{className:"font-mono text-sm text-gray-700",children:(y=s,y?y.length<=16?y:`${y.slice(0,8)}...${y.slice(-8)}`:"")}),t.jsxs("div",{className:"flex items-center",children:[d?t.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(()=>{const e=((e,t)=>{if(!e||!t)return null;const r="string"==typeof t?t:t.shortName||t.name;return{ethereum:`https://etherscan.io/tx/${e}`,bsc:`https://bscscan.com/tx/${e}`,polygon:`https://polygonscan.com/tx/${e}`,arbitrum:`https://arbiscan.io/tx/${e}`,optimism:`https://optimistic.etherscan.io/tx/${e}`,avalanche:`https://snowtrace.io/tx/${e}`,celo:`https://celoscan.io/tx/${e}`,base:`https://basescan.org/tx/${e}`,solana:`https://explorer.solana.com/tx/${e}`,"solana-mainnet":`https://explorer.solana.com/tx/${e}`,"solana-devnet":`https://explorer.solana.com/tx/${e}?cluster=devnet`,"solana devnet":`https://explorer.solana.com/tx/${e}?cluster=devnet`}[null==r?void 0:r.toLowerCase()]||null})(s,c),r=(e=>{if(!e)return"Explorer";const t="string"==typeof e?e:e.shortName||e.name;return{ethereum:"Etherscan",bsc:"BscScan",polygon:"PolygonScan",arbitrum:"Arbiscan",optimism:"Optimistic Etherscan",avalanche:"SnowTrace",celo:"CeloScan",base:"BaseScan",solana:"Solana Explorer","solana-mainnet":"Solana Explorer","solana-devnet":"Solana Explorer (Devnet)","solana devnet":"Solana Explorer (Devnet)"}[null==t?void 0:t.toLowerCase()]||"Explorer"})(c);return c&&e&&t.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 w-full p-3 rounded-lg border border-[#7042D2] bg-white hover:bg-purple-50 transition-colors group",children:[t.jsxs("span",{className:"text-sm font-medium text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["View on ",r]}),t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})()]}),u&&t.jsx("button",{onClick:u,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Close"})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[t.jsx("div",{className:"mb-4",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),t.jsx("p",{className:"text-center text-gray-600",children:n})]});var y},_E={bitcoin:1,ethereum:1027,bsc:1839,polygon:3890,cardano:2010,avalanche:5805,fantom:3513,arbitrum:11841,optimism:11840,USDT:825,USDC:3408,BUSD:4687,DAI:4943,FRAX:6952,TUSD:2563,USDP:5992,USDD:5994,FDUSD:26081,PYUSD:28295,WBTC:3717,LINK:1975,UNI:7083,AAVE:7278,COMP:5692,YFI:5864,MKR:1518,SUSHI:6758,CRV:6538,SNX:2586,UMA:5617,BAL:5728,MANA:1966,SAND:6210,APE:18876,LDO:8e3,GRT:6719,ENS:13855,RPL:2943,SHIB:5994,MATIC:3890,BNB:1839,ADA:2010,SOL:5426,DOT:6636,AVAX:5805,TRX:1958,ALGO:4030,FTM:3513,ARB:11841,OP:11840,"1INCH":8104,DYDX:11156,ICP:8916,FIL:2280,CAKE:7186,RUNE:4157,ALPHA:7232,BNT:1727,KNC:1982,ZRX:1896,REN:2539,LRC:1934,WETH:2396,WMATIC:3890,WBNB:1839,UST:7129,USTC:7129,LUSD:8115,MIM:9681,FEI:8642,TRIBE:8741,RAI:8525,SUSD:2927},SE={ethereum:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bsc:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",polygon:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arbitrum:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avalanche:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",celo:"https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png",optimism:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",base:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",eth:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bnb:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",trx:"https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png",algo:"https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png",matic:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arb:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avax:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",op:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",sol:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png",solana:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png","solana-mainnet":"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png","solana-devnet":"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png"},CE={metamask:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",coinbase:"https://avatars.githubusercontent.com/u/18060234?s=280&v=4",rabby:"https://rabby.io/logo-128.png",zerion:"https://app.zerion.io/favicon-32x32.png",okx:"https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png",binance:"https://bin.bnbstatic.com/static/images/common/favicon.ico",cryptocom:"https://crypto.com/favicon.ico","1inch":"https://1inch.io/favicon.svg",hot:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==",phantom:"https://phantom.app/img/phantom-logo.svg",solflare:"https://solflare.com/assets/logo.svg",backpack:"https://www.backpack.exchange/_next/image?url=%2Fbackpack-logo.png&w=128&q=75",trust:"https://trustwallet.com/assets/images/favicon.png",default:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=="},IE=e=>(e=>{if(!e)return null;const t=_E[e.toUpperCase()];return t?`https://s2.coinmarketcap.com/static/img/coins/64x64/${t}.png`:null})(e),EE=e=>"object"==typeof e&&(null==e?void 0:e.logo)?e.logo:"object"==typeof e&&(null==e?void 0:e.shortName)?SE[e.shortName.toLowerCase()]:"string"==typeof e?SE[e.toLowerCase()]:null,AE=(e,t)=>{const r=e.toLowerCase(),n=t.toLowerCase();for(const[i,o]of Object.entries(CE))if(r.includes(i)||n.includes(i))return o;return CE.default},NE=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ME=e=>{switch(e){case"trust":return window.ethereum&&!0===window.ethereum.isTrust;case"metaMask":return window.ethereum&&!0===window.ethereum.isMetaMask;case"injected":return window.ethereum&&!window.ethereum.isMetaMask&&!window.ethereum.isCoinbaseWallet;default:return!1}},PE=(e,t)=>{if(!t)return[];if(!["ethereum","bsc","polygon","arbitrum","optimism","avalanche","celo","base"].includes(t.shortName))return[];return[...(e||[]).map(e=>(e=>({type:e.id,name:e.name,icon:AE(e.name,e.id),description:`Connect using ${e.name}`,isInstalled:!0,connector:e,isWagmi:!0}))(e)),...NE()?[{type:"trust",name:"Trust Wallet",icon:"🛡️",description:"Multi-chain wallet with transaction deep links",isInstalled:!1,connector:null,isWagmi:!1,mobileOnly:!0,hasTransactionDeepLinks:!0}]:[]]},TE=(e,t,r,n,i="metamask",o=null)=>{if(!e)return null;try{const t="https://payment.coinley.io",n=new URLSearchParams,o=(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId);if(!o)return null;n.set("paymentId",o),n.set("preferredWallet",i),n.set("isMobile","true");const s=`${t}?${n.toString()}`;let a;switch(i){case"metamask":a=`https://metamask.app.link/dapp/${s.replace("https://","")}`;break;case"trust":const e=(null==r?void 0:r.chainId)||1;a=`https://link.trustwallet.com/open_url?coin_id=${(e=>{const t="string"==typeof e&&e.startsWith("0x")?parseInt(e,16):parseInt(e);return[1,56,137,42161,10,43114,42220,8453].includes(t)?60:{}[t]||60})(e)}&url=${encodeURIComponent(s)}`;break;case"coinbase":a=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(s)}`;break;default:a=s}return a}catch(ud){return null}},OE=(e,t)=>{if(!t)return null;try{switch(e){case"metamask":return t.includes("metamask.app.link")?t:`https://metamask.app.link/dapp/${t.replace("https://","")}`;case"trust":return t.includes("link.trustwallet.com")?t:`https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(t)}`;case"coinbase":return t.includes("go.cb-w.com")?t:`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t)}`;default:return t}}catch(ud){return t}},BE=Object.freeze(Object.defineProperty({__proto__:null,generateMobilePaymentDeepLink:OE,generateQRPaymentURI:TE},Symbol.toStringTag,{value:"Module"})),RE=({walletAddress:e,amount:n,currency:i,network:o,theme:s="light",paymentData:a=null,onPaymentDetected:c=null,config:l=null,selectedToken:d=null,selectedNetwork:h=null,preferredWallet:p="metamask",compact:f=!1})=>{const[m,g]=r.useState(""),[y,v]=r.useState(""),[b,w]=r.useState(!0),[x,k]=r.useState(!1),[_,S]=r.useState(!1),C=r.useRef(null);return r.useEffect(()=>{(async()=>{if(null==a?void 0:a.id){w(!0);try{if(!d||!d.contractAddress)throw new Error("Cannot generate QR code: Token contract address required");if(!h||!h.chainId)throw new Error("Cannot generate QR code: Network chain ID required");const e=TE(a,0,h,0,p);if(e.includes("metamask.app.link")||e.includes("link.trustwallet.com")||e.includes("go.cb-w.com"),!e)throw new Error("Failed to generate Coinley payment URL");g(e);const t=NE(),r=await u.toDataURL(e,{width:f?140:t?350:280,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===s?"#FFFFFF":"#000000",light:"dark"===s?"#000000":"#FFFFFF"}});v(r),w(!1)}catch(ud){w(!1)}}else w(!1)})()},[a,n,i,o,s,d,h,l,p]),r.useEffect(()=>()=>{C.current&&clearInterval(C.current)},[]),t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex gap-3 items-start w-full mb-2",children:[t.jsx("div",{className:"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0",children:b?t.jsx("div",{className:"flex items-center justify-center",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1"}),t.jsx("div",{className:"text-xs text-gray-600",children:"Generating..."})]})}):y?t.jsx("img",{src:y,alt:"Payment QR Code",className:"rounded-lg",style:{width:140,height:140}}):t.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center p-2",children:[t.jsx("div",{className:"text-lg mb-1",children:"⚠️"}),t.jsx("div",{className:"text-xs text-gray-600",children:(null==a?void 0:a.id)?"QR Failed":"Payment not created"})]})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-center",children:[t.jsxs("div",{className:"p-2 bg-gray-50 rounded-lg mb-2",children:[t.jsxs("div",{className:"flex justify-between items-center mb-1",children:[t.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"text-sm font-bold text-[#7042D2]",children:[n," ",i]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),t.jsx("span",{className:"text-xs font-medium text-gray-700",children:o})]})]}),_?t.jsxs("div",{className:"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg",children:[t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Payment Received!"]}):t.jsx("div",{className:"p-1.5 rounded-lg bg-blue-50 border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-700 text-center leading-tight",children:"📱 Scan with phone camera"})})]})]})})},jE=({selectedNetwork:e,onWalletSelect:i,onConnect:o,connectedWallet:s,loading:a,paymentData:c=null,selectedToken:l=null,api:u=null,onSolanaConnect:d=null,solanaWallet:h=null})=>{const[p,f]=r.useState(null),m=r.useMemo(()=>e?bm(e.type||e.shortName||e.id):fm,[e])===mm,{connectors:g}=n.useConnect(),{isConnected:y,address:v}=n.useAccount(),b=r.useMemo(()=>m?h.availableWallets.map(e=>({type:e.id,name:e.name,icon:AE(e.name,e.id)||"🔗",description:e.adapter?"Available":"Not installed",isSolana:!0,wallet:e})):PE(g,e),[m,h.availableWallets,g,e]),w=async(t,r)=>{if(NE())if(c)try{const{generateQRPaymentURI:n,generateMobilePaymentDeepLink:i}=await Promise.resolve().then(()=>BE),o=n(c,l,e,(null==u?void 0:u.config)||{},r);if(!o)throw new Error("Failed to generate payment URL");const s=i(r,o);if(!s)throw new Error(`Failed to generate ${t.name} deep link`);window.location.href=s}catch(ud){alert(`Failed to open ${t.name}: ${ud.message}`)}else alert("Please create a payment first before selecting a mobile wallet.");else alert(`Please install ${t.name} mobile app or use the browser extension if available.`)};return e?0===b.length?t.jsxs("div",{className:"text-center p-4",children:[t.jsxs("p",{className:"text-gray-500 mb-4",children:["No compatible wallets found for ",e.name]}),t.jsx("div",{className:"p-3 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-sm text-amber-800",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"font-medium mb-2",children:"Install a compatible wallet:"}),t.jsx("div",{className:"space-y-1 text-xs",children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:["• ",t.jsx("a",{href:dm.PHANTOM.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Phantom Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:dm.SOLFLARE.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Solflare Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:dm.BACKPACK.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Backpack Wallet"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://metamask.io/download/",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install MetaMask Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://www.coinbase.com/wallet",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Coinbase Wallet"})]})]})})]})})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Select Wallet for ",e.name]}),t.jsx(bE,{options:b,value:(null==s?void 0:s.walletType)||p||"",onChange:async e=>{f(e);const t=b.find(t=>t.type===e);if(t){if(i(e),t.isSolana){try{const t=await h.connectWallet(e);d&&await d({walletType:e,publicKey:t,wallet:h})}catch(ud){console.error("Failed to connect Solana wallet:",ud),alert(`Failed to connect: ${ud.message}`)}return}t.isWagmi&&t.connector?await o(t.connector):t.isWagmi||await w(t,e)}},placeholder:"Choose your wallet...",renderOption:e=>{var r,n,i,o,c,l,u;return t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsxs("div",{className:"w-8 h-8 flex items-center justify-center",children:[e.icon.startsWith("http")||e.icon.startsWith("data:")?t.jsx("img",{src:e.icon,alt:e.name,className:"w-6 h-6 rounded-full object-contain",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="block"}}):t.jsx("div",{className:"text-2xl",children:e.icon}),t.jsx("div",{className:"text-xl",style:{display:"none"},children:"🔗"})]}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800 flex items-center",children:[e.name,!e.isSolana&&ME(e.type)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),e.isSolana&&(null==(r=e.wallet)?void 0:r.adapter)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),e.isSolana&&(null==(n=h.connectedWallet)?void 0:n.id)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"}),!e.isSolana&&(null==s?void 0:s.walletType)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.isSolana&&(null==(i=h.connectedWallet)?void 0:i.id)===e.type?`Connected • ${null==(o=h.publicKey)?void 0:o.slice(0,6)}...${null==(c=h.publicKey)?void 0:c.slice(-4)}`:(null==s?void 0:s.walletType)===e.type?`Connected • ${null==(l=s.account)?void 0:l.slice(0,6)}...${null==(u=s.account)?void 0:u.slice(-4)}`:e.description})]}),a&&p===e.type&&t.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]"})]})},getOptionKey:e=>e.type,getOptionValue:e=>e.type,getSearchableText:e=>`${e.name} ${e.description}`,disabled:a})]}):t.jsx("div",{className:"text-center p-4",children:t.jsx("p",{className:"text-gray-500",children:"Please select a network first"})})},LE=(()=>{if(void 0!==ae&&ae.env)return!1;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.includes("192.168.")}return!1})()||(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search);return"true"===e.get("debug")||"true"===e.get("debugMode")}return!1})(),DE=({paymentData:e,selectedToken:n,selectedNetwork:i,config:o,onPaymentStarted:s=()=>{},onError:a=()=>{}})=>{var c,l;const[u,d]=r.useState(null),[h,p]=r.useState(!1),[f,m]=r.useState([]),[g,y]=r.useState(!1),[v,b]=r.useState(0);r.useEffect(()=>{var t,r,o;(null==e?void 0:e.id)&&(null==n?void 0:n.contractAddress)&&(null==i?void 0:i.chainId)&&((null==(t=null==e?void 0:e.contractCall)?void 0:t.contractAddress)||(null==e?void 0:e.contractAddress))?w("success","✅ Payment data complete",{paymentId:e.id,tokenContract:n.contractAddress,chainId:i.chainId,paymentContract:(null==(o=null==e?void 0:e.contractCall)?void 0:o.contractAddress)||(null==e?void 0:e.contractAddress)}):(w("debug","⏳ Waiting for complete payment data",{hasPaymentId:!!(null==e?void 0:e.id),hasTokenContract:!!(null==n?void 0:n.contractAddress),hasChainId:!!(null==i?void 0:i.chainId),hasPaymentContract:!(!(null==(r=null==e?void 0:e.contractCall)?void 0:r.contractAddress)&&!(null==e?void 0:e.contractAddress)),checkCount:v}),b(e=>e+1))},[e,n,i,v]);const w=(e,t,r=null)=>{const n=(new Date).toLocaleTimeString(),i={id:Date.now()+Math.random(),type:e,message:t,data:r,timestamp:n};LE&&(m(e=>[...e,i].slice(-20)),e.toUpperCase())},x=[{id:"metamask",name:"MetaMask",icon:"🦊",description:"Connect with MetaMask mobile"},{id:"trust",name:"Trust Wallet",icon:"🛡️",description:"Connect with Trust Wallet"},{id:"coinbase",name:"Coinbase Wallet",icon:"💙",description:"Connect with Coinbase Wallet"}];if(!e)return t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⚠️ Payment Required"}),t.jsx("div",{className:"text-sm text-amber-700",children:"Please create a payment before selecting a wallet"})]})});const k=(null==e?void 0:e.id)&&(null==n?void 0:n.contractAddress)&&(null==i?void 0:i.chainId)&&((null==(c=null==e?void 0:e.contractCall)?void 0:c.contractAddress)||(null==e?void 0:e.contractAddress));return t.jsx("div",{className:"space-y-4",children:k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Select Mobile Wallet"}),t.jsx(bE,{options:x,value:u||"",onChange:async t=>{const r=x.find(e=>e.id===t);if(r){d(t),p(!0);try{if(w("info",`🚀 Mobile wallet selected: ${r.name}`),!e)throw new Error("Payment data not available. Please create payment first.");w("debug","🔍 Payment Data Check",{hasPaymentData:!!e,hasSelectedToken:!!n,hasSelectedNetwork:!!i,hasConfig:!!o,paymentId:(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId),tokenAddress:null==n?void 0:n.contractAddress,networkChainId:null==i?void 0:i.chainId,amount:(null==e?void 0:e.totalAmount)||(null==e?void 0:e.amount)||(null==o?void 0:o.amount)});const a=TE(e,0,i,0,t);if(!a)throw new Error("Failed to generate payment URL");w("success","📱 Generated payment URL",{url:a,length:a.length});const c=OE(t,a);if(!c)throw new Error(`Failed to generate ${r.name} deep link`);w("success",`🔗 Deep link generated for ${r.name}`,{deepLink:c}),s({walletType:t,walletName:r.name,paymentUrl:a,deepLink:c}),setTimeout(()=>{w("info",`📱 Opening ${r.name}...`),window.location.href=c},500)}catch(ud){w("error","❌ Mobile wallet connection failed",{error:ud.message,walletId:t,hasPaymentData:!!e,hasSelectedToken:!!n,hasSelectedNetwork:!!i}),a(ud.message),p(!1),d(null)}}},placeholder:"Choose your wallet...",renderOption:e=>t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsx("div",{className:"w-8 h-8 flex items-center justify-center",children:t.jsx("div",{className:"text-2xl",children:e.icon})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name,u===e.id&&h&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse",children:"Opening..."})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.description})]})]}),getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.description}`,disabled:h}),t.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"Select a wallet to open it with your payment details"})]}),h&&u&&t.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse",children:t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"}),t.jsxs("div",{className:"text-sm text-blue-700",children:["Opening ",null==(l=x.find(e=>e.id===u))?void 0:l.name,"..."]})]})}),t.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[t.jsxs("div",{className:"flex justify-between items-center text-sm",children:[t.jsx("span",{className:"text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"font-semibold text-gray-800",children:[e.totalAmount," ",(null==n?void 0:n.symbol)||"USDC"]})]}),t.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[t.jsx("span",{className:"text-gray-600",children:"Network:"}),t.jsx("span",{className:"text-gray-800",children:(null==i?void 0:i.name)||"Ethereum"})]})]}),t.jsx("div",{className:"p-3 bg-purple-50 border border-purple-200 rounded-lg",children:t.jsxs("div",{className:"text-xs text-purple-700",children:[t.jsx("div",{className:"font-medium mb-1",children:"📱 Mobile Payment"}),t.jsx("div",{children:"Your selected wallet app will open with payment details pre-filled"})]})}),LE&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("button",{onClick:()=>y(!g),className:"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors",children:[g?"🔽 Hide Debug Info":"🔧 Show Debug Info"," (",f.length," logs)"]}),g&&t.jsxs("div",{className:"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto",children:[t.jsx("div",{className:"text-white mb-2 font-bold",children:"📱 Mobile Debug Panel"}),0===f.length?t.jsx("div",{className:"text-gray-400",children:"No debug logs yet. Try selecting a wallet..."}):f.map(e=>t.jsxs("div",{className:"mb-3 pb-2 border-b border-gray-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"px-2 py-1 rounded text-xs font-bold "+("error"===e.type?"bg-red-600 text-white":"success"===e.type?"bg-green-600 text-white":"debug"===e.type?"bg-blue-600 text-white":"bg-gray-600 text-white"),children:e.type.toUpperCase()}),t.jsx("span",{className:"text-gray-400",children:e.timestamp})]}),t.jsx("div",{className:"text-yellow-300 mb-1",children:e.message}),e.data&&t.jsx("div",{className:"text-gray-300 text-xs",children:t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer text-blue-300 hover:text-blue-200",children:"📊 Data"}),t.jsx("pre",{className:"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(e.data,null,2)})]})})]},e.id)),t.jsx("button",{onClick:()=>m([]),className:"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700",children:"Clear Logs"})]})]})]}):t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⏳ Preparing Payment..."}),t.jsx("div",{className:"text-sm text-amber-700",children:"Payment is being prepared. Please wait a moment..."}),t.jsx("div",{className:"mt-3",children:t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto"})})]})})})},UE=({error:e,onRetry:r,onDismiss:n,context:i="payment",className:o=""})=>{if(!e)return null;const s=Gv(e),a=(e=>{switch(e){case"user_rejected":return"info";case"insufficient_funds":case"wrong_network":case"wallet_disconnected":case"payment_pending":return"warning";case"network_error":case"gas_error":case"rate_limited":return"error";default:return"critical"}})(s.type),c=(e=>{switch(e){case"user_rejected":default:return"Try Again";case"insufficient_funds":return"Add Funds & Retry";case"wrong_network":return"Switch Network & Retry";case"wallet_disconnected":return"Reconnect Wallet";case"payment_pending":return"Check Again";case"network_error":case"rate_limited":return"Retry";case"popup_blocked":return"Allow Popups & Retry";case"mobile_wallet_error":return"Open Wallet App"}})(s.type),l={info:{container:"bg-blue-50 border-blue-200",title:"text-blue-800",message:"text-blue-700",icon:"ℹ️",button:"bg-blue-600 hover:bg-blue-700"},warning:{container:"bg-amber-50 border-amber-200",title:"text-amber-800",message:"text-amber-700",icon:"⚠️",button:"bg-amber-600 hover:bg-amber-700"},error:{container:"bg-red-50 border-red-200",title:"text-red-800",message:"text-red-700",icon:"❌",button:"bg-red-600 hover:bg-red-700"},critical:{container:"bg-red-50 border-red-300",title:"text-red-900",message:"text-red-800",icon:"🚨",button:"bg-red-700 hover:bg-red-800"}},u=l[a]||l.error;return t.jsxs("div",{className:`p-4 border rounded-lg ${u.container} ${o}`,children:[t.jsxs("div",{className:"flex items-start space-x-3",children:[t.jsx("div",{className:"flex-shrink-0 text-xl",children:u.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:`font-semibold ${u.title} mb-1`,children:s.title}),t.jsx("div",{className:`text-sm ${u.message} mb-2`,children:s.message}),s.suggestion&&t.jsxs("div",{className:`text-xs ${u.message} opacity-90`,children:["💡 ",s.suggestion]})]}),n&&t.jsx("button",{onClick:n,className:"flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Dismiss error",children:t.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:t.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),r&&t.jsxs("div",{className:"mt-3 flex justify-end space-x-2",children:[n&&"info"===a&&t.jsx("button",{onClick:n,className:"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:r,className:`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${u.button}`,children:c})]}),!1]})},FE="method",zE="confirm",qE="processing",$E="success",WE="wallet",HE="qr",GE="deposit",VE="Bricolage Grotesque, sans-serif",KE=({depositAddress:e,amount:n,currency:i,network:o,networkName:s,paymentId:a,expiresAt:c,requiredConfirmations:l=20,theme:d="light",api:h=null,onPaymentDetected:p=null,onPaymentConfirmed:f=null,onPaymentProcessing:m=null,onExpired:g=null,explorerUrl:y=null})=>{const[v,b]=r.useState(""),[w,x]=r.useState(!0),[k,_]=r.useState(!1),[S,C]=r.useState("awaiting"),[I,E]=r.useState("0"),[A,N]=r.useState(0),[M,P]=r.useState(null),[T,O]=r.useState(!1),[B,R]=r.useState(null),[j,L]=r.useState(null),D=r.useRef(null),U=r.useRef(null),F=r.useRef(!1),z=r.useRef(!1),q=NE();r.useEffect(()=>{(async()=>{if(e){x(!0);try{const t=await u.toDataURL(e,{width:q?200:180,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===d?"#FFFFFF":"#000000",light:"dark"===d?"#1F2937":"#FFFFFF"}});b(t),x(!1)}catch(ud){console.error("Failed to generate QR code:",ud),x(!1)}}else x(!1)})()},[e,d,q]),r.useEffect(()=>{if(!c)return;const e=()=>{const e=(new Date).getTime(),t=new Date(c).getTime()-e;if(t<=0)return O(!0),P(null),void(g&&g());const r=Math.floor(t%36e5/6e4),n=Math.floor(t%6e4/1e3);P(`${r}:${n.toString().padStart(2,"0")}`)};return e(),U.current=setInterval(e,1e3),()=>{U.current&&clearInterval(U.current)}},[c,g]);const $=r.useCallback(async()=>{if(h&&a&&"confirmed"!==S&&"swept"!==S)try{const t=await h.getDepositBalance(a);let r=!1,i="0";t.success&&(i=t.balance||"0",E(i),r=t.isComplete,parseFloat(i)>0&&"awaiting"===S&&(C("detected"),p&&p(t)),r&&"confirming"!==S&&"confirmed"!==S&&(C("confirming"),j||L(Date.now()),!F.current&&m&&(F.current=!0,m({balance:i,expectedAmount:n,depositAddress:e,paymentId:a}))));const o=await h.getDepositStatus(a);let s=null;if(o.success&&o.payment){const e=o.payment;s=e.status,N(e.confirmations||0),e.depositTxHash&&R(e.depositTxHash);const t="completed"===e.status||"swept"===e.status,r=e.depositTxHash||e.sweepTxHash||e.transactionHash;if(t&&r&&!z.current&&(z.current=!0,C("swept"===e.status?"swept":"confirmed"),f)){const t={...e,transactionHash:e.depositTxHash||e.sweepTxHash||e.transactionHash};f(t)}e.sweptAt&&"swept"!==S&&C("swept")}if(r&&j&&!z.current&&B){const t=Date.now()-j;t>=3e4&&(z.current=!0,C("confirmed"),f&&f({id:a,status:"completed",depositAddress:e,amount:i,depositTxHash:B,transactionHash:B,confirmations:A||l,sdkConfirmed:!0,confirmedAt:(new Date).toISOString()}))}}catch(ud){console.warn("Failed to check deposit status:",ud.message)}},[h,a,S,n,e,A,B,j,l,p,f,m]);r.useEffect(()=>{if(h&&a&&!T)return $(),D.current=setInterval($,5e3),()=>{D.current&&clearInterval(D.current)}},[h,a,T,$]);const W=(()=>{if(T)return{message:"Payment expired",color:"text-red-600",bgColor:"bg-red-50",icon:"⏰"};switch(S){case"detected":case"confirming":return{message:"Transfer detected! Processing...",color:"text-blue-600",bgColor:"bg-blue-50",icon:"⏳"};case"confirmed":return{message:"Payment confirmed!",color:"text-green-600",bgColor:"bg-green-50",icon:"✅"};case"swept":return{message:"Payment complete - Funds delivered!",color:"text-green-600",bgColor:"bg-green-50",icon:"🎉"};default:return{message:"Send exact amount to address below",color:"text-gray-600",bgColor:"bg-gray-50",icon:"📤"}}})(),H="dark"===d;return t.jsxs("div",{className:"flex flex-col items-center w-full",style:{fontFamily:VE},children:[t.jsx("div",{className:`w-full p-3 rounded-lg mb-4 ${W.bgColor} border ${H?"border-gray-600":"border-gray-200"}`,children:t.jsxs("div",{className:`flex items-center justify-center ${W.color} font-medium`,children:[t.jsx("span",{className:"mr-2",children:W.icon}),W.message]})}),t.jsxs("div",{className:`flex ${q?"flex-col":"flex-row"} gap-4 w-full`,children:[t.jsx("div",{className:"flex-shrink-0 "+(q?"mx-auto":""),children:t.jsx("div",{className:`p-2 rounded-xl ${H?"bg-gray-800":"bg-white"} shadow-md border ${H?"border-gray-700":"border-gray-200"}`,children:w?t.jsx("div",{className:"flex items-center justify-center",style:{width:q?200:180,height:q?200:180},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600 mx-auto mb-2"}),t.jsx("div",{className:"text-sm "+(H?"text-gray-400":"text-gray-600"),children:"Generating..."})]})}):v?t.jsx("img",{src:v,alt:"Transfer Address QR",className:"rounded-lg",style:{width:q?200:180,height:q?200:180}}):t.jsx("div",{className:"flex items-center justify-center rounded-lg "+(H?"bg-gray-700":"bg-gray-100"),style:{width:q?200:180,height:q?200:180},children:t.jsx("span",{className:"text-sm "+(H?"text-gray-400":"text-gray-500"),children:"QR unavailable"})})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-between",children:[t.jsxs("div",{className:`p-3 rounded-lg mb-3 ${H?"bg-gray-800":"bg-purple-50"} border ${H?"border-gray-700":"border-purple-200"}`,children:[t.jsx("div",{className:"text-xs font-medium mb-1 "+(H?"text-gray-400":"text-purple-600"),children:"Send Exactly:"}),t.jsxs("div",{className:"text-2xl font-bold text-[#7042D2]",children:[n," ",i]}),t.jsxs("div",{className:"text-xs mt-1 "+(H?"text-gray-400":"text-gray-500"),children:["on ",s||o]})]}),t.jsxs("div",{className:`p-3 rounded-lg ${H?"bg-gray-800":"bg-gray-50"} border ${H?"border-gray-700":"border-gray-200"}`,children:[t.jsx("div",{className:"text-xs font-medium mb-2 "+(H?"text-gray-400":"text-gray-600"),children:"Transfer Address:"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("code",{className:`flex-1 text-xs font-mono break-all p-2 rounded ${H?"bg-gray-900 text-gray-300":"bg-white text-gray-800"} border ${H?"border-gray-700":"border-gray-300"}`,children:e}),t.jsx("button",{onClick:async()=>{try{await navigator.clipboard.writeText(e),_(!0),setTimeout(()=>_(!1),2e3)}catch(ud){console.error("Failed to copy:",ud)}},className:"p-2 rounded-lg transition-colors "+(k?"bg-green-500 text-white":H?"bg-gray-700 text-gray-300 hover:bg-gray-600":"bg-gray-200 text-gray-700 hover:bg-gray-300"),title:k?"Copied!":"Copy address",children:k?t.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}):t.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})})]})]}),t.jsxs("div",{className:"flex gap-2 mt-3",children:[M&&!T&&"awaiting"===S&&t.jsxs("div",{className:`flex-1 p-2 rounded-lg text-center ${H?"bg-gray-800":"bg-orange-50"} border ${H?"border-gray-700":"border-orange-200"}`,children:[t.jsx("div",{className:"text-xs "+(H?"text-gray-400":"text-orange-600"),children:"Expires in"}),t.jsx("div",{className:"text-lg font-bold "+(H?"text-orange-400":"text-orange-600"),children:M})]}),parseFloat(I)>0&&t.jsxs("div",{className:`flex-1 p-2 rounded-lg text-center ${H?"bg-gray-800":"bg-green-50"} border ${H?"border-gray-700":"border-green-200"}`,children:[t.jsx("div",{className:"text-xs "+(H?"text-gray-400":"text-green-600"),children:"Received"}),t.jsxs("div",{className:"text-lg font-bold "+(H?"text-green-400":"text-green-600"),children:[I," ",i]})]})]})]})]}),B&&y&&t.jsx("div",{className:"w-full mt-4",children:t.jsxs("a",{href:`${y}/tx/${B}`,target:"_blank",rel:"noopener noreferrer",className:`flex items-center justify-center gap-2 p-2 rounded-lg ${H?"bg-gray-800 text-blue-400 hover:bg-gray-700":"bg-blue-50 text-blue-600 hover:bg-blue-100"} transition-colors`,children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),"View transaction on explorer"]})}),t.jsxs("div",{className:`w-full mt-4 p-3 rounded-lg ${H?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"} border`,children:[t.jsx("div",{className:"text-xs font-medium mb-2 "+(H?"text-gray-300":"text-gray-700"),children:"📋 Instructions:"}),t.jsxs("ol",{className:"text-xs space-y-1 "+(H?"text-gray-400":"text-gray-600"),children:[t.jsx("li",{children:"1. Copy the transfer address or scan QR code"}),t.jsxs("li",{children:["2. Send ",t.jsxs("strong",{children:[n," ",i]})," from any wallet"]}),t.jsxs("li",{children:["3. Wait for ",l," confirmations"]}),t.jsx("li",{children:"4. Payment will be automatically confirmed"})]})]})]})},ZE=new i.QueryClient,YE=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,config:s,onSuccess:a,onError:c,onClose:l,isOpen:u,theme:d="light"})=>{var h;const p=sm(o,e||n,e?null:i),f=wm(),m=Jv(),g=r.useMemo(()=>p.selectedNetwork?bm(p.selectedNetwork.type||p.selectedNetwork.shortName||p.selectedNetwork.id):fm,[p.selectedNetwork])===mm,y=r.useMemo(()=>!(!g||!p.selectedNetwork)&&(e=>{if(!e)return!1;const t=!0===e.isTestnet||"true"===e.isTestnet,r=(e.name||"").toLowerCase().includes("devnet"),n=(e.shortName||"").toLowerCase().includes("devnet"),i=(e.type||"").toLowerCase().includes("devnet"),o=(e.id||"").toLowerCase().includes("devnet");return t||r||n||i||o})(p.selectedNetwork),[g,p.selectedNetwork]),v=r.useMemo(()=>{if(!g||!p.selectedNetwork)return[];return pm()},[g,p.selectedNetwork,y]),b=vE(v,m.connectedWallet),[w,x]=r.useState("metamask"),[k,_]=r.useState(!1),[S,C]=r.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[I,E]=r.useState(!1);r.useEffect(()=>{_(NE())},[]);const{currentStep:A,networks:N,tokens:M,selectedNetwork:P,selectedToken:T,paymentData:O,loading:B,error:R,paymentType:j,loadData:L,createPayment:D,createDepositPayment:U,isDepositSupported:F,failPayment:z,resetState:q,setSelectedNetwork:$,setSelectedToken:W,setPaymentType:H,setCurrentStep:G,setError:V}=p,{connectedWallet:K,address:Z,connectWallet:Y,handleWalletSelection:J,resetState:X}=f,Q=Yv(O,T,P,Z,p.api,f),{executePaymentTransaction:ee,processFinalPayment:te,transactionStep:re,transactionError:ne,currentTransactionHash:ie}=Q;r.useEffect(()=>{A===$E&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[A]),r.useEffect(()=>{if(u){L(),q(),em.trackModalOpened(null==s?void 0:s.merchantName,null==s?void 0:s.amount);const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[u]),r.useEffect(()=>{if("processing"===re||"approve"===re||"splitPayment"===re){const e=setTimeout(()=>{V("Transaction timed out. Please try again."),G(zE),Q.resetTransaction()},12e4);return()=>clearTimeout(e)}},[re]),r.useEffect(()=>{if(A!==qE||j!==GE||!(null==O?void 0:O.id))return;const e=setInterval(async()=>{try{const t=await p.api.getDepositStatus(O.id);if(t.success&&t.payment){const r=t.payment.status,n=t.payment.depositTxHash||t.payment.sweepTxHash||t.payment.transactionHash;"completed"!==r&&"swept"!==r||!n?("completed"!==r&&"swept"!==r||n)&&("failed"!==r&&"sweep_failed"!==r||(clearInterval(e),V("Payment failed. Please try again."),G(zE))):(clearInterval(e),G($E),a&&a({paymentId:O.id,transactionHash:n,depositAddress:t.payment.depositAddress,network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:t.payment}))}}catch(t){console.warn("[DepositPolling] Error checking status:",t.message)}},5e3);return()=>{clearInterval(e)}},[A,j,null==O?void 0:O.id,P,T,a]);const oe=()=>{var e;Q.resetTransaction(),null==(e=b.resetTransaction)||e.call(b),null==X||X(),V(""),E(!1),C(!1),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started"),"undefined"!=typeof window&&(window.coinleyPendingSplitPayment=null)},se=async()=>{em.trackModalClosed("user_cancelled"),oe(),await z(),l()},ae={ethereum:{text:"High fees",color:"text-red-500"},polygon:{text:"~$0.01 fees",color:"text-green-500"},bsc:{text:"~$0.02 fees",color:"text-green-500"},base:{text:"~$0.03 fees",color:"text-green-500"},optimism:{text:"~$0.60 fees",color:"text-yellow-600"},arbitrum:{text:"~$0.50 fees",color:"text-yellow-600"},avalanche:{text:"Low fees",color:"text-green-500"},celo:{text:"Low fees",color:"text-green-500"},solana:{text:"~$0.001 fees",color:"text-green-500"}};return u?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:se,"aria-hidden":"true"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"relative pt-4 w-full max-w-md max-h-[90vh] mx-auto shadow-xl bg-gray-100 rounded-3xl flex flex-col overflow-hidden",style:{zIndex:52},children:[t.jsxs("div",{className:"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full",children:[t.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[t.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",children:t.jsx("img",{src:tm,alt:"Coinley"})}),t.jsx("span",{className:"text-base font-semibold text-gray-800",style:{fontFamily:VE},children:"Payment Details"})]}),A!==$E&&A!==qE&&t.jsx("button",{onClick:se,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),s&&A!==$E&&t.jsx("div",{className:"flex-shrink-0 mb-3 px-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-xs text-gray-600",children:"Total Amount"}),t.jsxs("div",{className:"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight",style:{fontFamily:VE},children:["$",xE(s.amount)]}),t.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"No additional fees"}),t.jsx("div",{className:"text-xs text-gray-600 mt-2",children:"Payment to:"}),t.jsxs("div",{className:"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center",style:{fontFamily:VE},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),s.merchantName||"Merchant"]})]})}),t.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[t.jsx(wE,{currentStep:A,targetStep:FE,children:t.jsxs("div",{className:"pb-4 pt-3 px-5 bg-white rounded-t-2xl",children:[t.jsx("h3",{className:"font-semibold text-center mb-3 text-sm",style:{fontFamily:VE},children:"Choose Payment Method"}),t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:VE},children:"Select Network"}),t.jsx(bE,{options:N,value:(null==P?void 0:P.id)||"",onChange:e=>{const t=N.find(t=>t.id===e);oe(),$(t),W(null),em.trackNetworkSelected(null==t?void 0:t.name,null==s?void 0:s.merchantName)},placeholder:"Choose your network...",renderOption:e=>{var r,n,i;const o=EE(e),s=ae[null==(r=e.shortName)?void 0:r.toLowerCase()];return t.jsxs("div",{className:"flex items-center space-x-3 w-full",children:[o?t.jsx("img",{src:o,alt:e.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:o?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.shortName)?void 0:n.slice(0,2).toUpperCase()})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"font-semibold text-gray-800",children:e.name}),s&&t.jsx("span",{className:`text-xs font-medium ${s.color}`,children:s.text})]}),t.jsx("div",{className:"text-sm text-gray-500",children:null==(i=e.shortName)?void 0:i.toUpperCase()})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.shortName}`,disabled:B})]}),P&&t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:VE},children:"Select Token"}),t.jsx(bE,{options:M.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==P?void 0:P.shortName)||e.networkId===(null==P?void 0:P.id)}),value:(null==T?void 0:T.id)||"",onChange:e=>{const t=M.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==P?void 0:P.shortName)||e.networkId===(null==P?void 0:P.id)}).find(t=>t.id===e);W(t),em.trackTokenSelected(null==t?void 0:t.symbol,null==P?void 0:P.name,null==s?void 0:s.merchantName)},placeholder:"Choose your token...",renderOption:e=>{var r,n;const i=IE(e.symbol);return t.jsxs("div",{className:"flex items-center space-x-3",children:[i?t.jsx("img",{src:i,alt:e.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:i?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(r=e.symbol)?void 0:r.slice(0,2)})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name," (",e.symbol,")"]}),t.jsxs("div",{className:"text-sm text-gray-500",children:[(null==(n=e.Network)?void 0:n.name)||"Unknown Network",e.isStablecoin&&t.jsx("span",{className:"ml-2 text-green-600",children:"• Stablecoin"})]})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.symbol}`,disabled:B})]}),P&&T&&t.jsx("button",{onClick:()=>D(s),disabled:B,className:"w-full bg-[#7042D2] text-white py-4 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200 shadow-lg hover:shadow-xl",style:{fontFamily:VE},children:B?"Creating Payment...":"Continue"})]})}),t.jsx(wE,{currentStep:A,targetStep:zE,children:P&&T&&O&&t.jsxs("div",{className:"pb-4 pt-4 px-4 bg-white rounded-t-2xl",children:[!k&&t.jsx("div",{className:"mb-4",children:t.jsxs("div",{className:"flex border-b border-gray-200",children:[t.jsx("button",{onClick:()=>H(WE),className:"py-3 px-4 text-sm font-semibold transition-all duration-200 "+(j===WE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:VE},children:"Wallet"}),F()&&t.jsx("button",{onClick:()=>H(GE),className:"py-3 px-4 text-sm font-semibold transition-all duration-200 "+(j===GE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:VE},children:"Transfer"}),t.jsx("button",{onClick:()=>H(HE),className:"py-3 px-4 text-sm font-semibold transition-all duration-200 "+(j===HE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:VE},children:"QR Code"})]})}),k?t.jsx(DE,{paymentData:O,selectedToken:T,selectedNetwork:P,config:s,onPaymentStarted:e=>{C(!0),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.setItem("coinley_mobile_payment_started","true"),e.walletName},onError:e=>{V(e)}}):j===WE?t.jsx(jE,{selectedNetwork:P,onWalletSelect:J,onConnect:async e=>{await Y(e,P)},connectedWallet:g?m.connectedWallet:K,loading:B,solanaWallet:m,onSolanaConnect:async({walletType:e,publicKey:t,wallet:r})=>{}}):null,j===HE&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-2",children:[t.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1.5 text-center",style:{fontFamily:VE},children:"Optimize QR for:"}),t.jsx("div",{className:"flex gap-1.5 justify-center flex-wrap",children:[{id:"metamask",name:"MetaMask",icon:"🦊"},{id:"trust",name:"Trust",icon:"🛡️"},{id:"coinbase",name:"Coinbase",icon:"💙"}].map(e=>t.jsxs("button",{onClick:()=>x(e.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 "+(w===e.id?"bg-[#7042D2] text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"),style:{fontFamily:VE},children:[t.jsx("span",{className:"text-sm",children:e.icon}),t.jsx("span",{children:e.name})]},e.id))})]}),t.jsx(RE,{amount:(null==O?void 0:O.totalAmount)||(null==O?void 0:O.amount)||(null==s?void 0:s.amount),currency:null==T?void 0:T.symbol,network:null==P?void 0:P.shortName,theme:d,paymentData:O,config:s,selectedToken:T,selectedNetwork:P,preferredWallet:w,compact:!0})]}),j===GE&&(null==O?void 0:O.isDepositPayment)&&t.jsxs(t.Fragment,{children:[t.jsx(KE,{depositAddress:O.depositAddress,amount:O.amount,currency:null==T?void 0:T.symbol,network:null==P?void 0:P.shortName,networkName:null==P?void 0:P.name,paymentId:O.id,expiresAt:O.expiresAt,requiredConfirmations:O.requiredConfirmations||20,theme:d,api:p.api,explorerUrl:(null==(h=O.explorer)?void 0:h.address)?O.explorer.address.split("/address/")[0]:null,onPaymentDetected:e=>{},onPaymentProcessing:e=>{G(qE)},onPaymentConfirmed:e=>{const t=e.transactionHash||e.depositTxHash||e.sweepTxHash;G($E),a&&t&&a({paymentId:e.id,transactionHash:t,sweepTxHash:e.sweepTxHash,network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e,sdkConfirmed:e.sdkConfirmed||!1})},onExpired:()=>{V("Payment expired. Please create a new payment.")}}),t.jsx("div",{className:"mt-4",children:t.jsx("button",{type:"button",onClick:()=>{oe(),G(FE)},className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:VE},children:"Cancel & Choose Different Method"})})]}),j===GE&&!(null==O?void 0:O.isDepositPayment)&&t.jsxs("div",{className:"text-center py-6",children:[t.jsxs("div",{className:"mb-4",children:[t.jsx("div",{className:"text-4xl mb-2",children:"💸"}),t.jsx("h3",{className:"text-lg font-semibold text-gray-800",style:{fontFamily:VE},children:"Transfer Payment"}),t.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get a unique address to send crypto from any wallet"})]}),t.jsx("button",{onClick:async()=>{try{await U(s)}catch(yA){}},disabled:B,className:"w-full bg-[#7042D2] text-white py-3 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200",style:{fontFamily:VE},children:B?"Generating Address...":"Generate Transfer Address"}),t.jsx("p",{className:"text-xs text-gray-500 mt-3",children:"Supported on Base, BSC, Arbitrum, Polygon, Optimism & Avalanche"})]}),(R||ne)&&t.jsx("div",{className:"mt-4",children:t.jsx(UE,{error:ne||R,onRetry:()=>{V(""),Q.resetTransaction(),"error"===re&&K&&ee()},onDismiss:()=>{V(""),Q.resetTransaction()},context:"payment"})}),!(j===GE&&(null==O?void 0:O.isDepositPayment))&&t.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:()=>{oe(),G(FE)},className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:VE},children:"Back"}),t.jsx("button",{type:"button",onClick:async()=>{var e,t,r,n,i,o,s,c,l,u,d,h,f,v,w,x,_,C,I,A,N,M,B,R,L,D;if(k&&S){if(!(null==O?void 0:O.id))return void V("Payment ID not found. Please refresh and try again.");try{E(!0),G(qE),V("");const h=await p.api.checkPaymentStatus(O.id),f="completed"===(null==(e=h.payment)?void 0:e.status)||"swept"===(null==(t=h.payment)?void 0:t.status),g=(null==(r=h.payment)?void 0:r.transactionHash)||(null==(n=h.payment)?void 0:n.sweepTxHash)||(null==(i=h.payment)?void 0:i.depositTxHash);if(f&&g)G($E),a&&a({paymentId:O.id,transactionHash:g,senderAddress:h.payment.senderWalletAddress||h.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:h.payment});else if(f&&!g){(async()=>{var e,t,r;for(let n=0;n<12;n++){await new Promise(e=>setTimeout(e,5e3));const n=await p.api.checkPaymentStatus(O.id),i=(null==(e=n.payment)?void 0:e.transactionHash)||(null==(t=n.payment)?void 0:t.sweepTxHash)||(null==(r=n.payment)?void 0:r.depositTxHash);if(i)return G($E),void(a&&a({paymentId:O.id,transactionHash:i,senderAddress:n.payment.senderWalletAddress||n.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:n.payment}))}V("Payment confirmed but transaction details unavailable. Please contact support."),G(zE)})()}else if("pending"===(null==(o=h.payment)?void 0:o.status)){const e=await p.api.verifyQRPayment(O.id),t=(null==(s=e.onChainData)?void 0:s.transactionHash)||(null==(c=e.payment)?void 0:c.transactionHash);if(e.success&&e.verified&&t)G($E),a&&a({paymentId:O.id,transactionHash:t,senderAddress:(null==(l=e.onChainData)?void 0:l.from)||(null==(u=e.payment)?void 0:u.senderWalletAddress)||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";V(`${t}. Please complete the payment in your wallet and try again.`),G(zE)}}else"failed"===(null==(d=h.payment)?void 0:d.status)?(V("Payment failed. Please try creating a new payment."),G(zE)):(V("Payment not found. Please verify the payment ID and try again."),G(zE))}catch(U){V(`Verification failed: ${U.message}. Please ensure payment was completed and try again.`),G(zE)}finally{E(!1)}}else if(j!==HE){if(g&&m.isConnected||K&&Z)try{let e;if(G(qE),V(""),!g&&Q.setTransactionError&&Q.setTransactionError(""),g){const t=(null==O?void 0:O.recipientWallet)||(null==O?void 0:O.merchantWallet)||(null==O?void 0:O.merchantWalletAddress);if(!t)throw new Error("Merchant wallet address not found");if("SOL"===T.symbol||T.isNative){e=(await b.sendSOL(t,parseFloat(O.totalAmount||O.amount))).signature}else{const r=parseFloat(O.totalAmount||O.amount),n=T.decimals||6,i=null==(B=T.symbol)?void 0:B.toUpperCase();let o=T.address||T.contractAddress;if(o&&o.length>=32&&o.length<=44&&!o.startsWith("0x"));else{const e=(y?hm:um)[i];(null==e?void 0:e.address)&&(o=e.address)}if(O.coinleyWallet&&O.merchantPercentage&&O.coinleyPercentage){const i=r*O.merchantPercentage/1e4,s=r*O.coinleyPercentage/1e4;e=(await b.sendSplitPayment({tokenMintAddress:o,merchantAddress:t,coinleyAddress:O.coinleyWallet,merchantAmount:i,coinleyAmount:s,decimals:n})).signature}else{e=(await b.sendSPLToken(o,t,r,n)).signature}}await p.api.processPayment(O.id,e,P.shortName,m.publicKey)}else e=await ee();if(e&&(V(""),Q.setTransactionError(""),G($E),a)){const t={paymentId:O.id,transactionHash:e,senderAddress:g?null==m?void 0:m.publicKey:Z,network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:O};a(t)}}catch(U){G(zE),(null==(R=U.message)?void 0:R.includes("User rejected"))||(null==(L=U.message)?void 0:L.includes("User denied"))||4001===U.code||"ACTION_REJECTED"===U.code?V("Transaction was cancelled by user. Please try again."):V(U.message||"Transaction failed. Please try again."),g?null==(D=b.resetTransaction)||D.call(b):Q.resetTransaction()}}else{if(!(null==O?void 0:O.id))return void V("Payment ID not found. Please refresh and try again.");try{G(qE),V("");const e=await p.api.checkPaymentStatus(O.id),t="completed"===(null==(h=e.payment)?void 0:h.status)||"swept"===(null==(f=e.payment)?void 0:f.status),r=(null==(v=e.payment)?void 0:v.transactionHash)||(null==(w=e.payment)?void 0:w.sweepTxHash)||(null==(x=e.payment)?void 0:x.depositTxHash);if(t&&r)G($E),a&&a({paymentId:O.id,transactionHash:r,senderAddress:e.payment.senderWalletAddress||e.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e.payment});else if(t&&!r){(async()=>{var e,t,r;for(let n=0;n<12;n++){await new Promise(e=>setTimeout(e,5e3));const n=await p.api.checkPaymentStatus(O.id),i=(null==(e=n.payment)?void 0:e.transactionHash)||(null==(t=n.payment)?void 0:t.sweepTxHash)||(null==(r=n.payment)?void 0:r.depositTxHash);if(i)return G($E),void(a&&a({paymentId:O.id,transactionHash:i,senderAddress:n.payment.senderWalletAddress||n.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:n.payment}))}V("Payment confirmed but transaction details unavailable. Please contact support."),G(zE)})()}else if("pending"===(null==(_=e.payment)?void 0:_.status)){const e=await p.api.verifyQRPayment(O.id),t=(null==(C=e.onChainData)?void 0:C.transactionHash)||(null==(I=e.payment)?void 0:I.transactionHash);if(e.success&&e.verified&&t)G($E),a&&a({paymentId:O.id,transactionHash:t,senderAddress:(null==(A=e.onChainData)?void 0:A.from)||(null==(N=e.payment)?void 0:N.senderWalletAddress)||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";V(`${t}. Please complete the payment and try again.`),G(zE)}}else"failed"===(null==(M=e.payment)?void 0:M.status)?(V("Payment failed. Please try creating a new payment."),G(zE)):(V("Payment not found. Please verify the payment ID and try again."),G(zE))}catch(U){V(`Verification failed: ${U.message}. Please ensure payment was completed and try again.`),G(zE)}}},className:"bg-green-600 text-white w-full py-2.5 px-3 font-semibold rounded-xl hover:bg-green-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 text-sm",disabled:j===WE&&!k&&!g&&!K||j===WE&&!k&&g&&!m.isConnected||k&&!S||"processing"===re||b.isProcessing||I,style:{fontFamily:VE},children:I?"Verifying...":"processing"===re||b.isProcessing?"Processing...":k&&S?"I Have Paid":k?"Select Wallet":j===HE?"I Have Paid":"Pay Now"})]})]})}),t.jsx(wE,{currentStep:A,targetStep:qE,children:t.jsx(kE,{status:"processing",message:j===GE?"Transfer received! Confirming on blockchain...":g?b.isProcessing?"Confirming Solana transaction...":"Processing your Solana payment...":"approve"===re?"Approving token spending...":"splitPayment"===re?"Processing payment split...":ie?"Confirming transaction on blockchain...":"Processing your payment...",theme:d,transactionHash:g?b.txSignature:ie,selectedNetwork:P})}),t.jsx(wE,{currentStep:A,targetStep:$E,children:t.jsx(kE,{status:"success",message:"Payment completed successfully!",theme:d,payment:O,transactionHash:g?b.txSignature||(null==O?void 0:O.transactionHash):ie||(null==O?void 0:O.transactionHash),selectedPaymentMethod:T,selectedNetwork:P,merchantName:(null==s?void 0:s.merchantName)||"Merchant",onClose:l})}),(R||ne)&&t.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4",children:[t.jsx("p",{className:"text-red-800 text-sm",children:R||ne}),t.jsx("button",{onClick:()=>{V(""),Q.setTransactionError("")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]}),A!==$E&&t.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",style:{fontFamily:VE},children:[t.jsxs("p",{children:["Powered by ",t.jsx("span",{className:"text-[#7042D2] font-semibold",children:"Coinley"})," - Multi-Wallet Support"]}),t.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})]}):null},JE=e=>t.jsx(n.WagmiProvider,{config:im,children:t.jsx(i.QueryClientProvider,{client:ZE,children:t.jsx(YE,{...e})})}),XE=r.createContext(null),QE=r.forwardRef(({customerEmail:e="",merchantName:t="",onSuccess:n,onError:i,onClose:o,theme:s="light",autoOpen:a=!1,testMode:c=!1,debug:l=!1,merchantWalletAddresses:u={}},d)=>{const h=r.useContext(XE);if(!h)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:p,closePayment:f}=h,m=t=>{try{if(!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const r={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...u,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};p(r,{onSuccess:n,onError:i,onClose:o})}catch(ud){i&&i(ud)}},g=()=>{f()};return r.useImperativeHandle(d,()=>({open:m,close:g})),null});QE.displayName="CoinleyCheckout";const eA=new i.QueryClient,tA="wallet",rA="qr",nA="transfer",iA=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,config:s,onSuccess:a,onError:c,onClose:l,isOpen:d,theme:h="light"})=>{const p=sm(o,e||n,e?null:i),f=wm(),m=Jv(),g=r.useMemo(()=>p.selectedNetwork?bm(p.selectedNetwork.type||p.selectedNetwork.shortName||p.selectedNetwork.id):fm,[p.selectedNetwork])===mm,y=r.useMemo(()=>!(!g||!p.selectedNetwork)&&(e=>{if(!e)return!1;const t=!0===e.isTestnet||"true"===e.isTestnet,r=(e.name||"").toLowerCase().includes("devnet"),n=(e.shortName||"").toLowerCase().includes("devnet"),i=(e.type||"").toLowerCase().includes("devnet"),o=(e.id||"").toLowerCase().includes("devnet");return t||r||n||i||o})(p.selectedNetwork),[g,p.selectedNetwork]),v=r.useMemo(()=>g&&p.selectedNetwork?pm():[],[g,p.selectedNetwork,y]),b=vE(v,m.connectedWallet),[w,x]=r.useState(tA),[k,_]=r.useState(""),[S,C]=r.useState(!1),[I,E]=r.useState(""),[A,N]=r.useState(!1),[M,P]=r.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[T,O]=r.useState(!1);r.useEffect(()=>{N(NE())},[]);const{currentStep:B,networks:R,tokens:j,selectedNetwork:L,selectedToken:D,paymentData:U,loading:F,error:z,paymentType:q,loadData:$,createPayment:W,createDepositPayment:H,failPayment:G,resetState:V,setSelectedNetwork:K,setSelectedToken:Z,setCurrentStep:Y,setError:J}=p,{connectedWallet:X,address:Q,connectWallet:ee,handleWalletSelection:te,resetState:re}=f,ne=Yv(U,D,L,Q,p.api,f),{executePaymentTransaction:ie,processFinalPayment:oe,transactionStep:se,transactionError:ae,currentTransactionHash:ce}=ne;r.useEffect(()=>{U&&D&&L&&w===rA&&le()},[U,D,L,w]);const le=async()=>{if(U)try{const e=`https://payment.coinley.io/?paymentId=${U.id}&amount=${U.totalAmount||U.amount}&token=${null==D?void 0:D.symbol}&network=${null==L?void 0:L.shortName}`,t=await u.toDataURL(e,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"}});E(t)}catch(yA){console.error("Error generating QR code:",yA)}};r.useEffect(()=>{B===$E&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[B]),r.useEffect(()=>{if(d){$(),V(),em.trackModalOpened(null==s?void 0:s.merchantName,null==s?void 0:s.amount);const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(d){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[d]),r.useEffect(()=>{if("processing"===se||"approve"===se||"splitPayment"===se){const e=setTimeout(()=>{J("Transaction timed out. Please try again."),Y(zE),ne.resetTransaction()},12e4);return()=>clearTimeout(e)}},[se]),r.useEffect(()=>{if(B!==qE||q!==GE||!(null==U?void 0:U.id))return;const e=setInterval(async()=>{try{const t=await p.api.getDepositStatus(U.id);if(t.success&&t.payment){const r=t.payment.status,n=t.payment.depositTxHash||t.payment.sweepTxHash||t.payment.transactionHash;"completed"!==r&&"swept"!==r||!n?"failed"!==r&&"sweep_failed"!==r||(clearInterval(e),J("Payment failed. Please try again."),Y(zE)):(clearInterval(e),Y($E),a&&a({paymentId:U.id,transactionHash:n,depositAddress:t.payment.depositAddress,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol,paymentDetails:t.payment}))}}catch(t){console.warn("[DepositPolling] Error checking status:",t.message)}},5e3);return()=>clearInterval(e)},[B,q,null==U?void 0:U.id,L,D,a]);const ue=()=>{var e;ne.resetTransaction(),null==(e=b.resetTransaction)||e.call(b),null==re||re(),J(""),O(!1),P(!1),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started"),"undefined"!=typeof window&&(window.coinleyPendingSplitPayment=null)},de=async()=>{em.trackModalClosed("user_cancelled"),ue(),await G(),l()},he=r.useMemo(()=>{if(!k)return R;const e=k.toLowerCase();return R.filter(t=>{var r;return t.name.toLowerCase().includes(e)||(null==(r=t.shortName)?void 0:r.toLowerCase().includes(e))})},[R,k]),pe=r.useMemo(()=>L?j.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==L?void 0:L.shortName)||e.networkId===(null==L?void 0:L.id)}):[],[j,L]),fe=e=>{ue(),K(e),Z(null),em.trackNetworkSelected(null==e?void 0:e.name,null==s?void 0:s.merchantName)},me=e=>{Z(e),em.trackTokenSelected(null==e?void 0:e.symbol,null==L?void 0:L.name,null==s?void 0:s.merchantName)},ge=async()=>{var e,t,r,n,i,o,s,c,l,u;if(null==U?void 0:U.id)try{O(!0),Y(qE),J("");const d=await p.api.checkPaymentStatus(U.id),h="completed"===(null==(e=d.payment)?void 0:e.status)||"swept"===(null==(t=d.payment)?void 0:t.status),f=(null==(r=d.payment)?void 0:r.transactionHash)||(null==(n=d.payment)?void 0:n.sweepTxHash)||(null==(i=d.payment)?void 0:i.depositTxHash);if(h&&f)Y($E),a&&a({paymentId:U.id,transactionHash:f,senderAddress:d.payment.senderWalletAddress||d.payment.fromAddress,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol,paymentDetails:d.payment});else if("pending"===(null==(o=d.payment)?void 0:o.status)){const e=await p.api.verifyQRPayment(U.id),t=(null==(s=e.onChainData)?void 0:s.transactionHash)||(null==(c=e.payment)?void 0:c.transactionHash);if(e.success&&e.verified&&t)Y($E),a&&a({paymentId:U.id,transactionHash:t,senderAddress:(null==(l=e.onChainData)?void 0:l.from)||(null==(u=e.payment)?void 0:u.senderWalletAddress),network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";J(`${t}. Please complete the payment and try again.`),Y(zE)}}else J("Payment not found or failed. Please try again."),Y(zE)}catch(d){J(`Verification failed: ${d.message}. Please try again.`),Y(zE)}finally{O(!1)}else J("Payment ID not found. Please refresh and try again.")},ye=e=>e?`${e.slice(0,12)}......${e.slice(-12)}`:"";return d?B===qE?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50",onClick:de}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsx("div",{className:"bg-white rounded-2xl p-8 max-w-md w-full",children:t.jsx(kE,{status:"processing",message:w===nA?"Transfer received! Confirming on blockchain...":g?"Processing your Solana payment...":"Processing your payment...",theme:h,transactionHash:g?b.txSignature:ce,selectedNetwork:L})})})]}):B===$E?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsx("div",{className:"bg-white rounded-2xl p-8 max-w-md w-full",children:t.jsx(kE,{status:"success",message:"Payment completed successfully!",theme:h,payment:U,transactionHash:g?b.txSignature||(null==U?void 0:U.transactionHash):ce||(null==U?void 0:U.transactionHash),selectedPaymentMethod:D,selectedNetwork:L,merchantName:(null==s?void 0:s.merchantName)||"Merchant",onClose:l})})})]}):t.jsxs("div",{className:"fixed inset-0 z-50",style:{fontFamily:VE},children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50",onClick:de}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"bg-gray-50 rounded-2xl shadow-2xl w-[709px] h-[698.17px] overflow-hidden flex",children:[t.jsxs("div",{className:"w-56 bg-gray-50 p-6 flex flex-col border-r border-gray-200",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-4",children:"Pay With :"}),t.jsxs("button",{onClick:()=>x(tA),className:"flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all mb-2 "+(w===tA?"bg-white text-[#7042D2] border-l-4 border-[#7042D2] shadow-sm":"text-gray-400 hover:bg-gray-100"),children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"})}),t.jsx("span",{className:"text-sm font-medium whitespace-nowrap",children:"Wallet extension"})]}),t.jsxs("button",{onClick:()=>x(rA),className:"flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all mb-2 "+(w===rA?"bg-white text-[#7042D2] border-l-4 rounded-none border-[#7042D2] shadow-sm":"text-gray-400 hover:bg-gray-100"),children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"})}),t.jsx("span",{className:"text-sm font-medium whitespace-nowrap",children:"Scan QR to pay"})]}),t.jsxs("button",{onClick:()=>x(nA),className:"flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all "+(w===nA?"bg-white text-[#7042D2] border-l-4 border-[#7042D2] shadow-sm":"text-gray-400 hover:bg-gray-100"),children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"})}),t.jsx("span",{className:"text-sm font-medium whitespace-nowrap",children:"Transfer to address"})]})]}),t.jsxs("div",{className:"flex-1 bg-white rounded-r-2xl p-6 overflow-y-auto",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("img",{src:tm,alt:"Coinley",className:"w-6 h-6"}),t.jsx("span",{className:"text-lg font-semibold text-gray-800",children:"coinley"})]}),t.jsx("button",{onClick:de,className:"w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center hover:bg-gray-200 transition-colors",children:t.jsx("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 mb-6",children:[t.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"Payment summary"}),t.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[t.jsx("svg",{className:"w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"})}),t.jsxs("span",{className:"font-medium",children:["Payment to: ",(null==s?void 0:s.merchantName)||"Merchant"]})]}),t.jsxs("div",{className:"flex items-baseline justify-between",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-gray-400",children:"Amount:"}),t.jsxs("p",{className:"text-3xl text-[#7042D2] font-bold text-gray-900",children:["$",xE((null==s?void 0:s.amount)||0)]})]}),(null==U?void 0:U.id)&&t.jsxs("div",{className:"text-right",children:[t.jsx("p",{className:"text-xs text-gray-400",children:"Transaction Hash:"}),t.jsx("p",{className:"text-xs text-gray-600",children:ye(U.id)})]})]})]}),w===tA&&!S&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Select a network"}),t.jsxs("div",{className:"relative mb-4",children:[t.jsx("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),t.jsx("input",{type:"text",placeholder:"Search Network",value:k,onChange:e=>_(e.target.value),className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#7042D2] focus:border-transparent"})]}),t.jsx("div",{className:"grid grid-cols-2 gap-3",children:he.map(e=>t.jsxs("button",{onClick:()=>fe(e),className:"flex items-center gap-3 p-3 rounded-xl border-2 transition-all "+((null==L?void 0:L.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2] hover:bg-purple-50"),children:[t.jsx("img",{src:EE(e),alt:e.name,className:"w-10 h-10 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.shortName}&background=7042D2&color=fff`}}),t.jsxs("div",{className:"text-left",children:[t.jsx("p",{className:"font-semibold text-gray-900",children:e.name}),t.jsx("p",{className:"text-xs text-gray-400",children:"Blockchain network"})]})]},e.id))})]}),L&&pe.length>0&&t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Choose a token"}),t.jsx("p",{className:"text-sm text-gray-400 mb-4",children:"Select an option from these available tokens"}),t.jsx("div",{className:"grid grid-cols-2 gap-3",children:pe.map(e=>t.jsxs("button",{onClick:()=>me(e),className:"flex items-center gap-3 p-3 rounded-xl border-2 transition-all "+((null==D?void 0:D.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2] hover:bg-purple-50"),children:[t.jsx("img",{src:IE(e.symbol),alt:e.symbol,className:"w-10 h-10 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.symbol}&background=7042D2&color=fff`}}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("p",{className:"font-semibold text-gray-900",children:e.name||e.symbol}),e.isStablecoin&&t.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[t.jsx("span",{className:"w-1.5 h-1.5 bg-green-500 rounded-full"}),"Stablecoin"]})]}),t.jsx("p",{className:"text-xs text-gray-400",children:ye(e.contractAddress||e.address)})]})]},e.id))})]}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsx("button",{onClick:de,className:"px-8 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:async()=>{L&&D&&(U||await W(s),C(!0))},disabled:!L||!D||F,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:F?"Creating Payment...":"Connect my Wallet"})]})]}),w===tA&&S&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Confirm Payment"}),t.jsx("div",{className:"bg-gray-50 rounded-xl p-4 mb-4",children:t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("img",{src:EE(L),alt:null==L?void 0:L.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.src=`https://ui-avatars.com/api/?name=${null==L?void 0:L.shortName}&background=7042D2&color=fff`}}),t.jsx("span",{className:"font-medium",children:null==L?void 0:L.name})]}),t.jsx("span",{className:"text-gray-400",children:"•"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("img",{src:IE(null==D?void 0:D.symbol),alt:null==D?void 0:D.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.src=`https://ui-avatars.com/api/?name=${null==D?void 0:D.symbol}&background=7042D2&color=fff`}}),t.jsx("span",{className:"font-medium",children:null==D?void 0:D.symbol})]})]})}),t.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 space-y-3",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Product Amount"}),t.jsxs("span",{className:"font-medium",children:["$",xE((null==U?void 0:U.productAmount)||(null==s?void 0:s.amount)||0)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Processing Fee"}),t.jsxs("span",{className:"font-medium",children:["+$",xE((null==U?void 0:U.platformFee)||0)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Network Fee"}),t.jsxs("span",{className:"font-medium",children:["+$",xE((null==U?void 0:U.networkFee)||0)]})]}),t.jsxs("div",{className:"border-t border-gray-200 pt-3 flex justify-between",children:[t.jsx("span",{className:"font-semibold",children:"Total"}),t.jsxs("span",{className:"font-bold text-lg",children:[xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount)||0)," ",null==D?void 0:D.symbol]})]})]})]}),t.jsx("div",{className:"mb-6",children:t.jsx(jE,{selectedNetwork:L,onWalletSelect:te,onConnect:async e=>{await ee(e,L)},connectedWallet:g?m.connectedWallet:X,loading:F,paymentData:U,selectedToken:D,api:p.api,solanaWallet:m,onSolanaConnect:async({walletType:e,publicKey:t,wallet:r})=>{}})}),(X||m.connectedWallet)&&t.jsx("div",{className:"bg-green-50 border border-green-200 rounded-xl p-4 mb-4",children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("svg",{className:"w-5 h-5 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium text-green-800",children:"Wallet Connected"}),t.jsx("p",{className:"text-sm text-green-600",children:ye(g?m.publicKey:Q)})]})]})}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsx("button",{onClick:()=>{C(!1),ue()},className:"px-8 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors",children:"Back"}),t.jsx("button",{onClick:async()=>{if(g){if(!m.publicKey||!m.connectedWallet)return void J("Please connect your Solana wallet first");try{Y(qE);const e=await b.executeSplitPayment(U,D,L);if(!e.success)throw new Error(e.error||"Transaction failed");{const t=await p.api.processPayment(U.id,e.signature,m.publicKey);if(!t.success)throw new Error(t.message||"Failed to process payment");Y($E),a&&a({paymentId:U.id,transactionHash:e.signature,senderAddress:m.publicKey,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol})}}catch(yA){J(yA.message||"Transaction failed"),Y(zE)}}else{if(!X||!Q)return void J("Please connect your wallet first");try{Y(qE);const e=await ie();if((null==e?void 0:e.success)&&(null==e?void 0:e.transactionHash))Y($E),a&&a({paymentId:U.id,transactionHash:e.transactionHash,senderAddress:Q,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol});else if(null==e?void 0:e.error)throw new Error(e.error)}catch(yA){J(yA.message||"Transaction failed"),Y(zE)}}},disabled:!(X||m.connectedWallet)||F,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:F?"Processing...":`Pay ${xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount)||0)} ${null==D?void 0:D.symbol}`})]})]}),w===rA&&t.jsxs(t.Fragment,{children:[(!L||!D)&&t.jsxs("div",{className:"text-center py-8",children:[t.jsx("div",{className:"mb-4",children:t.jsx("svg",{className:"w-16 h-16 mx-auto text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"})})}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Generate QR Code"}),t.jsx("p",{className:"text-gray-500 mb-6",children:"Please select a network and token to generate your payment QR code"}),t.jsxs("div",{className:"text-left max-w-md mx-auto",children:[t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Network"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:R.slice(0,4).map(e=>t.jsxs("button",{onClick:()=>fe(e),className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==L?void 0:L.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:EE(e),alt:e.name,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.shortName}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.name})]},e.id))})]}),L&&pe.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Token"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:pe.map(e=>t.jsxs("button",{onClick:async()=>{me(e),U||await W(s)},className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==D?void 0:D.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:IE(e.symbol),alt:e.symbol,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.symbol}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.symbol})]},e.id))})]})]})]}),L&&D&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex gap-6 mb-6",children:[t.jsx("div",{className:"flex-shrink-0",children:I?t.jsx("img",{src:I,alt:"Payment QR Code",className:"w-40 h-40"}):t.jsx("div",{className:"w-40 h-40 bg-gray-100 rounded-lg flex items-center justify-center animate-pulse",children:t.jsx("span",{className:"text-gray-400 text-sm",children:"Generating..."})})}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"font-semibold mb-3",children:"Instructions"}),t.jsxs("ol",{className:"text-sm text-gray-600 space-y-2",children:[t.jsx("li",{children:"1. Open your crypto wallet app (metamask, trust wallet etc)"}),t.jsx("li",{children:"2. Scan the QR code above"}),t.jsxs("li",{children:["3. Confirm the payment amount (",xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount))," ",null==D?void 0:D.symbol,")"]}),t.jsx("li",{children:'4. Click "I\'ve paid" button below after sending the payment'})]})]})]}),t.jsxs("div",{className:"flex justify-between py-3 border-t border-gray-100",children:[t.jsx("span",{className:"text-gray-500",children:"Currency"}),t.jsx("span",{className:"font-medium",children:null==D?void 0:D.symbol})]}),t.jsxs("div",{className:"flex justify-between py-3 border-t border-gray-100",children:[t.jsx("span",{className:"text-gray-500",children:"Network"}),t.jsx("span",{className:"font-medium",children:null==L?void 0:L.name})]}),t.jsxs("div",{className:"bg-purple-50 border border-purple-200 rounded-xl p-4 mt-4 flex items-start gap-3",children:[t.jsx("svg",{className:"w-6 h-6 text-[#7042D2] flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),t.jsxs("p",{className:"text-sm text-[#7042D2]",children:["Make sure you're sending on the correct network (",null==L?void 0:L.name,") and using the exact amount shown above."]})]}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsxs("button",{onClick:()=>{if(I){const e=document.createElement("a");e.download=`coinley-payment-${(null==U?void 0:U.id)||"qr"}.png`,e.href=I,e.click()}},className:"px-6 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors flex items-center gap-2",children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),"Download QR"]}),t.jsx("button",{onClick:ge,disabled:!U||T,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:T?"Verifying...":"I've made the payment"})]})]})]}),w===nA&&t.jsxs(t.Fragment,{children:[(!L||!D||!(null==U?void 0:U.depositAddress))&&t.jsxs("div",{className:"text-center py-8",children:[t.jsx("div",{className:"mb-4",children:t.jsx("svg",{className:"w-16 h-16 mx-auto text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"})})}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Transfer to Address"}),t.jsx("p",{className:"text-gray-500 mb-6",children:"Select a network and token to get the payment address"}),t.jsxs("div",{className:"text-left max-w-md mx-auto",children:[t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Network"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:R.slice(0,4).map(e=>t.jsxs("button",{onClick:()=>fe(e),className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==L?void 0:L.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:EE(e),alt:e.name,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.shortName}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.name})]},e.id))})]}),L&&pe.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Token"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:pe.map(e=>t.jsxs("button",{onClick:()=>me(e),className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==D?void 0:D.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:IE(e.symbol),alt:e.symbol,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.symbol}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.symbol})]},e.id))})]}),L&&D&&!(null==U?void 0:U.depositAddress)&&t.jsx("button",{onClick:async()=>{try{await H(s)}catch(yA){}},disabled:F,className:"w-full py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:F?"Generating Address...":"Generate Transfer Address"})]})]}),L&&D&&(null==U?void 0:U.depositAddress)&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-2",children:"Wallet Address"}),t.jsxs("div",{className:"flex items-center gap-2 p-4 bg-gray-50 rounded-xl border border-gray-200",children:[t.jsx("span",{className:"flex-1 text-sm font-mono text-gray-700 break-all",children:U.depositAddress}),t.jsx("button",{onClick:()=>(async e=>{try{await navigator.clipboard.writeText(e)}catch(yA){console.error("Failed to copy:",yA)}})(U.depositAddress),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors flex-shrink-0",children:t.jsx("svg",{className:"w-5 h-5 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})})]}),t.jsxs("p",{className:"text-xs text-gray-400 mt-2 flex items-center gap-1",children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Double-check before sending. Transactions cannot be reversed."]})]}),t.jsxs("div",{className:"mb-4",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-2",children:"Amount"}),t.jsx("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:t.jsxs("span",{className:"text-lg font-semibold",children:[xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount))," ",null==D?void 0:D.symbol]})})]}),t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-2",children:"Network Fee"}),t.jsx("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:t.jsxs("span",{className:"text-lg font-semibold",children:["$",xE((null==U?void 0:U.networkFee)||.5)]})})]}),t.jsxs("div",{className:"bg-orange-50 border border-orange-200 rounded-xl p-4 flex items-start gap-3",children:[t.jsx("svg",{className:"w-6 h-6 text-orange-500 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),t.jsxs("div",{children:[t.jsxs("p",{className:"font-semibold text-orange-700",children:["Send ",null==D?void 0:D.symbol," on ",null==L?void 0:L.name," network"]}),t.jsxs("p",{className:"text-sm text-orange-600",children:["Use the ",null==L?void 0:L.name," network to send your ",null==D?void 0:D.symbol," quickly and securely with lower transaction fees."]})]})]}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsx("button",{onClick:()=>{ue(),x(tA)},className:"px-8 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors",children:"Go Back"}),t.jsx("button",{onClick:ge,disabled:T,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:T?"Verifying...":"I've made the payment"})]})]})]}),(z||ae)&&t.jsxs("div",{className:"mt-4 p-4 bg-red-50 border border-red-200 rounded-xl",children:[t.jsx("p",{className:"text-red-800 text-sm",children:z||ae}),t.jsx("button",{onClick:()=>{var e;J(""),null==(e=ne.setTransactionError)||e.call(ne,"")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]})]})})]}):null},oA={ethereum:jv,bsc:Iv,polygon:Uv,arbitrum:kv,optimism:Dv,avalanche:_v},sA=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],type:"function"}];const aA=new class{constructor(){this.clients=new Map}getClient(e){if(!this.clients.has(e)){const t=oA[e];if(!t)throw new Error(`Unsupported network: ${e}`);const r=c.createPublicClient({chain:t,transport:c.http()});this.clients.set(e,r)}return this.clients.get(e)}async checkNativeBalance(e,t){try{const r=this.getClient(t),n=await r.getBalance({address:e}),i=c.formatUnits(n,18);return{balance:parseFloat(i),balanceWei:n.toString(),symbol:this.getNativeTokenSymbol(t),decimals:18}}catch(ud){throw new Error(`Failed to check native balance: ${ud.message}`)}}async checkTokenBalance(e,t,r){try{const n=this.getClient(r),i=c.getContract({address:t,abi:sA,client:n}),[o,s,a]=await Promise.all([i.read.balanceOf([e]),i.read.decimals().catch(()=>18),i.read.symbol().catch(()=>"TOKEN")]);return{balance:parseFloat(c.formatUnits(o,s)),balanceWei:o.toString(),symbol:a,decimals:s,tokenAddress:t}}catch(ud){throw new Error(`Failed to check token balance: ${ud.message}`)}}async validateBalance(e,t,r,n,i=!0){try{let o,s=null;o=t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,n):await this.checkNativeBalance(e,n),t.contractAddress&&i&&(s=await this.checkNativeBalance(e,n));const a=o.balance>=r,c=a?0:r-o.balance;let l=0,u=!0,d=0;if(i)if(l=this.estimateGasFee(n,!!t.contractAddress),t.contractAddress)u=s.balance>=l,d=u?0:l-s.balance;else{const e=r+l;u=o.balance>=e,d=u?0:e-o.balance}const h={isValid:a&&u,tokenBalance:o,nativeBalance:s,requiredAmount:r,estimatedGasFee:l,hasEnoughTokens:a,hasEnoughForGas:u,tokenShortfall:c,gasShortfall:d,errors:[]};if(a||h.errors.push(`Insufficient ${t.symbol} balance. Need ${r} ${t.symbol}, have ${o.balance.toFixed(6)} ${t.symbol}`),!u){const e=(null==s?void 0:s.symbol)||this.getNativeTokenSymbol(n);t.contractAddress?h.errors.push(`Insufficient ${e} for gas fees. Need ~${l.toFixed(6)} ${e}, have ${s.balance.toFixed(6)} ${e}`):h.errors.push(`Insufficient ${e} for payment + gas. Need ${(r+l).toFixed(6)} ${e} total, have ${o.balance.toFixed(6)} ${e}`)}return h}catch(ud){return{isValid:!1,errors:[`Failed to check balance: ${ud.message}`],tokenBalance:null,nativeBalance:null}}}estimateGasFee(e,t=!1){return{ethereum:t?.001:5e-4,bsc:t?5e-4:3e-4,polygon:t?.01:.005,arbitrum:t?3e-4:2e-4,optimism:t?3e-4:2e-4,avalanche:t?.001:5e-4}[e]||.001}getNativeTokenSymbol(e){return{ethereum:"ETH",bsc:"BNB",polygon:"MATIC",arbitrum:"ETH",optimism:"ETH",avalanche:"AVAX"}[e]||"ETH"}async getBalance(e,t,r){return t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,r):await this.checkNativeBalance(e,r)}formatBalance(e,t,r=6){return null==e?"Unknown":0===e?`0 ${t}`:e<.001?`${e.toFixed(8)} ${t}`:e<1?`${e.toFixed(6)} ${t}`:`${e.toFixed(4)} ${t}`}async checkMultipleBalances(e,t,r){try{const n=t.map(t=>this.getBalance(e,t,r).catch(e=>({error:e.message,symbol:t.symbol,balance:0})));return await Promise.all(n)}catch(ud){throw ud}}};class cA{constructor(e,t,r){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=r}async request(e,t={}){const r=`${this.baseURL}${e}`,n={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},i=await fetch(r,{...t,headers:n});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`HTTP ${i.status}`)}return i.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(ud){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"},{id:"42220",name:"Celo",shortName:"celo",chainId:"0xa4ec",type:"celo"},{id:"8453",name:"Base",shortName:"base",chainId:"0x2105",type:"base"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(ud){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Binance USD",symbol:"BUSD",contractAddress:"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"USD Coin",symbol:"USDC",contractAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async updatePaymentStatus(e,t,r=null){return await this.request(`/api/payments/${e}/status`,{method:"PUT",body:JSON.stringify({status:t,transactionHash:r})})}}const lA=globalThis||self;!function(){const e=N;"undefined"!=typeof globalThis&&(globalThis.Buffer=e),"undefined"!=typeof window&&(window.Buffer=e),void 0!==lA&&(lA.Buffer=e),"undefined"!=typeof self&&(self.Buffer=e)}();class uA{constructor(e={}){if(!e.publicKey&&!e.apiKey)throw new Error("CoinleyVanilla: publicKey or apiKey is required");if(!e.publicKey&&!e.apiSecret)throw new Error("CoinleyVanilla: apiSecret is required when using apiKey");if(!e.apiUrl)throw new Error("CoinleyVanilla: apiUrl is required");this.config={publicKey:e.publicKey||null,apiKey:e.apiKey||null,apiSecret:e.apiSecret||null,apiUrl:e.apiUrl.replace(/\/$/,""),theme:e.theme||"light",debug:e.debug||!1,...e},this.isOpen=!1,this.root=null,this.container=null,this.callbacks={},this.currentPayment=null,this.config.debug}open(e,t={}){if(!this.isOpen)try{this._validatePaymentConfig(e),this.callbacks=t,this.currentPayment=e,this._createContainer(),this.root=h.createRoot(this.container),this.isOpen=!0,this.root.render(r.createElement(JE,{publicKey:this.config.publicKey,apiKey:this.config.apiKey,apiSecret:this.config.apiSecret,apiUrl:this.config.apiUrl,isOpen:!0,theme:this.config.theme,config:{amount:e.amount,customerEmail:e.customerEmail,merchantName:e.merchantName||"Merchant",callbackUrl:e.callbackUrl||this._getDefaultCallbackUrl(),merchantWalletAddresses:e.merchantWalletAddresses||{},preferredNetwork:e.preferredNetwork,preferredCurrency:e.preferredCurrency,metadata:{...e.metadata,source:"vanilla-sdk",sdkVersion:"2.0.0",timestamp:(new Date).toISOString()}},onSuccess:this._handleSuccess.bind(this),onError:this._handleError.bind(this),onClose:this._handleClose.bind(this)})),this.config.debug}catch(ud){t.onError&&t.onError(ud.message||"Failed to open payment modal")}}close(){this.isOpen&&(this._cleanup(),this.config.debug)}isPaymentOpen(){return this.isOpen}updateConfig(e){this.config={...this.config,...e},this.config.debug}getConfig(){return{...this.config}}getCurrentPayment(){return this.currentPayment?{...this.currentPayment}:null}_validatePaymentConfig(e){if(!e)throw new Error("Payment configuration is required");if(!e.amount||"number"!=typeof e.amount||e.amount<=0)throw new Error("Valid amount (number > 0) is required");if(!e.customerEmail||"string"!=typeof e.customerEmail)throw new Error("Customer email is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customerEmail))throw new Error("Invalid email format");if(e.merchantWalletAddresses){if("object"!=typeof e.merchantWalletAddresses)throw new Error("merchantWalletAddresses must be an object");Object.keys(e.merchantWalletAddresses).length}}_createContainer(){this.container||(this.container=document.createElement("div"),this.container.id="coinley-payment-container",this.container.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n ",document.body.appendChild(this.container))}_getDefaultCallbackUrl(){return"undefined"!=typeof window?`${window.location.origin}/api/webhooks/coinley`:""}_handleSuccess(e,t,r){this.config.debug,this.callbacks.onSuccess&&this.callbacks.onSuccess(e,t,r)}_handleError(e){this.config.debug,this.callbacks.onError&&this.callbacks.onError(e)}_handleClose(){this._cleanup(),this.callbacks.onClose&&this.callbacks.onClose()}_cleanup(){if(this.isOpen=!1,this.root){try{this.root.unmount()}catch(ud){}this.root=null}this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null),this.currentPayment=null}}function dA(){document.querySelectorAll('script[src*="coinley-vanilla"]').forEach(e=>{const t=e.getAttribute("data-public-key"),r=e.getAttribute("data-api-key"),n=e.getAttribute("data-api-secret"),i=e.getAttribute("data-api-url"),o=e.getAttribute("data-theme")||"light",s=e.hasAttribute("data-debug");if((t||r&&n)&&i)try{window.coinley=new uA({publicKey:t,apiKey:r,apiSecret:n,apiUrl:i,theme:o,debug:s})}catch(ud){}})}"undefined"!=typeof window&&(window.CoinleyVanilla=uA,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",dA):dA());class hA{constructor(e="https://payment.coinley.io/"){this.basePaymentUrl=e.endsWith("/")?e:e+"/"}generatePaymentURL(e){const{merchant:t,amount:r,productAmount:n,platformFee:i,networkFee:o,token:s="USDC",network:a="Ethereum Mainnet",merchantAddress:c}=e;if(!t)throw new Error("Merchant name is required");if(!r)throw new Error("Amount is required");if(!c)throw new Error("Merchant address (smart contract) is required");const l=n||.95*r,u=i||.03*r,d=o||.02*r,h=new URLSearchParams({merchant:t,amount:r.toString(),productAmount:l.toString(),platformFee:u.toString(),networkFee:d.toString(),token:s,network:a,merchantAddress:c});return this.basePaymentUrl+"?"+h.toString()}async generateQRCode(e,t={}){const{width:r=300,margin:n=2,colorDark:i="#7c3aed",colorLight:o="#ffffff"}=t;try{const t=this.generatePaymentURL(e);return{qrCodeDataURL:await u.toDataURL(t,{width:r,margin:n,color:{dark:i,light:o}}),paymentURL:t,paymentData:{...e,qrCodeUrl:t}}}catch(ud){throw new Error(`Failed to generate QR code: ${ud.message}`)}}async generateQRCodeToCanvas(e,t,r={}){const{width:n=300,margin:i=2,colorDark:o="#7c3aed",colorLight:s="#ffffff"}=r;try{const r=this.generatePaymentURL(e);return await u.toCanvas(t,r,{width:n,margin:i,color:{dark:o,light:s}}),r}catch(ud){throw new Error(`Failed to generate QR code to canvas: ${ud.message}`)}}validatePaymentData(e){const t=[],r=[];e.merchant||t.push("Merchant name is required"),(!e.amount||e.amount<=0)&&t.push("Valid amount is required"),e.merchantAddress||t.push("Merchant address (smart contract) is required"),e.merchantAddress&&!/^0x[a-fA-F0-9]{40}$/.test(e.merchantAddress)&&t.push("Invalid Ethereum address format for merchantAddress"),e.amount>1e4&&r.push("Large payment amount detected");return(e.platformFee||0)+(e.networkFee||0)>.1*e.amount&&r.push("High fees detected (>10% of total amount)"),{isValid:0===t.length,errors:t,warnings:r}}async createPaymentQR(e){const{merchantName:t,amount:r,productAmount:n,platformFee:i,networkFee:o,token:s,network:a,merchantWalletAddresses:c,selectedNetwork:l="ethereum",...u}=e,d={merchant:t||"Coinley Merchant",amount:r,productAmount:n,platformFee:i,networkFee:o,token:s||"USDC",network:a||"Ethereum Mainnet",merchantAddress:(null==c?void 0:c[l])||(null==c?void 0:c.ethereum)||(null==c?void 0:c.splitPaymentContract),...u},h=this.validatePaymentData(d);if(!h.isValid)throw new Error(`Payment validation failed: ${h.errors.join(", ")}`);return{...await this.generateQRCode(d),validation:h,instructions:{userAction:"Scan this QR code with your mobile wallet to pay",expectedFlow:"QR Scan → Payment Screen → Wallet Connect → Split Payment → Confirmation",supportedWallets:["MetaMask","Trust Wallet","Coinbase Wallet","WalletConnect compatible wallets"]}}}}const pA=new hA;"undefined"!=typeof window&&(window.Buffer=N),"undefined"!=typeof globalThis&&(globalThis.Buffer=N);const fA={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,r=4)=>e?e.length<=t+r?e:`${e.slice(0,t)}...${e.slice(-r)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class mA extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const gA={react:"\nimport { CoinleyProvider, CoinleyCheckout } from 'coinley-test';\n\n// New recommended way - using publicKey only\n<CoinleyProvider\n publicKey=\"pk_your-public-key\"\n apiUrl=\"https://api.coinley.io\"\n>\n <CoinleyCheckout\n ref={checkoutRef}\n onSuccess={({ paymentId, transactionHash, senderAddress, network, currency, paymentDetails }) => {\n console.log('Payment successful!');\n console.log('Payment ID:', paymentId);\n console.log('Transaction Hash:', transactionHash);\n console.log('Sender Address:', senderAddress); // Wallet address that made the payment\n console.log('Network:', network); // e.g., 'ethereum', 'bsc', 'polygon'\n console.log('Currency:', currency); // e.g., 'USDT', 'USDC'\n console.log('Full Details:', paymentDetails);\n }}\n onError={(error) => console.error('Error:', error)}\n onClose={() => console.log('Closed')}\n />\n</CoinleyProvider>\n\n// Legacy way (still supported) - using apiKey + apiSecret\n<CoinleyProvider\n apiKey=\"your-api-key\"\n apiSecret=\"your-api-secret\"\n apiUrl=\"https://api.coinley.io\"\n>\n ...\n</CoinleyProvider>\n ",vanilla:'\n\x3c!-- Include via CDN --\x3e\n<script src="https://unpkg.com/coinley-test@latest/vanilla"><\/script>\n<link rel="stylesheet" href="https://unpkg.com/coinley-test@latest/vanilla/style.css">\n\n<script>\n// New recommended way - using publicKey only\nconst coinley = new CoinleyVanilla({\n publicKey: "pk_your-public-key",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Legacy way (still supported)\nconst coinleyLegacy = new CoinleyVanilla({\n apiKey: "your-api-key",\n apiSecret: "your-api-secret",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Use in checkout\ncoinley.open({\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n}, {\n onSuccess: ({ paymentId, transactionHash, senderAddress, network, currency, paymentDetails }) => {\n console.log(\'Payment successful!\');\n console.log(\'Sender Address:\', senderAddress); // Wallet that made the payment\n console.log(\'Network:\', network); // e.g., \'ethereum\', \'bsc\'\n console.log(\'Currency:\', currency); // e.g., \'USDT\', \'USDC\'\n },\n onError: (error) => console.error(\'Error:\', error),\n onClose: () => console.log(\'Closed\')\n});\n<\/script>\n '};e.CoinleyCheckout=QE,e.CoinleyError=mA,e.CoinleyProvider=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,theme:s="light",debug:a=!1,children:c})=>{const[l,u]=r.useState(!1),[d,h]=r.useState(null),[p,f]=r.useState({}),[m,g]=r.useState(""),y=()=>{u(!1),h(null),p.onClose&&p.onClose()},v={openPayment:(e,t)=>{h(e),t&&f(t),u(!0)},closePayment:y};return t.jsxs(XE.Provider,{value:v,children:[c,l&&d&&t.jsx(JE,{publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,isOpen:l,config:d,theme:s,debug:a,merchantName:m,onSuccess:p.onSuccess,onError:p.onError,onClose:y})]})},e.CoinleyVanilla=uA,e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=JE,e.PaymentAPI=class{constructor(e,t,r=null){t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=r),this.api=d.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{if(this.publicKey)e.headers["x-public-key"]=this.publicKey;else{e.headers["x-api-key"]=this.apiKey,e.headers["x-api-secret"]=this.apiSecret;const t=this.generateMerchantToken();t&&(e.headers.Authorization=`Bearer ${t}`)}return e},e=>Promise.reject(e)),this.api.interceptors.response.use(e=>e,e=>{var t,r,n;if(401===(null==(t=e.response)?void 0:t.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(r=e.response)?void 0:r.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(n=e.response)?void 0:n.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(ud){return null}}async request(e,t={}){var r,n;try{return(await this.api({url:e,method:t.method||"GET",data:t.data||t.body?JSON.parse(t.body||"{}"):void 0,...t})).data}catch(ud){if(null==(n=null==(r=ud.response)?void 0:r.data)?void 0:n.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Request failed")}}async createPayment(e){var t,r;try{return(await this.api.post("/api/payments/create",e)).data}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to create payment")}}async getPayment(e){var t,r;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(ud){return{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:1,type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:56,type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:137,type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(ud){return{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,r;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to verify payment")}}async processPayment(e,t,r,n){var i;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:r,senderAddress:n})).data}catch(ud){if(null==(i=ud.response)?void 0:i.data){const t=ud.response.data,r=t.error||t.message||"Payment processing failed",n=new Error(r);throw n.isAlreadyCompleted=t.isAlreadyCompleted||!1,n.verificationAttempts=t.verificationAttempts||0,n.statusCode=ud.response.status,n.originalData=t,n}throw new Error(ud.message||"Failed to process PaymentSplitter transaction")}}async getContractInfo(e){var t,r;try{return(await this.api.get(`/api/payments/contract/${e}`)).data.contractInfo}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to get contract information")}}async getPaymentSplitterStatus(e){var t,r;try{return(await this.api.get(`/api/payments/splitter-status/${e}`)).data.paymentSplitterStatus}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to get PaymentSplitter status")}}async checkPaymentSplitterHealth(){try{return(await this.api.get("/api/payments/health")).data.paymentSplitterHealth}catch(ud){return{error:ud.message}}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(ud){return!1}}},e.PaymentQRGenerator=hA,e.QRCodePayment=({apiKey:e,apiSecret:n,apiUrl:i,config:o,onSuccess:s,onError:a,onClose:c,isOpen:l,theme:d="light",mode:h="splitpayment",splitPaymentUrl:p="https://payment.coinley.io/"})=>{var f;const[m,g]=r.useState("network"),[y,v]=r.useState([]),[b,w]=r.useState([]),[x,k]=r.useState(null),[_,S]=r.useState(null),[C,I]=r.useState(null),[E,A]=r.useState(!1),[N,M]=r.useState(""),[P,T]=r.useState(""),[O,B]=r.useState(""),[R,j]=r.useState(""),[L,D]=r.useState(!1),[U,F]=r.useState(""),[z,q]=r.useState(!1),[$,W]=r.useState(null),H=r.useRef(new cA(i,e,n)),G=r.useRef(null);r.useEffect(()=>(l&&(K(),V()),()=>{G.current&&clearInterval(G.current)}),[l]);const V=()=>{g("network"),k(null),S(null),I(null),M(""),T(""),B(""),j(""),D(!1),F(""),q(!1),W(null),G.current&&clearInterval(G.current)},K=async()=>{try{A(!0),M("");const[e,t]=await Promise.all([H.current.getNetworks(),H.current.getTokens()]);v(e.networks||[]),w(t.stablecoins||[])}catch(yA){M("Failed to load payment options.")}finally{A(!1)}},Z=async e=>{if(!_||!x||!C)return!1;try{const t=await aA.validateBalance(e,_,C.totalAmount,x.shortName,!0);return W(t),!!t.isValid||(M(`Insufficient balance: ${t.errors.join(", ")}`),!1)}catch(t){return M(`Failed to check balance: ${t.message}`),!1}};if(!l)return null;const Y="dark"===d;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(Y?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[t.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(Y?"border-gray-700":"border-gray-200"),children:[t.jsxs("div",{className:"text-center flex-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:"splitpayment"===h?"Split Payment QR":"QR Code Payment"}),o.amount&&t.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",o.amount.toFixed(2)]}),t.jsx("p",{className:"text-xs text-blue-600",children:"splitpayment"===h?"📱 Scan to redirect to payment screen":"📱 Scan with mobile wallet"})]}),t.jsx("button",{onClick:c,className:"ml-4 text-gray-500 hover:text-gray-700 "+(Y?"hover:text-gray-300":""),children:"✕"})]}),t.jsxs("div",{className:"p-4 min-h-[400px]",children:[N&&t.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[N,t.jsx("button",{onClick:()=>M(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"network"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsx("h3",{className:"font-medium text-center",children:"Select Network"}),t.jsx("div",{className:"space-y-2",children:y.map(e=>{var r;const n=null==(r=o.merchantWalletAddresses)?void 0:r[e.shortName];return t.jsxs("button",{onClick:()=>{k(e),g("token")},disabled:!n,className:"w-full p-3 border rounded-lg text-left transition-colors "+(n?"hover:border-purple-500 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"):"opacity-50 cursor-not-allowed "+(Y?"border-gray-700":"border-gray-100")),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsxs("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:[e.shortName.toUpperCase(),!n&&" (No merchant address configured)"]})]},e.id)})})]}),"token"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("button",{onClick:()=>g("network"),className:""+(Y?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),t.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==x?void 0:x.name]})]}),t.jsx("div",{className:"space-y-2",children:b.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==x?void 0:x.shortName)}).map(e=>t.jsxs("button",{onClick:()=>{S(e),(async e=>{var t,r;try{A(!0),M("");const n={amount:o.amount,currency:e.symbol,network:x.shortName,customerEmail:o.customerEmail,callbackUrl:o.callbackUrl,metadata:{...o.metadata,merchantWalletAddresses:o.merchantWalletAddresses,paymentMethod:"split_payment_qr",selectedNetwork:x.shortName,selectedToken:e.symbol}},i=await H.current.createPayment(n);I(i.payment);const s=(null==(t=o.merchantWalletAddresses)?void 0:t.splitPaymentContract)||(null==(r=o.merchantWalletAddresses)?void 0:r[x.shortName]);if(!s)throw new Error("Split payment contract address not found in config");const a=new URLSearchParams({merchant:o.merchantName||"Coinley Merchant",amount:i.payment.totalAmount.toString(),productAmount:(.95*i.payment.totalAmount).toFixed(2),platformFee:(.03*i.payment.totalAmount).toFixed(2),networkFee:(.02*i.payment.totalAmount).toFixed(2),token:e.symbol,network:x.name,merchantAddress:s,paymentId:i.payment.id}),c=p+"?"+a.toString();T(c);const l=await u.toDataURL(c,{width:256,margin:2,color:{dark:"#7c3aed",light:"#ffffff"}});B(l),g("scan")}catch(n){M(n.message||"Failed to generate split payment QR code")}finally{A(!1)}})(e)},disabled:E,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsx("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:e.symbol})]},e.id))})]}),"scan"===m&&t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("h3",{className:"font-medium mb-4",children:"splitpayment"===h?"Scan QR Code to Open Payment Screen":"Scan QR Code with Mobile Wallet"}),O?t.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[t.jsx("div",{className:"p-4 rounded-lg "+(Y?"bg-gray-800":"bg-gray-50"),children:t.jsx("img",{src:O,alt:"Payment QR Code",className:"mx-auto",style:{width:"200px",height:"200px"}})}),t.jsxs("div",{className:"text-sm space-y-1 "+(Y?"text-gray-300":"text-gray-600"),children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Amount:"}),t.jsxs("span",{className:"font-medium",children:[null==C?void 0:C.totalAmount," ",null==_?void 0:_.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Network:"}),t.jsx("span",{className:"font-medium",children:null==x?void 0:x.name})]}),"splitpayment"===h&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Merchant:"}),t.jsx("span",{className:"font-medium",children:o.merchantName||"Coinley Merchant"})]})]}),t.jsx("div",{className:"p-3 rounded-lg text-xs "+(Y?"bg-blue-900 text-blue-200":"bg-blue-50 text-blue-600"),children:"splitpayment"===h?t.jsxs(t.Fragment,{children:["📱 Scan this QR code with your mobile wallet to open the payment screen.",t.jsx("br",{}),"The payment screen will auto-connect your wallet and execute the split payment."]}):"📱 Open your mobile wallet and scan this QR code to connect and pay"}),"splitpayment"===h?t.jsx("button",{onClick:()=>window.open(P,"_blank"),className:"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm",children:"🔗 Test Payment Screen (Opens in new tab)"}):t.jsx("button",{onClick:async()=>{try{A(!0),M("");const e="0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4";F(e),D(!0),await Z(e),g("confirm")}catch(e){M("Failed to simulate wallet connection")}finally{A(!1)}},disabled:E,className:"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm",children:E?"Connecting...":"🧪 Simulate Wallet Scan (Test)"})]}):t.jsxs("div",{className:"flex items-center justify-center py-8",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"}),t.jsx("span",{className:"ml-2",children:"Generating QR Code..."})]})]})}),"confirm"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:t.jsx("span",{className:"text-2xl",children:"📱"})}),t.jsx("h3",{className:"font-medium",children:"Mobile Wallet Connected"}),t.jsx("p",{className:"text-sm mt-2 "+(Y?"text-gray-300":"text-gray-600"),children:"Ready to complete payment"})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[t.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),t.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==U?void 0:U.slice(0,6),"...",null==U?void 0:U.slice(-4)]})]}),$&&t.jsx("div",{className:"p-3 rounded-lg border "+($.isValid?"bg-green-50 border-green-200":"bg-red-50 border-red-200"),children:t.jsxs("div",{className:"space-y-2 text-sm",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Required:"}),t.jsxs("span",{className:"font-medium",children:[null==C?void 0:C.totalAmount," ",null==_?void 0:_.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Your Balance:"}),t.jsx("span",{className:"font-medium "+($.hasEnoughTokens?"text-green-600":"text-red-600"),children:aA.formatBalance(null==(f=$.tokenBalance)?void 0:f.balance,null==_?void 0:_.symbol)})]}),$.nativeBalance&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Gas Balance:"}),t.jsx("span",{className:"font-medium "+($.hasEnoughForGas?"text-green-600":"text-red-600"),children:aA.formatBalance($.nativeBalance.balance,$.nativeBalance.symbol)})]})]})}),t.jsx("button",{onClick:async()=>{try{q(!0),M("");const e=`0x${Math.random().toString(16).substring(2,66)}`;await new Promise(e=>setTimeout(e,3e3)),g("success"),null==s||s(C.id,e,{network:x.name,token:_.symbol,amount:C.totalAmount,method:"qr_code",walletAddress:U})}catch(e){M("Transaction confirmation failed")}finally{q(!1)}},disabled:z||!(null==$?void 0:$.isValid),className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium",children:z?"Processing Payment...":(null==$?void 0:$.isValid)?`Confirm Payment of ${null==C?void 0:C.totalAmount} ${null==_?void 0:_.symbol}`:"Insufficient Balance"})]})]}),"success"===m&&t.jsxs("div",{className:"text-center space-y-4",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:t.jsx("span",{className:"text-2xl",children:"✅"})}),t.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),t.jsx("p",{className:"text-sm "+(Y?"text-gray-300":"text-gray-600"),children:"Transaction completed via QR code scan"}),t.jsx("button",{onClick:c,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium",children:"Close"})]}),E&&"scan"!==m&&"confirm"!==m&&t.jsx("div",{className:"flex items-center justify-center py-8",children:t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.RedesignedCoinleyPayment=e=>t.jsx(n.WagmiProvider,{config:im,children:t.jsx(i.QueryClientProvider,{client:eA,children:t.jsx(iA,{...e})})}),e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:n})=>{const[i,o]=r.useState(e);return r.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",i)},[i]),t.jsx("div",{className:`coinley-theme-${i}`,children:n})},e.USAGE_EXAMPLES=gA,e.VERSION="0.0.27",e.generatePaymentQR=(e,t)=>pA.generateQRCode(e,t),e.generatePaymentURL=e=>pA.generatePaymentURL(e),e.paymentQR=pA,e.sdkAnalytics=em,e.useCoinley=()=>{const e=r.useContext(XE);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=fA,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
22
+ const q_={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},$_={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},W_=BigInt(2);const H_=Db(q_.p,{sqrt:function(e){const t=q_.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Eb(u,r,t)*u%t,h=Eb(d,r,t)*u%t,p=Eb(h,W_,t)*l%t,f=Eb(p,i,t)*p%t,m=Eb(f,o,t)*f%t,g=Eb(m,a,t)*m%t,y=Eb(g,c,t)*g%t,v=Eb(y,a,t)*m%t,b=Eb(v,r,t)*u%t,w=Eb(b,s,t)*f%t,x=Eb(w,n,t)*l%t,k=Eb(x,W_,t);if(!H_.eql(H_.sqr(k),e))throw new Error("Cannot find square root");return k}}),G_=function(e,t){const r=t=>z_({...e,hash:t});return{...r(t),create:r}}({...q_,Fp:H_,lowS:!0,endo:$_},Ny);function V_(e){try{return bw.ExtendedPoint.fromHex(e),!0}catch{return!1}}bw.utils.randomPrivateKey,bw.getPublicKey;const K_=bw.verify,Z_=e=>N.isBuffer(e)?e:e instanceof Uint8Array?N.from(e.buffer,e.byteOffset,e.byteLength):N.from(e);class Y_{constructor(e){Object.assign(this,e)}encode(){return N.from(cx(J_,this))}static decode(e){return dx(J_,this,e)}static decodeUnchecked(e){return Zw(J_,this,e)}}const J_=new Map;var X_;const Q_=32;let eS=1;class tS extends Y_{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=Pw.decode(e);if(t.length!=Q_)throw new Error("Invalid public key input");this._bn=new Iw(t)}else this._bn=new Iw(e);if(this._bn.byteLength()>Q_)throw new Error("Invalid public key input")}}static unique(){const e=new tS(eS);return eS+=1,new tS(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Pw.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(N);if(e.length===Q_)return e;const t=N.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,r){const n=N.concat([e.toBuffer(),N.from(t),r.toBuffer()]),i=Py(n);return new tS(i)}static createProgramAddressSync(e,t){let r=N.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");r=N.concat([r,Z_(e)])}),r=N.concat([r,t.toBuffer(),N.from("ProgramDerivedAddress")]);const n=Py(r);if(V_(n))throw new Error("Invalid seeds, address must fall off the curve");return new tS(n)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let r,n=255;for(;0!=n;){try{const i=e.concat(N.from([n]));r=this.createProgramAddressSync(i,t)}catch(yA){if(yA instanceof TypeError)throw yA;n--;continue}return[r,n]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return V_(new tS(e).toBytes())}}X_=tS,tS.default=new X_("11111111111111111111111111111111"),J_.set(tS,{kind:"struct",fields:[["_bn","u256"]]}),new tS("BPFLoader1111111111111111111111111111111111");const rS=1232;class nS extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(nS.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class iS extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(iS.prototype,"name",{value:"TransactionExpiredTimeoutError"});class oS extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(oS.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class sS{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,r)=>{t.set(e.toBase58(),r)});const r=e=>{const r=t.get(e.toBase58());if(void 0===r)throw new Error("Encountered an unknown instruction account key during compilation");return r};return e.map(e=>({programIdIndex:r(e.programId),accountKeyIndexes:e.keys.map(e=>r(e.pubkey)),data:e.data}))}}const aS=(e="publicKey")=>ik(32,e),cS=(e="string")=>{const t=rk([Qx("length"),Qx("lengthPadding"),ik(Yx(Qx(),-8),"chars")],e),r=t.decode.bind(t),n=t.encode.bind(t),i=t;return i.decode=(e,t)=>r(e,t).chars.toString(),i.encode=(e,t,r)=>{const i={chars:N.from(e,"utf8")};return n(i,t,r)},i.alloc=e=>Qx().span+Qx().span+N.from(e,"utf8").length,i};function lS(e,t){const r=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const n=t[e.property];if(Array.isArray(n))return n.length*r(e.elementLayout)}else if("fields"in e)return lS({layout:e},t[e.property]);return 0};let n=0;return e.layout.fields.forEach(e=>{n+=r(e)}),n}function uS(e){let t=0,r=0;for(;;){let n=e.shift();if(t|=(127&n)<<7*r,r+=1,!(128&n))break}return t}function dS(e,t){let r=t;for(;;){let t=127&r;if(r>>=7,0==r){e.push(t);break}t|=128,e.push(t)}}function hS(e,t){if(!e)throw new Error(t||"Assertion failed")}class pS{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const r=new Map,n=e=>{const t=e.toBase58();let n=r.get(t);return void 0===n&&(n={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(t,n)),n},i=n(t);i.isSigner=!0,i.isWritable=!0;for(const o of e){n(o.programId).isInvoked=!0;for(const e of o.keys){const t=n(e.pubkey);t.isSigner||(t.isSigner=e.isSigner),t.isWritable||(t.isWritable=e.isWritable)}}return new pS(t,r)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];hS(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),r=e.filter(([,e])=>e.isSigner&&!e.isWritable),n=e.filter(([,e])=>!e.isSigner&&e.isWritable),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),o={numRequiredSignatures:t.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:i.length};{hS(t.length>0,"Expected at least one writable signer key");const[e]=t[0];hS(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new tS(e)),...r.map(([e])=>new tS(e)),...n.map(([e])=>new tS(e)),...i.map(([e])=>new tS(e))]]}extractTableLookup(e){const[t,r]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[n,i]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==n.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:n},{writable:r,readonly:i}]}drainKeysFoundInLookupTable(e,t){const r=new Array,n=new Array;for(const[i,o]of this.keyMetaMap.entries())if(t(o)){const t=new tS(i),o=e.findIndex(e=>e.equals(t));o>=0&&(hS(o<256,"Max lookup table index exceeded"),r.push(o),n.push(t),this.keyMetaMap.delete(i))}return[r,n]}}const fS="Reached end of buffer unexpectedly";function mS(e){if(0===e.length)throw new Error(fS);return e.shift()}function gS(e,...t){const[r]=t;if(2===t.length?r+(t[1]??0)>e.length:r>=e.length)throw new Error(fS);return e.splice(...t)}class yS{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new tS(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Pw.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new sS(this.staticAccountKeys)}static compile(e){const t=pS.compile(e.instructions,e.payerKey),[r,n]=t.getMessageComponents(),i=new sS(n).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Pw.encode(e.data)}));return new yS({header:r,accountKeys:n,recentBlockhash:e.recentBlockhash,instructions:i})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];dS(t,e);const r=this.instructions.map(e=>{const{accounts:t,programIdIndex:r}=e,n=Array.from(Pw.decode(e.data));let i=[];dS(i,t.length);let o=[];return dS(o,n.length),{programIdIndex:r,keyIndicesCount:N.from(i),keyIndices:t,dataLength:N.from(o),data:n}});let n=[];dS(n,r.length);let i=N.alloc(rS);N.from(n).copy(i);let o=n.length;r.forEach(e=>{const t=rk([Jx("programIdIndex"),ik(e.keyIndicesCount.length,"keyIndicesCount"),nk(Jx("keyIndex"),e.keyIndices.length,"keyIndices"),ik(e.dataLength.length,"dataLength"),nk(Jx("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=rk([ik(1,"numRequiredSignatures"),ik(1,"numReadonlySignedAccounts"),ik(1,"numReadonlyUnsignedAccounts"),ik(t.length,"keyCount"),nk(aS("key"),e,"keys"),aS("recentBlockhash")]),a={numRequiredSignatures:N.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:N.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:N.from([this.header.numReadonlyUnsignedAccounts]),keyCount:N.from(t),keys:this.accountKeys.map(e=>Z_(e.toBytes())),recentBlockhash:Pw.decode(this.recentBlockhash)};let c=N.alloc(2048);const l=s.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const r=mS(t);if(r!==(127&r))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const n=mS(t),i=mS(t),o=uS(t);let s=[];for(let d=0;d<o;d++){const e=gS(t,0,Q_);s.push(new tS(N.from(e)))}const a=gS(t,0,Q_),c=uS(t);let l=[];for(let d=0;d<c;d++){const e=mS(t),r=gS(t,0,uS(t)),n=gS(t,0,uS(t)),i=Pw.encode(N.from(n));l.push({programIdIndex:e,accounts:r,data:i})}const u={header:{numRequiredSignatures:r,numReadonlySignedAccounts:n,numReadonlyUnsignedAccounts:i},recentBlockhash:Pw.encode(N.from(a)),accountKeys:s,instructions:l};return new yS(u)}}class vS{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new sS(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,r=this.staticAccountKeys.length;if(e>=r){return e-r<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<r-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const r of this.addressTableLookups){const n=e.find(e=>e.key.equals(r.accountKey));if(!n)throw new Error(`Failed to find address lookup table account for table key ${r.accountKey.toBase58()}`);for(const e of r.writableIndexes){if(!(e<n.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${r.accountKey.toBase58()}`);t.writable.push(n.state.addresses[e])}for(const e of r.readonlyIndexes){if(!(e<n.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${r.accountKey.toBase58()}`);t.readonly.push(n.state.addresses[e])}}return t}static compile(e){const t=pS.compile(e.instructions,e.payerKey),r=new Array,n={writable:new Array,readonly:new Array},i=e.addressLookupTableAccounts||[];for(const c of i){const e=t.extractTableLookup(c);if(void 0!==e){const[t,{writable:i,readonly:o}]=e;r.push(t),n.writable.push(...i),n.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new sS(s,n).compileInstructions(e.instructions);return new vS({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:r})}serialize(){const e=Array();dS(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),r=Array();dS(r,this.compiledInstructions.length);const n=this.serializeAddressTableLookups(),i=Array();dS(i,this.addressTableLookups.length);const o=rk([Jx("prefix"),rk([Jx("numRequiredSignatures"),Jx("numReadonlySignedAccounts"),Jx("numReadonlyUnsignedAccounts")],"header"),ik(e.length,"staticAccountKeysLength"),nk(aS(),this.staticAccountKeys.length,"staticAccountKeys"),aS("recentBlockhash"),ik(r.length,"instructionsLength"),ik(t.length,"serializedInstructions"),ik(i.length,"addressTableLookupsLength"),ik(n.length,"serializedAddressTableLookups")]),s=new Uint8Array(rS),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Pw.decode(this.recentBlockhash),instructionsLength:new Uint8Array(r),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:n},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(rS);for(const r of this.compiledInstructions){const n=Array();dS(n,r.accountKeyIndexes.length);const i=Array();dS(i,r.data.length);e+=rk([Jx("programIdIndex"),ik(n.length,"encodedAccountKeyIndexesLength"),nk(Jx(),r.accountKeyIndexes.length,"accountKeyIndexes"),ik(i.length,"encodedDataLength"),ik(r.data.length,"data")]).encode({programIdIndex:r.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(n),accountKeyIndexes:r.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:r.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(rS);for(const r of this.addressTableLookups){const n=Array();dS(n,r.writableIndexes.length);const i=Array();dS(i,r.readonlyIndexes.length);e+=rk([aS("accountKey"),ik(n.length,"encodedWritableIndexesLength"),nk(Jx(),r.writableIndexes.length,"writableIndexes"),ik(i.length,"encodedReadonlyIndexesLength"),nk(Jx(),r.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:r.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(n),writableIndexes:r.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:r.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const r=mS(t),n=127&r;hS(r!==n,"Expected versioned message but received legacy message");hS(0===n,`Expected versioned message with version 0 but found version ${n}`);const i={numRequiredSignatures:mS(t),numReadonlySignedAccounts:mS(t),numReadonlyUnsignedAccounts:mS(t)},o=[],s=uS(t);for(let h=0;h<s;h++)o.push(new tS(gS(t,0,Q_)));const a=Pw.encode(gS(t,0,Q_)),c=uS(t),l=[];for(let h=0;h<c;h++){const e=mS(t),r=gS(t,0,uS(t)),n=uS(t),i=new Uint8Array(gS(t,0,n));l.push({programIdIndex:e,accountKeyIndexes:r,data:i})}const u=uS(t),d=[];for(let h=0;h<u;h++){const e=new tS(gS(t,0,Q_)),r=gS(t,0,uS(t)),n=gS(t,0,uS(t));d.push({accountKey:e,writableIndexes:r,readonlyIndexes:n})}return new vS({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}let bS=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const wS=N.alloc(64).fill(0);class xS{constructor(e){this.keys=void 0,this.programId=void 0,this.data=N.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:r})=>({pubkey:e.toJSON(),isSigner:t,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class kS{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:r}=e;this.minNonceContextSlot=t,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:r}=e;this.recentBlockhash=t,this.lastValidBlockHeight=r}else{const{recentBlockhash:t,nonceInfo:r}=e;r&&(this.nonceInfo=r),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new xS(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,r;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length<1&&console.warn("No instructions provided"),this.feePayer)r=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");r=this.signatures[0].publicKey}for(let f=0;f<t.length;f++)if(void 0===t[f].programId)throw new Error(`Transaction instruction index ${f} has undefined program id`);const n=[],i=[];t.forEach(e=>{e.keys.forEach(e=>{i.push({...e})});const t=e.programId.toString();n.includes(t)||n.push(t)}),n.forEach(e=>{i.push({pubkey:new tS(e),isSigner:!1,isWritable:!1})});const o=[];i.forEach(e=>{const t=e.pubkey.toString(),r=o.findIndex(e=>e.pubkey.toString()===t);r>-1?(o[r].isWritable=o[r].isWritable||e.isWritable,o[r].isSigner=o[r].isSigner||e.isSigner):o.push(e)}),o.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=o.findIndex(e=>e.pubkey.equals(r));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const f of this.signatures){const e=o.findIndex(e=>e.pubkey.equals(f.publicKey));if(!(e>-1))throw new Error(`unknown signer: ${f.publicKey.toString()}`);o[e].isSigner||(o[e].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."))}let a=0,c=0,l=0;const u=[],d=[];o.forEach(({pubkey:e,isSigner:t,isWritable:r})=>{t?(u.push(e.toString()),a+=1,r||(c+=1)):(d.push(e.toString()),r||(l+=1))});const h=u.concat(d),p=t.map(e=>{const{data:t,programId:r}=e;return{programIdIndex:h.indexOf(r.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:Pw.encode(t)}});return p.forEach(e=>{hS(e.programIdIndex>=0),e.accounts.forEach(e=>hS(e>=0))}),new yS({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:l},accountKeys:h,recentBlockhash:e,instructions:p})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,r)=>t[r].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const r=e.toString();return!t.has(r)&&(t.add(r),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,r=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),r.push(i))}this.signatures=r.map(e=>({signature:null,publicKey:e.publicKey}));const n=this._compile();this._partialSign(n,...r)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,r=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),r.push(i))}const n=this._compile();this._partialSign(n,...r)}_partialSign(e,...t){const r=e.serialize();t.forEach(e=>{const t=((e,t)=>bw.sign(e,t.slice(0,32)))(r,e.secretKey);this._addSignature(e.publicKey,Z_(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){hS(64===t.length);const r=this.signatures.findIndex(t=>e.equals(t.publicKey));if(r<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[r].signature=N.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const r={};for(const{signature:n,publicKey:i}of this.signatures)null===n?t&&(r.missing||(r.missing=[])).push(i):K_(n,e,i.toBytes())||(r.invalid||(r.invalid=[])).push(i);return r.invalid||r.missing?r:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),n=this.serializeMessage();if(r){const e=this._getMessageSignednessErrors(n,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(n)}_serialize(e){const{signatures:t}=this,r=[];dS(r,t.length);const n=r.length+64*t.length+e.length,i=N.alloc(n);return hS(t.length<256),N.from(r).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(hS(64===e.length,"signature has invalid length"),N.from(e).copy(i,r.length+64*t))}),e.copy(i,r.length+64*t.length),hS(i.length<=rS,`Transaction too large: ${i.length} > 1232`),i}get keys(){return hS(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return hS(1===this.instructions.length),this.instructions[0].programId}get data(){return hS(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const r=uS(t);let n=[];for(let i=0;i<r;i++){const e=gS(t,0,64);n.push(Pw.encode(N.from(e)))}return kS.populate(yS.from(t),n)}static populate(e,t=[]){const r=new kS;return r.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(r.feePayer=e.accountKeys[0]),t.forEach((t,n)=>{const i={signature:t==Pw.encode(wS)?null:Pw.decode(t),publicKey:e.accountKeys[n]};r.signatures.push(i)}),e.instructions.forEach(t=>{const n=t.accounts.map(t=>{const n=e.accountKeys[t];return{pubkey:n,isSigner:r.signatures.some(e=>e.publicKey.toString()===n.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});r.instructions.push(new xS({keys:n,programId:e.accountKeys[t.programIdIndex],data:Pw.decode(t.data)}))}),r._message=e,r._json=r.toJSON(),r}}new tS("SysvarC1ock11111111111111111111111111111111"),new tS("SysvarEpochSchedu1e111111111111111111111111"),new tS("Sysvar1nstructions1111111111111111111111111");const _S=new tS("SysvarRecentB1ockHashes11111111111111111111"),SS=new tS("SysvarRent111111111111111111111111111111111");new tS("SysvarRewards111111111111111111111111111111"),new tS("SysvarS1otHashes111111111111111111111111111"),new tS("SysvarS1otHistory11111111111111111111111111"),new tS("SysvarStakeHistory1111111111111111111111111");class CS extends Error{constructor({action:e,signature:t,transactionMessage:r,logs:n}){const i=n?`Logs: \n${JSON.stringify(n.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${r}. `+i+o;break;case"simulate":s=`Simulation failed. \nMessage: ${r}. \n`+i+o;break;default:s=`Unknown action '${(e=>e)(e)}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=r,this.transactionLogs=n||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,r)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const r=e.meta.logMessages;this.transactionLogs=r,t(r)}else r(new Error("Log messages not found"))}).catch(r)})),await this.transactionLogs}}class IS extends Error{constructor({code:e,message:t,data:r},n){super(null!=n?`${n}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=r,this.name="SolanaJSONRPCError"}}function ES(e){return new Promise(t=>setTimeout(t,e))}function AS(e,t){const r=e.layout.span>=0?e.layout.span:lS(e,t),n=N.alloc(r),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,n),n}const NS=ek("lamportsPerSignature"),MS=rk([Qx("version"),Qx("state"),aS("authorizedPubkey"),aS("nonce"),rk([NS],"feeCalculator")]),PS=MS.span;class TS{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=MS.decode(Z_(e),0);return new TS({authorizedPubkey:new tS(t.authorizedPubkey),nonce:new tS(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function OS(e){const t=ik(8,e),r=t.decode.bind(t),n=t.encode.bind(t),i=t,o=pk();return i.decode=(e,t)=>{const n=r(e,t);return o.decode(n)},i.encode=(e,t,r)=>{const i=o.encode(e);return n(i,t,r)},i}const BS=Object.freeze({Create:{index:0,layout:rk([Qx("instruction"),tk("lamports"),tk("space"),aS("programId")])},Assign:{index:1,layout:rk([Qx("instruction"),aS("programId")])},Transfer:{index:2,layout:rk([Qx("instruction"),OS("lamports")])},CreateWithSeed:{index:3,layout:rk([Qx("instruction"),aS("base"),cS("seed"),tk("lamports"),tk("space"),aS("programId")])},AdvanceNonceAccount:{index:4,layout:rk([Qx("instruction")])},WithdrawNonceAccount:{index:5,layout:rk([Qx("instruction"),tk("lamports")])},InitializeNonceAccount:{index:6,layout:rk([Qx("instruction"),aS("authorized")])},AuthorizeNonceAccount:{index:7,layout:rk([Qx("instruction"),aS("authorized")])},Allocate:{index:8,layout:rk([Qx("instruction"),tk("space")])},AllocateWithSeed:{index:9,layout:rk([Qx("instruction"),aS("base"),cS("seed"),tk("space"),aS("programId")])},AssignWithSeed:{index:10,layout:rk([Qx("instruction"),aS("base"),cS("seed"),aS("programId")])},TransferWithSeed:{index:11,layout:rk([Qx("instruction"),OS("lamports"),cS("seed"),aS("programId")])},UpgradeNonceAccount:{index:12,layout:rk([Qx("instruction")])}});class RS{constructor(){}static createAccount(e){const t=AS(BS.Create,{lamports:e.lamports,space:e.space,programId:Z_(e.programId.toBuffer())});return new xS({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,r;if("basePubkey"in e){t=AS(BS.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=AS(BS.Transfer,{lamports:BigInt(e.lamports)}),r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new xS({keys:r,programId:this.programId,data:t})}static assign(e){let t,r;if("basePubkey"in e){t=AS(BS.AssignWithSeed,{base:Z_(e.basePubkey.toBuffer()),seed:e.seed,programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=AS(BS.Assign,{programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new xS({keys:r,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=AS(BS.CreateWithSeed,{base:Z_(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Z_(e.programId.toBuffer())});let r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||r.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new xS({keys:r,programId:this.programId,data:t})}static createNonceAccount(e){const t=new kS;"basePubkey"in e&&"seed"in e?t.add(RS.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:PS,programId:this.programId})):t.add(RS.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:PS,programId:this.programId}));const r={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(r)),t}static nonceInitialize(e){const t=AS(BS.InitializeNonceAccount,{authorized:Z_(e.authorizedPubkey.toBuffer())}),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:_S,isSigner:!1,isWritable:!1},{pubkey:SS,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new xS(r)}static nonceAdvance(e){const t=AS(BS.AdvanceNonceAccount),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:_S,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new xS(r)}static nonceWithdraw(e){const t=AS(BS.WithdrawNonceAccount,{lamports:e.lamports});return new xS({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:_S,isSigner:!1,isWritable:!1},{pubkey:SS,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=AS(BS.AuthorizeNonceAccount,{authorized:Z_(e.newAuthorizedPubkey.toBuffer())});return new xS({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,r;if("basePubkey"in e){t=AS(BS.AllocateWithSeed,{base:Z_(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Z_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=AS(BS.Allocate,{space:e.space}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new xS({keys:r,programId:this.programId,data:t})}}function jS(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var LS,DS;function US(){if(DS)return LS;DS=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};function r(n,i){var o,s,a,c,l,u,d;if(!0===n)return"true";if(!1===n)return"false";switch(typeof n){case"object":if(null===n)return null;if(n.toJSON&&"function"==typeof n.toJSON)return r(n.toJSON(),i);if("[object Array]"===(d=e.call(n))){for(a="[",s=n.length-1,o=0;o<s;o++)a+=r(n[o],!0)+",";return s>-1&&(a+=r(n[o],!0)),a+"]"}if("[object Object]"===d){for(s=(c=t(n).sort()).length,a="",o=0;o<s;)void 0!==(u=r(n[l=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),o++;return"{"+a+"}"}return JSON.stringify(n);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(n);default:return isFinite(n)?n:null}}return LS=function(e){var t=r(e,!1);if(void 0!==t)return""+t}}RS.programId=new tS("11111111111111111111111111111111"),new tS("BPFLoader2111111111111111111111111111111111");var FS=jS(US());function zS(e){let t=0;for(;e>1;)e/=2,t++;return t}class qS{constructor(e,t,r,n,i){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=r,this.firstNormalEpoch=n,this.firstNormalSlot=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const r=zS(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-zS(32)-1;return[r,e-(this.getSlotsInEpoch(r)-32)]}{const t=e-this.firstNormalSlot,r=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+r,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+zS(32)):this.slotsPerEpoch}}var $S=globalThis.fetch;class WS extends __{constructor(e,t,r){super(e=>{const r=function(e,t){return new x_(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in r?r.socket:r,r},e,t,r),this.underlyingSocket=void 0}call(...e){var t;const r=null==(t=this.underlyingSocket)?void 0:t.readyState;return 1===r?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+r+")"))}notify(...e){var t;const r=null==(t=this.underlyingSocket)?void 0:t.readyState;return 1===r?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+r+")"))}}class HS{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let r;try{r=e.layout.decode(t)}catch(yA){throw new Error("invalid instruction; "+yA)}if(r.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${r.typeIndex} != ${e.index}`);return r}(GS,e),r=e.length-56;hS(r>=0,"lookup table is invalid"),hS(r%32==0,"lookup table is invalid");const n=r/32,{addresses:i}=rk([nk(aS(),n,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new tS(t.authority[0]):void 0,addresses:i.map(e=>new tS(e))}}}const GS={index:1,layout:rk([Qx("typeIndex"),OS("deactivationSlot"),ek("lastExtendedSlot"),Jx("lastExtendedStartIndex"),Jx(),nk(aS(),Yx(Jx(),-1),"authority")])},VS=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const KS=Uk(Ak(tS),Bk(),e=>new tS(e)),ZS=Rk([Bk(),Nk("base64")]),YS=Uk(Ak(N),ZS,e=>N.from(e[0],"base64"));function JS(e){let t,r;if("string"==typeof e)t=e;else if(e){const{commitment:n,...i}=e;t=n,r=i}return{commitment:t,config:r}}function XS(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function QS(e){return Lk([jk({jsonrpc:Nk("2.0"),id:Bk(),result:e}),jk({jsonrpc:Nk("2.0"),id:Bk(),error:jk({code:Dk(),message:Bk(),data:Tk(Ck("any",()=>!0))})})])}const eC=QS(Dk());function tC(e){return Uk(QS(e),eC,t=>"error"in t?t:{...t,result:kk(t.result,e)})}function rC(e){return tC(jk({context:jk({slot:Pk()}),value:e}))}function nC(e){return jk({context:jk({slot:Pk()}),value:e})}function iC(e,t){return 0===e?new vS({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new tS(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Pw.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new yS(t)}const oC=jk({foundation:Pk(),foundationTerm:Pk(),initial:Pk(),taper:Pk(),terminal:Pk()}),sC=tC(Ik(Mk(jk({epoch:Pk(),effectiveSlot:Pk(),amount:Pk(),postBalance:Pk(),commission:Tk(Mk(Pk()))})))),aC=Ik(jk({slot:Pk(),prioritizationFee:Pk()})),cC=jk({total:Pk(),validator:Pk(),foundation:Pk(),epoch:Pk()}),lC=jk({epoch:Pk(),slotIndex:Pk(),slotsInEpoch:Pk(),absoluteSlot:Pk(),blockHeight:Tk(Pk()),transactionCount:Tk(Pk())}),uC=jk({slotsPerEpoch:Pk(),leaderScheduleSlotOffset:Pk(),warmup:Ek(),firstNormalEpoch:Pk(),firstNormalSlot:Pk()}),dC=Ok(Bk(),Ik(Pk())),hC=Mk(Lk([jk({}),Bk()])),pC=jk({err:hC}),fC=Nk("receivedSignature"),mC=jk({"solana-core":Bk(),"feature-set":Tk(Pk())}),gC=jk({program:Bk(),programId:KS,parsed:Dk()}),yC=jk({programId:KS,accounts:Ik(KS),data:Bk()}),vC=rC(jk({err:Mk(Lk([jk({}),Bk()])),logs:Mk(Ik(Bk())),accounts:Tk(Mk(Ik(Mk(jk({executable:Ek(),owner:Bk(),lamports:Pk(),data:Ik(Bk()),rentEpoch:Tk(Pk())}))))),unitsConsumed:Tk(Pk()),returnData:Tk(Mk(jk({programId:Bk(),data:Rk([Bk(),Nk("base64")])}))),innerInstructions:Tk(Mk(Ik(jk({index:Pk(),instructions:Ik(Lk([gC,yC]))}))))})),bC=rC(jk({byIdentity:Ok(Bk(),Ik(Pk())),range:jk({firstSlot:Pk(),lastSlot:Pk()})}));const wC=tC(oC),xC=tC(cC),kC=tC(aC),_C=tC(lC),SC=tC(uC),CC=tC(dC),IC=tC(Pk()),EC=rC(jk({total:Pk(),circulating:Pk(),nonCirculating:Pk(),nonCirculatingAccounts:Ik(KS)})),AC=jk({amount:Bk(),uiAmount:Mk(Pk()),decimals:Pk(),uiAmountString:Tk(Bk())}),NC=rC(Ik(jk({address:KS,amount:Bk(),uiAmount:Mk(Pk()),decimals:Pk(),uiAmountString:Tk(Bk())}))),MC=rC(Ik(jk({pubkey:KS,account:jk({executable:Ek(),owner:KS,lamports:Pk(),data:YS,rentEpoch:Pk()})}))),PC=jk({program:Bk(),parsed:Dk(),space:Pk()}),TC=rC(Ik(jk({pubkey:KS,account:jk({executable:Ek(),owner:KS,lamports:Pk(),data:PC,rentEpoch:Pk()})}))),OC=rC(Ik(jk({lamports:Pk(),address:KS}))),BC=jk({executable:Ek(),owner:KS,lamports:Pk(),data:YS,rentEpoch:Pk()}),RC=jk({pubkey:KS,account:BC}),jC=Uk(Lk([Ak(N),PC]),Lk([ZS,PC]),e=>Array.isArray(e)?kk(e,YS):e),LC=jk({executable:Ek(),owner:KS,lamports:Pk(),data:jC,rentEpoch:Pk()}),DC=jk({pubkey:KS,account:LC}),UC=jk({state:Lk([Nk("active"),Nk("inactive"),Nk("activating"),Nk("deactivating")]),active:Pk(),inactive:Pk()}),FC=tC(Ik(jk({signature:Bk(),slot:Pk(),err:hC,memo:Mk(Bk()),blockTime:Tk(Mk(Pk()))}))),zC=tC(Ik(jk({signature:Bk(),slot:Pk(),err:hC,memo:Mk(Bk()),blockTime:Tk(Mk(Pk()))}))),qC=jk({subscription:Pk(),result:nC(BC)}),$C=jk({pubkey:KS,account:BC}),WC=jk({subscription:Pk(),result:nC($C)}),HC=jk({parent:Pk(),slot:Pk(),root:Pk()}),GC=jk({subscription:Pk(),result:HC}),VC=Lk([jk({type:Lk([Nk("firstShredReceived"),Nk("completed"),Nk("optimisticConfirmation"),Nk("root")]),slot:Pk(),timestamp:Pk()}),jk({type:Nk("createdBank"),parent:Pk(),slot:Pk(),timestamp:Pk()}),jk({type:Nk("frozen"),slot:Pk(),timestamp:Pk(),stats:jk({numTransactionEntries:Pk(),numSuccessfulTransactions:Pk(),numFailedTransactions:Pk(),maxTransactionsPerEntry:Pk()})}),jk({type:Nk("dead"),slot:Pk(),timestamp:Pk(),err:Bk()})]),KC=jk({subscription:Pk(),result:VC}),ZC=jk({subscription:Pk(),result:nC(Lk([pC,fC]))}),YC=jk({subscription:Pk(),result:Pk()}),JC=jk({pubkey:Bk(),gossip:Mk(Bk()),tpu:Mk(Bk()),rpc:Mk(Bk()),version:Mk(Bk())}),XC=jk({votePubkey:Bk(),nodePubkey:Bk(),activatedStake:Pk(),epochVoteAccount:Ek(),epochCredits:Ik(Rk([Pk(),Pk(),Pk()])),commission:Pk(),lastVote:Pk(),rootSlot:Mk(Pk())}),QC=tC(jk({current:Ik(XC),delinquent:Ik(XC)})),eI=Lk([Nk("processed"),Nk("confirmed"),Nk("finalized")]),tI=jk({slot:Pk(),confirmations:Mk(Pk()),err:hC,confirmationStatus:Tk(eI)}),rI=rC(Ik(Mk(tI))),nI=tC(Pk()),iI=jk({accountKey:KS,writableIndexes:Ik(Pk()),readonlyIndexes:Ik(Pk())}),oI=jk({signatures:Ik(Bk()),message:jk({accountKeys:Ik(Bk()),header:jk({numRequiredSignatures:Pk(),numReadonlySignedAccounts:Pk(),numReadonlyUnsignedAccounts:Pk()}),instructions:Ik(jk({accounts:Ik(Pk()),data:Bk(),programIdIndex:Pk()})),recentBlockhash:Bk(),addressTableLookups:Tk(Ik(iI))})}),sI=jk({pubkey:KS,signer:Ek(),writable:Ek(),source:Tk(Lk([Nk("transaction"),Nk("lookupTable")]))}),aI=jk({accountKeys:Ik(sI),signatures:Ik(Bk())}),cI=jk({parsed:Dk(),program:Bk(),programId:KS}),lI=jk({accounts:Ik(KS),data:Bk(),programId:KS}),uI=Uk(Lk([lI,cI]),Lk([jk({parsed:Dk(),program:Bk(),programId:Bk()}),jk({accounts:Ik(Bk()),data:Bk(),programId:Bk()})]),e=>kk(e,"accounts"in e?lI:cI)),dI=jk({signatures:Ik(Bk()),message:jk({accountKeys:Ik(sI),instructions:Ik(uI),recentBlockhash:Bk(),addressTableLookups:Tk(Mk(Ik(iI)))})}),hI=jk({accountIndex:Pk(),mint:Bk(),owner:Tk(Bk()),programId:Tk(Bk()),uiTokenAmount:AC}),pI=jk({writable:Ik(KS),readonly:Ik(KS)}),fI=jk({err:hC,fee:Pk(),innerInstructions:Tk(Mk(Ik(jk({index:Pk(),instructions:Ik(jk({accounts:Ik(Pk()),data:Bk(),programIdIndex:Pk()}))})))),preBalances:Ik(Pk()),postBalances:Ik(Pk()),logMessages:Tk(Mk(Ik(Bk()))),preTokenBalances:Tk(Mk(Ik(hI))),postTokenBalances:Tk(Mk(Ik(hI))),loadedAddresses:Tk(pI),computeUnitsConsumed:Tk(Pk()),costUnits:Tk(Pk())}),mI=jk({err:hC,fee:Pk(),innerInstructions:Tk(Mk(Ik(jk({index:Pk(),instructions:Ik(uI)})))),preBalances:Ik(Pk()),postBalances:Ik(Pk()),logMessages:Tk(Mk(Ik(Bk()))),preTokenBalances:Tk(Mk(Ik(hI))),postTokenBalances:Tk(Mk(Ik(hI))),loadedAddresses:Tk(pI),computeUnitsConsumed:Tk(Pk()),costUnits:Tk(Pk())}),gI=Lk([Nk(0),Nk("legacy")]),yI=jk({pubkey:Bk(),lamports:Pk(),postBalance:Mk(Pk()),rewardType:Mk(Bk()),commission:Tk(Mk(Pk()))}),vI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:oI,meta:Mk(fI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),bI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),wI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:aI,meta:Mk(fI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),xI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:dI,meta:Mk(mI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),kI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:aI,meta:Mk(mI),version:Tk(gI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),_I=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),rewards:Tk(Ik(yI)),blockTime:Mk(Pk()),blockHeight:Mk(Pk())}))),SI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),transactions:Ik(jk({transaction:oI,meta:Mk(fI)})),rewards:Tk(Ik(yI)),blockTime:Mk(Pk())}))),CI=tC(Mk(jk({blockhash:Bk(),previousBlockhash:Bk(),parentSlot:Pk(),signatures:Ik(Bk()),blockTime:Mk(Pk())}))),II=tC(Mk(jk({slot:Pk(),meta:Mk(fI),blockTime:Tk(Mk(Pk())),transaction:oI,version:Tk(gI)}))),EI=tC(Mk(jk({slot:Pk(),transaction:dI,meta:Mk(mI),blockTime:Tk(Mk(Pk())),version:Tk(gI)}))),AI=rC(jk({blockhash:Bk(),lastValidBlockHeight:Pk()})),NI=rC(Ek()),MI=tC(Ik(jk({slot:Pk(),numTransactions:Pk(),numSlots:Pk(),samplePeriodSecs:Pk()}))),PI=rC(Mk(jk({feeCalculator:jk({lamportsPerSignature:Pk()})}))),TI=tC(Bk()),OI=tC(Bk()),BI=jk({err:hC,logs:Ik(Bk()),signature:Bk()}),RI=jk({result:nC(BI),subscription:Pk()}),jI={"solana-client":"js/1.0.0-maintenance"};class LI{constructor(e,t){let r,n,i,o,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:r,config:n}=JS(t),i=this._buildArgs([],r,void 0,n),o=FS(i);return e[o]=e[o]??(async()=>{try{const e=kk(await this._rpcRequest("getBlockHeight",i),tC(Pk()));if("error"in e)throw new IS(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,r=t.wsEndpoint,n=t.httpHeaders,i=t.fetch,o=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=r||function(e){const t=e.match(VS);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[r,n,i,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${s}//${n}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,r,n,i,o){const s=r||$S;let a;null!=o&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments."),n&&(a=async(e,t)=>{const r=await new Promise((r,i)=>{try{n(e,t,(e,t)=>r([e,t]))}catch(ud){i(ud)}});return await s(...r)});const c=new v_(async(r,n)=>{const o={method:"POST",body:r,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},jI)};try{let t,r=5,c=500;for(;t=a?await a(e,o):await s(e,o),429===t.status&&!0!==i&&(r-=1,0!==r);)console.error(`Server responded with ${t.status} ${t.statusText}. Retrying after ${c}ms delay...`),await ES(c),c*=2;const l=await t.text();t.ok?n(null,l):n(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(yA){yA instanceof Error&&n(yA)}},{});return c}(e,n,i,o,s,a),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((r,n)=>{c.request(e,t,(e,t)=>{e?n(e):r(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((r,n)=>{0===t.length&&r([]);const i=t.map(t=>e.request(t.methodName,t.args));e.request(i,(e,t)=>{e?n(e):r(t)})})}(this._rpcClient),this._rpcWebSocket=new WS(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,void 0,n),o=kk(await this._rpcRequest("getBalance",i),rC(Pk()));if("error"in o)throw new IS(o.error,`failed to get balance for ${e.toBase58()}`);return o.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=kk(await this._rpcRequest("getBlockTime",[e]),tC(Mk(Pk())));if("error"in t)throw new IS(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=kk(await this._rpcRequest("minimumLedgerSlot",[]),tC(Pk()));if("error"in e)throw new IS(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=kk(await this._rpcRequest("getFirstAvailableBlock",[]),IC);if("error"in e)throw new IS(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const r=kk(await this._rpcRequest("getSupply",[t]),EC);if("error"in r)throw new IS(r.error,"failed to get supply");return r.result}async getTokenSupply(e,t){const r=this._buildArgs([e.toBase58()],t),n=kk(await this._rpcRequest("getTokenSupply",r),rC(AC));if("error"in n)throw new IS(n.error,"failed to get token supply");return n.result}async getTokenAccountBalance(e,t){const r=this._buildArgs([e.toBase58()],t),n=kk(await this._rpcRequest("getTokenAccountBalance",r),rC(AC));if("error"in n)throw new IS(n.error,"failed to get token account balance");return n.result}async getTokenAccountsByOwner(e,t,r){const{commitment:n,config:i}=JS(r);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,n,"base64",i),a=kk(await this._rpcRequest("getTokenAccountsByOwner",s),MC);if("error"in a)throw new IS(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,r){let n=[e.toBase58()];"mint"in t?n.push({mint:t.mint.toBase58()}):n.push({programId:t.programId.toBase58()});const i=this._buildArgs(n,r,"jsonParsed"),o=kk(await this._rpcRequest("getTokenAccountsByOwner",i),TC);if("error"in o)throw new IS(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},r=t.filter||t.commitment?[t]:[],n=kk(await this._rpcRequest("getLargestAccounts",r),OC);if("error"in n)throw new IS(n.error,"failed to get largest accounts");return n.result}async getTokenLargestAccounts(e,t){const r=this._buildArgs([e.toBase58()],t),n=kk(await this._rpcRequest("getTokenLargestAccounts",r),NC);if("error"in n)throw new IS(n.error,"failed to get token largest accounts");return n.result}async getAccountInfoAndContext(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,"base64",n),o=kk(await this._rpcRequest("getAccountInfo",i),rC(Mk(BC)));if("error"in o)throw new IS(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,"jsonParsed",n),o=kk(await this._rpcRequest("getAccountInfo",i),rC(Mk(LC)));if("error"in o)throw new IS(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(r){throw new Error("failed to get info about account "+e.toBase58()+": "+r)}}async getMultipleParsedAccounts(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],r,"jsonParsed",n),s=kk(await this._rpcRequest("getMultipleAccounts",o),rC(Ik(Mk(LC))));if("error"in s)throw new IS(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],r,"base64",n),s=kk(await this._rpcRequest("getMultipleAccounts",o),rC(Ik(Mk(BC))));if("error"in s)throw new IS(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,r){const{commitment:n,config:i}=JS(t),o=this._buildArgs([e.toBase58()],n,void 0,{...i,epoch:null!=r?r:null==i?void 0:i.epoch}),s=kk(await this._rpcRequest("getStakeActivation",o),tC(UC));if("error"in s)throw new IS(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:r,config:n}=JS(t),{encoding:i,...o}=n||{},s=this._buildArgs([e.toBase58()],r,i||"base64",{...o,...o.filters?{filters:XS(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Ik(RC),l=!0===o.withContext?kk(a,rC(c)):kk(a,tC(c));if("error"in l)throw new IS(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e.toBase58()],r,"jsonParsed",n),o=kk(await this._rpcRequest("getProgramAccounts",i),tC(Ik(DC)));if("error"in o)throw new IS(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.result}async confirmTransaction(e,t){var r;let n,i;if("string"==typeof e)n=e;else{const t=e;if(null==(r=t.abortSignal)?void 0:r.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{i=Pw.decode(n)}catch(yA){throw new Error("signature must be base58 encoded: "+n)}return hS(64===i.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,r)=>{null!=e&&(e.aborted?r(e.reason):e.addEventListener("abort",()=>{r(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let r,n,i=!1;const o=new Promise((o,s)=>{try{r=this.onSignature(t,(e,t)=>{r=void 0;const n={context:t,value:e};o({__type:bS.PROCESSED,response:n})},e);const a=new Promise(e=>{null==r?e():n=this._onSubscriptionStateChange(r,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,i)return;const r=await this.getSignatureStatus(t);if(i)return;if(null==r)return;const{context:n,value:c}=r;if(null!=c)if(null==c?void 0:c.err)s(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}i=!0,o({__type:bS.PROCESSED,response:{context:n,value:c}})}})()}catch(yA){s(yA)}});return{abortConfirmation:()=>{n&&(n(),n=void 0),null!=r&&(this.removeSignatureListener(r),r=void 0)},confirmationPromise:o}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:r,signature:n}}){let i=!1;const o=new Promise(t=>{const n=async()=>{try{return await this.getBlockHeight(e)}catch(t){return-1}};(async()=>{let e=await n();if(!i){for(;e<=r;){if(await ES(1e3),i)return;if(e=await n(),i)return}t({__type:bS.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:n}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,o]);if(e.__type!==bS.PROCESSED)throw new nS(n);l=e.response}finally{i=!0,s()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:r,nonceAccountPubkey:n,nonceValue:i,signature:o}}){let s=!1;const a=new Promise(t=>{let o=i,a=null;const c=async()=>{try{const{context:t,value:i}=await this.getNonceAndContext(n,{commitment:e,minContextSlot:r});return a=t.slot,null==i?void 0:i.nonce}catch(t){return o}};(async()=>{if(o=await c(),!s)for(;;){if(i!==o)return void t({__type:bS.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await ES(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===bS.PROCESSED)d=t.response;else{let n;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??r))){n=e;break}await ES(400)}if(!(null==n?void 0:n.value))throw new oS(o);{const t=e||"finalized",{confirmationStatus:r}=n.value;switch(t){case"processed":case"recent":if("processed"!==r&&"confirmed"!==r&&"finalized"!==r)throw new oS(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==r&&"finalized"!==r)throw new oS(o);break;case"finalized":case"max":case"root":if("finalized"!==r)throw new oS(o)}d={context:n.context,value:{err:n.value.err}}}}}finally{s=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let r;const n=new Promise(t=>{let n=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":n=this._confirmTransactionInitialTimeout||3e4}r=setTimeout(()=>t({__type:bS.TIMED_OUT,timeoutMs:n}),n)}),{abortConfirmation:i,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,n]);if(e.__type!==bS.PROCESSED)throw new iS(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(r),i()}return s}async getClusterNodes(){const e=kk(await this._rpcRequest("getClusterNodes",[]),tC(Ik(JC)));if("error"in e)throw new IS(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),r=kk(await this._rpcRequest("getVoteAccounts",t),QC);if("error"in r)throw new IS(r.error,"failed to get vote accounts");return r.result}async getSlot(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getSlot",n),tC(Pk()));if("error"in i)throw new IS(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getSlotLeader",n),tC(Bk()));if("error"in i)throw new IS(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const r=[e,t],n=kk(await this._rpcRequest("getSlotLeaders",r),tC(Ik(KS)));if("error"in n)throw new IS(n.error,"failed to get slot leaders");return n.result}async getSignatureStatus(e,t){const{context:r,value:n}=await this.getSignatureStatuses([e],t);hS(1===n.length);return{context:r,value:n[0]}}async getSignatureStatuses(e,t){const r=[e];t&&r.push(t);const n=kk(await this._rpcRequest("getSignatureStatuses",r),rI);if("error"in n)throw new IS(n.error,"failed to get signature status");return n.result}async getTransactionCount(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getTransactionCount",n),tC(Pk()));if("error"in i)throw new IS(i.error,"failed to get transaction count");return i.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),r=kk(await this._rpcRequest("getInflationGovernor",t),wC);if("error"in r)throw new IS(r.error,"failed to get inflation");return r.result}async getInflationReward(e,t,r){const{commitment:n,config:i}=JS(r),o=this._buildArgs([e.map(e=>e.toBase58())],n,void 0,{...i,epoch:null!=t?t:null==i?void 0:i.epoch}),s=kk(await this._rpcRequest("getInflationReward",o),sC);if("error"in s)throw new IS(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=kk(await this._rpcRequest("getInflationRate",[]),xC);if("error"in e)throw new IS(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getEpochInfo",n),_C);if("error"in i)throw new IS(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=kk(await this._rpcRequest("getEpochSchedule",[]),SC);if("error"in e)throw new IS(e.error,"failed to get epoch schedule");const t=e.result;return new qS(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=kk(await this._rpcRequest("getLeaderSchedule",[]),CC);if("error"in e)throw new IS(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const r=this._buildArgs([e],t),n=kk(await this._rpcRequest("getMinimumBalanceForRentExemption",r),nI);return"error"in n?(console.warn("Unable to fetch minimum balance for rent exemption"),0):n.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:r}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:r,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=kk(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),MI);if("error"in t)throw new IS(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const r=this._buildArgs([e],t),n=kk(await this._rpcRequest("getFeeCalculatorForBlockhash",r),PI);if("error"in n)throw new IS(n.error,"failed to get fee calculator");const{context:i,value:o}=n.result;return{context:i,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const r=Z_(e.serialize()).toString("base64"),n=this._buildArgs([r],t),i=kk(await this._rpcRequest("getFeeForMessage",n),rC(Mk(Pk())));if("error"in i)throw new IS(i.error,"failed to get fee for message");if(null===i.result)throw new Error("invalid blockhash");return i.result}async getRecentPrioritizationFees(e){var t;const r=null==(t=null==e?void 0:e.lockedWritableAccounts)?void 0:t.map(e=>e.toBase58()),n=(null==r?void 0:r.length)?[r]:[],i=kk(await this._rpcRequest("getRecentPrioritizationFees",n),kC);if("error"in i)throw new IS(i.error,"failed to get recent prioritization fees");return i.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,void 0,r),i=kk(await this._rpcRequest("getLatestBlockhash",n),AI);if("error"in i)throw new IS(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgs([e],r,void 0,n),o=kk(await this._rpcRequest("isBlockhashValid",i),NI);if("error"in o)throw new IS(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=kk(await this._rpcRequest("getVersion",[]),tC(mC));if("error"in e)throw new IS(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=kk(await this._rpcRequest("getGenesisHash",[]),tC(Bk()));if("error"in e)throw new IS(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,void 0,n),o=await this._rpcRequest("getBlock",i);try{switch(null==n?void 0:n.transactionDetails){case"accounts":{const e=kk(o,wI);if("error"in e)throw e.error;return e.result}case"none":{const e=kk(o,bI);if("error"in e)throw e.error;return e.result}default:{const e=kk(o,vI);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:r})=>({meta:t,transaction:{...e,message:iC(r,e.message)},version:r}))}:null}}}catch(s){throw new IS(s,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n),o=await this._rpcRequest("getBlock",i);try{switch(null==n?void 0:n.transactionDetails){case"accounts":{const e=kk(o,kI);if("error"in e)throw e.error;return e.result}case"none":{const e=kk(o,_I);if("error"in e)throw e.error;return e.result}default:{const e=kk(o,xI);if("error"in e)throw e.error;return e.result}}}catch(s){throw new IS(s,"failed to get block")}}async getBlockProduction(e){let t,r;if("string"==typeof e)r=e;else if(e){const{commitment:n,...i}=e;r=n,t=i}const n=this._buildArgs([],r,"base64",t),i=kk(await this._rpcRequest("getBlockProduction",n),bC);if("error"in i)throw new IS(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,void 0,n),o=kk(await this._rpcRequest("getTransaction",i),II);if("error"in o)throw new IS(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:iC(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:r,config:n}=JS(t),i=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n),o=kk(await this._rpcRequest("getTransaction",i),EI);if("error"in o)throw new IS(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=kk(e,EI);if("error"in t)throw new IS(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:r,config:n}=JS(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],r,void 0,n)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=kk(e,II);if("error"in t)throw new IS(t.error,"failed to get transactions");const r=t.result;return r?{...r,transaction:{...r.transaction,message:iC(r.version,r.transaction.message)}}:r})}async getConfirmedBlock(e,t){const r=this._buildArgsAtLeastConfirmed([e],t),n=kk(await this._rpcRequest("getBlock",r),SI);if("error"in n)throw new IS(n.error,"failed to get confirmed block");const i=n.result;if(!i)throw new Error("Confirmed block "+e+" not found");const o={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const r=new yS(e.message);return{meta:t,transaction:{...e,message:r}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:kS.populate(e.message,e.signatures)}))}}async getBlocks(e,t,r){const n=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],r),i=kk(await this._rpcRequest("getBlocks",n),tC(Ik(Pk())));if("error"in i)throw new IS(i.error,"failed to get blocks");return i.result}async getBlockSignatures(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),n=kk(await this._rpcRequest("getBlock",r),CI);if("error"in n)throw new IS(n.error,"failed to get block");const i=n.result;if(!i)throw new Error("Block "+e+" not found");return i}async getConfirmedBlockSignatures(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),n=kk(await this._rpcRequest("getBlock",r),CI);if("error"in n)throw new IS(n.error,"failed to get confirmed block");const i=n.result;if(!i)throw new Error("Confirmed block "+e+" not found");return i}async getConfirmedTransaction(e,t){const r=this._buildArgsAtLeastConfirmed([e],t),n=kk(await this._rpcRequest("getTransaction",r),II);if("error"in n)throw new IS(n.error,"failed to get transaction");const i=n.result;if(!i)return i;const o=new yS(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:kS.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),n=kk(await this._rpcRequest("getTransaction",r),EI);if("error"in n)throw new IS(n.error,"failed to get confirmed transaction");return n.result}async getParsedConfirmedTransactions(e,t){const r=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(r)).map(e=>{const t=kk(e,EI);if("error"in t)throw new IS(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,r){let n={},i=await this.getFirstAvailableBlock();for(;!("until"in n)&&!(--t<=0||t<i);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(n.until=e.signatures[e.signatures.length-1].toString())}catch(yA){if(yA instanceof Error&&yA.message.includes("skipped"))continue;throw yA}let o=await this.getSlot("finalized");for(;!("before"in n||++r>o);)try{const e=await this.getConfirmedBlockSignatures(r);e.signatures.length>0&&(n.before=e.signatures[e.signatures.length-1].toString())}catch(yA){if(yA instanceof Error&&yA.message.includes("skipped"))continue;throw yA}return(await this.getConfirmedSignaturesForAddress2(e,n)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,r){const n=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,t),i=kk(await this._rpcRequest("getConfirmedSignaturesForAddress2",n),FC);if("error"in i)throw new IS(i.error,"failed to get confirmed signatures for address");return i.result}async getSignaturesForAddress(e,t,r){const n=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,t),i=kk(await this._rpcRequest("getSignaturesForAddress",n),zC);if("error"in i)throw new IS(i.error,"failed to get signatures for address");return i.result}async getAddressLookupTable(e,t){const{context:r,value:n}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==n&&(i=new HS({key:e,state:HS.deserialize(n.data)})),{context:r,value:i}}async getNonceAndContext(e,t){const{context:r,value:n}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==n&&(i=TS.fromAccountData(n.data)),{context:r,value:i}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const r=kk(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),TI);if("error"in r)throw new IS(r.error,`airdrop to ${e.toBase58()} failed`);return r.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await ES(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,r=t?t.blockhash:null;for(let n=0;n<50;n++){const e=await this.getLatestBlockhash("finalized");if(r!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await ES(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:r}=JS(e),n=this._buildArgs([],t,"base64",r),i=kk(await this._rpcRequest("getStakeMinimumDelegation",n),rC(Pk()));if("error"in i)throw new IS(i.error,"failed to get stake minimum delegation");return i.result}async simulateTransaction(e,t,r){if("message"in e){const n=e.serialize(),i=N.from(n).toString("base64");if(Array.isArray(t)||void 0!==r)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[i,o],a=kk(await this._rpcRequest("simulateTransaction",s),vC);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let n;if(e instanceof kS){let t=e;n=new kS,n.feePayer=t.feePayer,n.instructions=e.instructions,n.nonceInfo=t.nonceInfo,n.signatures=t.signatures}else n=kS.populate(e),n._message=n._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const i=t;if(n.nonceInfo&&i)n.sign(...i);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(n.lastValidBlockHeight=t.lastValidBlockHeight,n.recentBlockhash=t.blockhash,!i)break;if(n.sign(...i),!n.signature)throw new Error("!signature");const r=n.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(r)&&!this._blockhashInfo.transactionSignatures.includes(r)){this._blockhashInfo.simulatedSignatures.push(r);break}e=!0}}const o=n._compile(),s=o.serialize(),a=n._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(r){const e=(Array.isArray(r)?r:o.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}i&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=kk(await this._rpcRequest("simulateTransaction",l),vC);if("error"in u){let e;if("data"in u.error&&(e=u.error.data.logs,e&&Array.isArray(e))){const t="\n ",r=t+e.join(t);console.error(u.error.message,r)}throw new CS({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,r){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const r=e.serialize();return await this.sendRawTransaction(r,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const n=t;if(e.nonceInfo)e.sign(...n);else{let t=this._disableBlockhashCaching;for(;;){const r=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=r.lastValidBlockHeight,e.recentBlockhash=r.blockhash,e.sign(...n),!e.signature)throw new Error("!signature");const i=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(i)){this._blockhashInfo.transactionSignatures.push(i);break}t=!0}}const i=e.serialize();return await this.sendRawTransaction(i,r)}async sendRawTransaction(e,t){const r=Z_(e).toString("base64");return await this.sendEncodedTransaction(r,t)}async sendEncodedTransaction(e,t){const r={encoding:"base64"},n=t&&t.skipPreflight,i=!0===n?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(r.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(r.minContextSlot=t.minContextSlot),n&&(r.skipPreflight=n),i&&(r.preflightCommitment=i);const o=[e,r],s=kk(await this._rpcRequest("sendTransaction",o),OI);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new CS({action:n?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){var r;const n=null==(r=this._subscriptionsByHash[e])?void 0:r.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const r=this._subscriptionStateChangeCallbacksByHash[e];r&&r.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){var r;const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const i=(r=this._subscriptionStateChangeCallbacksByHash)[n]||(r[n]=new Set);return i.add(t),()=>{i.delete(t),0===i.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(yA){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const r=this._subscriptionsByHash[e];if(void 0!==r)switch(r.state){case"pending":case"unsubscribed":if(0===r.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===r.state&&delete this._subscriptionCallbacksByServerSubscriptionId[r.serverSubscriptionId],void(await this._updateSubscriptions());await(async()=>{const{args:n,method:i}=r;try{this._setSubscription(e,{...r,state:"subscribing"});const t=await this._rpcWebSocket.call(i,n);this._setSubscription(e,{...r,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=r.callbacks,await this._updateSubscriptions()}catch(o){if(console.error(`Received ${o instanceof Error?"":"JSON-RPC "}error calling \`${i}\``,{args:n,error:o}),!t())return;this._setSubscription(e,{...r,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===r.callbacks.size&&await(async()=>{const{serverSubscriptionId:n,unsubscribeMethod:i}=r;if(this._subscriptionsAutoDisposedByRpc.has(n))this._subscriptionsAutoDisposedByRpc.delete(n);else{this._setSubscription(e,{...r,state:"unsubscribing"}),this._setSubscription(e,{...r,state:"unsubscribing"});try{await this._rpcWebSocket.call(i,[n])}catch(o){if(o instanceof Error&&console.error(`${i} error:`,o.message),!t())return;return this._setSubscription(e,{...r,state:"subscribed"}),void(await this._updateSubscriptions())}}this._setSubscription(e,{...r,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const r=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==r&&r.forEach(e=>{try{e(...t)}catch(r){console.error(r)}})}_wsOnAccountNotification(e){const{result:t,subscription:r}=kk(e,qC);this._handleServerNotification(r,[t.value,t.context])}_makeSubscription(e,t){const r=this._nextClientSubscriptionId++,n=FS([e.method,t]),i=this._subscriptionsByHash[n];return void 0===i?this._subscriptionsByHash[n]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[r]=n,this._subscriptionDisposeFunctionsByClientSubscriptionId[r]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[r],delete this._subscriptionHashByClientSubscriptionId[r];const t=this._subscriptionsByHash[n];hS(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${r}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),r}onAccountChange(e,t,r){const{commitment:n,config:i}=JS(r),o=this._buildArgs([e.toBase58()],n||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:r}=kk(e,WC);this._handleServerNotification(r,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,r,n){const{commitment:i,config:o}=JS(r),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(n?{filters:XS(n)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,r){const n=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],r||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},n)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:r}=kk(e,RI);this._handleServerNotification(r,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:r}=kk(e,GC);this._handleServerNotification(r,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:r}=kk(e,KC);this._handleServerNotification(r,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const r=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];r?await r():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${t}' events could not be found.`)}_buildArgs(e,t,r,n){const i=t||this._commitment;if(i||r||n){let t={};r&&(t.encoding=r),i&&(t.commitment=i),n&&(t=Object.assign(t,n)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,r,n){const i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,r,n)}_wsOnSignatureNotification(e){const{result:t,subscription:r}=kk(e,ZC);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(r),this._handleServerNotification(r,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,r){const n=this._buildArgs([e],r||this._commitment||"finalized"),i=this._makeSubscription({callback:(e,r)=>{if("status"===e.type){t(e.result,r);try{this.removeSignatureListener(i)}catch(n){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},n);return i}onSignatureWithOptions(e,t,r){const{commitment:n,...i}={...r,commitment:r&&r.commitment||this._commitment||"finalized"},o=this._buildArgs([e],n,void 0,i),s=this._makeSubscription({callback:(e,r)=>{t(e,r);try{this.removeSignatureListener(s)}catch(n){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:r}=kk(e,YC);this._handleServerNotification(r,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}var DI;Object.freeze({CreateLookupTable:{index:0,layout:rk([Qx("instruction"),OS("recentSlot"),Jx("bumpSeed")])},FreezeLookupTable:{index:1,layout:rk([Qx("instruction")])},ExtendLookupTable:{index:2,layout:rk([Qx("instruction"),OS(),nk(aS(),Yx(Qx(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:rk([Qx("instruction")])},CloseLookupTable:{index:4,layout:rk([Qx("instruction")])}}),new tS("AddressLookupTab1e1111111111111111111111111"),Object.freeze({RequestUnits:{index:0,layout:rk([Jx("instruction"),Qx("units"),Qx("additionalFee")])},RequestHeapFrame:{index:1,layout:rk([Jx("instruction"),Qx("bytes")])},SetComputeUnitLimit:{index:2,layout:rk([Jx("instruction"),Qx("units")])},SetComputeUnitPrice:{index:3,layout:rk([Jx("instruction"),OS("microLamports")])}}),new tS("ComputeBudget111111111111111111111111111111"),rk([Jx("numSignatures"),Jx("padding"),Xx("signatureOffset"),Xx("signatureInstructionIndex"),Xx("publicKeyOffset"),Xx("publicKeyInstructionIndex"),Xx("messageDataOffset"),Xx("messageDataSize"),Xx("messageInstructionIndex")]),new tS("Ed25519SigVerify111111111111111111111111111"),G_.utils.isValidPrivateKey,rk([Jx("numSignatures"),Xx("signatureOffset"),Jx("signatureInstructionIndex"),Xx("ethAddressOffset"),Jx("ethAddressInstructionIndex"),Xx("messageDataOffset"),Xx("messageDataSize"),Jx("messageInstructionIndex"),ik(20,"ethAddress"),ik(64,"signature"),Jx("recoveryId")]),new tS("KeccakSecp256k11111111111111111111111111111"),new tS("StakeConfig11111111111111111111111111111111");class UI{constructor(e,t,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=r}}DI=UI,UI.default=new DI(0,0,tS.default),Object.freeze({Initialize:{index:0,layout:rk([Qx("instruction"),((e="authorized")=>rk([aS("staker"),aS("withdrawer")],e))(),((e="lockup")=>rk([tk("unixTimestamp"),tk("epoch"),aS("custodian")],e))()])},Authorize:{index:1,layout:rk([Qx("instruction"),aS("newAuthorized"),Qx("stakeAuthorizationType")])},Delegate:{index:2,layout:rk([Qx("instruction")])},Split:{index:3,layout:rk([Qx("instruction"),tk("lamports")])},Withdraw:{index:4,layout:rk([Qx("instruction"),tk("lamports")])},Deactivate:{index:5,layout:rk([Qx("instruction")])},Merge:{index:7,layout:rk([Qx("instruction")])},AuthorizeWithSeed:{index:8,layout:rk([Qx("instruction"),aS("newAuthorized"),Qx("stakeAuthorizationType"),cS("authoritySeed"),aS("authorityOwner")])}}),new tS("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:rk([Qx("instruction"),((e="voteInit")=>rk([aS("nodePubkey"),aS("authorizedVoter"),aS("authorizedWithdrawer"),Jx("commission")],e))()])},Authorize:{index:1,layout:rk([Qx("instruction"),aS("newAuthorized"),Qx("voteAuthorizationType")])},Withdraw:{index:3,layout:rk([Qx("instruction"),tk("lamports")])},UpdateValidatorIdentity:{index:4,layout:rk([Qx("instruction")])},AuthorizeWithSeed:{index:10,layout:rk([Qx("instruction"),((e="voteAuthorizeWithSeedArgs")=>rk([Qx("voteAuthorizationType"),aS("currentAuthorityDerivedKeyOwnerPubkey"),cS("currentAuthorityDerivedKeySeed"),aS("newAuthorized")],e))()])}}),new tS("Vote111111111111111111111111111111111111111"),new tS("Va1idator1nfo111111111111111111111111111111"),jk({name:Bk(),website:Tk(Bk()),details:Tk(Bk()),iconUrl:Tk(Bk()),keybaseUsername:Tk(Bk())}),new tS("Vote111111111111111111111111111111111111111"),rk([aS("nodePubkey"),aS("authorizedWithdrawer"),Jx("commission"),ek(),nk(rk([ek("slot"),Qx("confirmationCount")]),Yx(Qx(),-8),"votes"),Jx("rootSlotValid"),ek("rootSlot"),ek(),nk(rk([ek("epoch"),aS("authorizedVoter")]),Yx(Qx(),-8),"authorizedVoters"),rk([nk(rk([aS("authorizedPubkey"),ek("epochOfLastAuthorizedSwitch"),ek("targetEpoch")]),32,"buf"),ek("idx"),Jx("isEmpty")],"priorVoters"),ek(),nk(rk([ek("epoch"),ek("credits"),ek("prevCredits")]),Yx(Qx(),-8),"epochCredits"),rk([ek("slot"),ek("timestamp")],"lastTimestamp")]);const FI=1e9,zI=Object.freeze(Object.defineProperty({__proto__:null,AddressLookupTableAccount:HS,BLOCKHASH_CACHE_TIMEOUT_MS:3e4,Connection:LI,EpochSchedule:qS,FeeCalculatorLayout:NS,LAMPORTS_PER_SOL:FI,Lockup:UI,MAX_SEED_LENGTH:32,Message:yS,MessageAccountKeys:sS,MessageV0:vS,NONCE_ACCOUNT_LENGTH:PS,NonceAccount:TS,PACKET_DATA_SIZE:rS,PUBLIC_KEY_LENGTH:Q_,PublicKey:tS,SIGNATURE_LENGTH_IN_BYTES:64,SOLANA_SCHEMA:J_,SYSTEM_INSTRUCTION_LAYOUTS:BS,SYSVAR_RECENT_BLOCKHASHES_PUBKEY:_S,SYSVAR_RENT_PUBKEY:SS,SendTransactionError:CS,SolanaJSONRPCError:IS,Struct:Y_,SystemProgram:RS,Transaction:kS,TransactionExpiredBlockheightExceededError:nS,TransactionExpiredNonceInvalidError:oS,TransactionExpiredTimeoutError:iS,TransactionInstruction:xS,TransactionStatus:bS,VERSION_PREFIX_MASK:127},Symbol.toStringTag,{value:"Module"})),qI=new tS("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new tS("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const $I=new tS("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new tS("So11111111111111111111111111111111111111112"),new tS("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const WI=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var HI={};Object.defineProperty(HI,"__esModule",{value:!0});var GI=HI.toBigIntLE=function(e){{const t=I.from(e);t.reverse();const r=t.toString("hex");return 0===r.length?BigInt(0):BigInt(`0x${r}`)}};HI.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}};var VI=HI.toBufferLE=function(e,t){{const r=e.toString(16),n=I.from(r.padStart(2*t,"0").slice(0,2*t),"hex");return n.reverse(),n}};HI.toBufferBE=function(e,t){{const r=e.toString(16);return I.from(r.padStart(2*t,"0").slice(0,2*t),"hex")}};const KI=(ZI=8,e=>{const t=ik(ZI,e),{encode:r,decode:n}=WI(t),i=t;return i.decode=(e,t)=>{const r=n(e,t);return GI(I.from(r))},i.encode=(e,t,n)=>{const i=VI(e,ZI);return r(i,t,n)},i});var ZI;const YI=e=>{const t=Jx(e),{encode:r,decode:n}=WI(t),i=t;return i.decode=(e,t)=>!!n(e,t),i.encode=(e,t,n)=>{const i=Number(e);return r(i,t,n)},i},JI=e=>{const t=ik(32,e),{encode:r,decode:n}=WI(t),i=t;return i.decode=(e,t)=>{const r=n(e,t);return new tS(r)},i.encode=(e,t,n)=>{const i=e.toBuffer();return r(i,t,n)},i};class XI extends Error{constructor(e){super(e)}}class QI extends XI{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class eE extends XI{constructor(){super(...arguments),this.name="TokenInvalidAccountError"}}class tE extends XI{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class rE extends XI{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class nE extends XI{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var iE,oE,sE,aE;(oE=iE||(iE={}))[oE.InitializeMint=0]="InitializeMint",oE[oE.InitializeAccount=1]="InitializeAccount",oE[oE.InitializeMultisig=2]="InitializeMultisig",oE[oE.Transfer=3]="Transfer",oE[oE.Approve=4]="Approve",oE[oE.Revoke=5]="Revoke",oE[oE.SetAuthority=6]="SetAuthority",oE[oE.MintTo=7]="MintTo",oE[oE.Burn=8]="Burn",oE[oE.CloseAccount=9]="CloseAccount",oE[oE.FreezeAccount=10]="FreezeAccount",oE[oE.ThawAccount=11]="ThawAccount",oE[oE.TransferChecked=12]="TransferChecked",oE[oE.ApproveChecked=13]="ApproveChecked",oE[oE.MintToChecked=14]="MintToChecked",oE[oE.BurnChecked=15]="BurnChecked",oE[oE.InitializeAccount2=16]="InitializeAccount2",oE[oE.SyncNative=17]="SyncNative",oE[oE.InitializeAccount3=18]="InitializeAccount3",oE[oE.InitializeMultisig2=19]="InitializeMultisig2",oE[oE.InitializeMint2=20]="InitializeMint2",oE[oE.GetAccountDataSize=21]="GetAccountDataSize",oE[oE.InitializeImmutableOwner=22]="InitializeImmutableOwner",oE[oE.AmountToUiAmount=23]="AmountToUiAmount",oE[oE.UiAmountToAmount=24]="UiAmountToAmount",oE[oE.InitializeMintCloseAuthority=25]="InitializeMintCloseAuthority",oE[oE.TransferFeeExtension=26]="TransferFeeExtension",oE[oE.ConfidentialTransferExtension=27]="ConfidentialTransferExtension",oE[oE.DefaultAccountStateExtension=28]="DefaultAccountStateExtension",oE[oE.Reallocate=29]="Reallocate",oE[oE.MemoTransferExtension=30]="MemoTransferExtension",oE[oE.CreateNativeMint=31]="CreateNativeMint",oE[oE.InitializeNonTransferableMint=32]="InitializeNonTransferableMint",oE[oE.InterestBearingMintExtension=33]="InterestBearingMintExtension",oE[oE.CpiGuardExtension=34]="CpiGuardExtension",oE[oE.InitializePermanentDelegate=35]="InitializePermanentDelegate",oE[oE.TransferHookExtension=36]="TransferHookExtension",oE[oE.MetadataPointerExtension=39]="MetadataPointerExtension",oE[oE.GroupPointerExtension=40]="GroupPointerExtension",oE[oE.GroupMemberPointerExtension=41]="GroupMemberPointerExtension",oE[oE.ScaledUiAmountExtension=43]="ScaledUiAmountExtension",oE[oE.PausableExtension=44]="PausableExtension",(aE=sE||(sE={}))[aE.Uninitialized=0]="Uninitialized",aE[aE.Mint=1]="Mint",aE[aE.Account=2]="Account";const cE=rk([Jx("m"),Jx("n"),YI("isInitialized"),JI("signer1"),JI("signer2"),JI("signer3"),JI("signer4"),JI("signer5"),JI("signer6"),JI("signer7"),JI("signer8"),JI("signer9"),JI("signer10"),JI("signer11")]).span;var lE,uE;(uE=lE||(lE={}))[uE.Uninitialized=0]="Uninitialized",uE[uE.Initialized=1]="Initialized",uE[uE.Frozen=2]="Frozen";const dE=rk([JI("mint"),JI("owner"),KI("amount"),Qx("delegateOption"),JI("delegate"),Jx("state"),Qx("isNativeOption"),KI("isNative"),KI("delegatedAmount"),Qx("closeAuthorityOption"),JI("closeAuthority")]),hE=dE.span;async function pE(e,t,r,n=qI){return function(e,t,r=qI){if(!t)throw new QI;if(!t.owner.equals(r))throw new tE;if(t.data.length<hE)throw new rE;const n=dE.decode(t.data.slice(0,hE));let i=I.alloc(0);if(t.data.length>hE){if(t.data.length===cE)throw new rE;if(t.data[hE]!=sE.Account)throw new eE;i=t.data.slice(hE+1)}return{address:e,mint:n.mint,owner:n.owner,amount:n.amount,delegate:n.delegateOption?n.delegate:null,delegatedAmount:n.delegatedAmount,isInitialized:n.state!==lE.Uninitialized,isFrozen:n.state===lE.Frozen,isNative:!!n.isNativeOption,rentExemptReserve:n.isNativeOption?n.isNative:null,closeAuthority:n.closeAuthorityOption?n.closeAuthority:null,tlvData:i}}(t,await e.getAccountInfo(t,r),n)}async function fE(e,t,r=!1,n=qI,i=$I){if(!r&&!tS.isOnCurve(t.toBuffer()))throw new nE;const[o]=await tS.findProgramAddress([t.toBuffer(),n.toBuffer(),e.toBuffer()],i);return o}function mE(e,t,r,n,i=qI,o=$I){return function(e,t,r,n,i,o=qI,s=$I){const a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:RS.programId,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1}];return new xS({keys:a,programId:s,data:i})}(e,t,r,n,I.alloc(0),i,o)}rk([Qx("mintAuthorityOption"),JI("mintAuthority"),KI("supply"),Jx("decimals"),YI("isInitialized"),Qx("freezeAuthorityOption"),JI("freezeAuthority")]).span;const gE=rk([Jx("instruction"),KI("amount")]);function yE(e,t,r,n,i=[],o=qI){const s=function(e,t,r){if(r.length){e.push({pubkey:t,isSigner:!1,isWritable:!1});for(const t of r)e.push({pubkey:t instanceof tS?t:t.publicKey,isSigner:!0,isWritable:!1})}else e.push({pubkey:t,isSigner:!0,isWritable:!1});return e}([{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0}],r,i),a=I.alloc(gE.span);return gE.encode({instruction:iE.Transfer,amount:BigInt(n)},a),new xS({keys:s,programId:o,data:a})}const vE=(e,t)=>{const[n,i]=r.useState(!1),[o,s]=r.useState(null),[a,c]=r.useState(null),l=r.useRef(0),u=r.useCallback(()=>{const t=Array.isArray(e)?e:[e];if(!t||0===t.length||!t[0])return null;const r=t[l.current%t.length];return new LI(r,"confirmed")},[e]);r.useCallback(()=>{const t=Array.isArray(e)?e:[e];l.current=(l.current+1)%t.length},[e]);const d=r.useCallback(async(e,r)=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const n=u();if(!n)throw new Error("Solana RPC connection not available. Please select a Solana network.");const o=t.adapter,a=Math.floor(r*FI),c=5e-6,l=r+c,d=new tS(t.publicKey),h=await n.getBalance(d)/FI;if(h<l){const e=(l-h).toFixed(6);throw new Error(`Insufficient SOL balance. You have ${h.toFixed(6)} SOL but need ${l.toFixed(6)} SOL (${r} + ~${c} fee). Please add at least ${e} SOL to your wallet.`)}const p=new tS(e),f=(new kS).add(RS.transfer({fromPubkey:d,toPubkey:p,lamports:a})),{blockhash:m,lastValidBlockHeight:g}=await n.getLatestBlockhash();f.recentBlockhash=m,f.feePayer=d;const y=await o.signTransaction(f),v=await n.sendRawTransaction(y.serialize());return s(v),i(!1),{signature:v,success:!0}}catch(yA){throw console.error("❌ SOL transaction failed:",yA),c(yA.message||"Transaction failed"),i(!1),yA}},[t,u]),h=r.useCallback(async(e,r,n,o)=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const c=u();if(!c)throw new Error("Solana RPC connection not available. Please select a Solana network.");const l=t.adapter,d=Math.floor(n*Math.pow(10,o)),h=new tS(t.publicKey),p=new tS(r),f=new tS(e),m=1e-5,g=await c.getBalance(h)/FI;if(g<m)throw new Error(`Insufficient SOL for transaction fee. You have ${g.toFixed(6)} SOL but need at least ${m} SOL for the network fee. Please add SOL to your wallet.`);try{const e=await fE(f,h,!1,qI,$I),t=await c.getTokenAccountBalance(e),r=parseFloat(t.value.uiAmount||0);if(r<n){const e=(n-r).toFixed(o);throw new Error(`Insufficient token balance. You have ${r.toFixed(o)} but need ${n.toFixed(o)}. Please add at least ${e} more tokens to your wallet.`)}}catch(a){if(a.message.includes("Insufficient"))throw a;throw new Error(`You don't have any of this token in your wallet. Please add ${n} tokens to continue.`)}const y=await fE(f,h,!1,qI,$I),v=await fE(f,p,!1,qI,$I),b=(new kS).add(yE(y,v,h,d,[],qI)),{blockhash:w,lastValidBlockHeight:x}=await c.getLatestBlockhash();b.recentBlockhash=w,b.feePayer=h;const k=await l.signTransaction(b),_=await c.sendRawTransaction(k.serialize());return s(_),i(!1),{signature:_,success:!0}}catch(yA){console.error("❌ SPL Token transaction failed:",yA);let t=yA.message||"Transaction failed";throw t.includes("Account not found")?t="Recipient token account not found. They need to have received this token before.":t.includes("insufficient")?t="Insufficient balance":t.includes("User rejected")&&(t="Transaction was rejected"),c(t),i(!1),new Error(t)}},[t,u]),p=r.useCallback(async e=>{try{const r=u();if(!r)return console.warn("⚠️ Cannot fetch SOL balance: RPC connection not available"),0;const n=new tS(e||t.publicKey);return await r.getBalance(n)/FI}catch(yA){return console.error("Error getting SOL balance:",yA),0}},[t,u]),f=r.useCallback(async(e,r)=>{try{const n=u();if(!n)return console.warn("⚠️ Cannot fetch SPL token balance: RPC connection not available"),0;const i=new tS(r||t.publicKey),o=new tS(e),s=await fE(o,i,!1,qI,$I),a=await n.getTokenAccountBalance(s);return parseFloat(a.value.uiAmount||0)}catch(yA){return console.error("Error getting SPL token balance:",yA),0}},[t,u]),m=r.useCallback(async()=>{try{const e=u();if(!e)return 5e-6;await e.getRecentBlockhash();return 5e-6}catch(yA){return console.error("Error estimating fee:",yA),5e-6}},[u]);return{isProcessing:n,txSignature:o,error:a,sendSOL:d,sendSPLToken:h,sendSplitPayment:r.useCallback(async({tokenMintAddress:e,merchantAddress:r,coinleyAddress:n,merchantAmount:o,coinleyAmount:a,decimals:l=6})=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const c=u();if(!c)throw new Error("Solana RPC connection not available. Please select a Solana network.");const p=t.adapter,f=Math.floor(o*Math.pow(10,l)),m=Math.floor(a*Math.pow(10,l)),g=o+a,y=new tS(t.publicKey),v=new tS(r),b=new tS(n),w=new tS(e),x=.01,k=await c.getBalance(y)/FI;if(k<x)throw new Error(`Insufficient SOL for transaction fee. You have ${k.toFixed(6)} SOL but need at least ${x} SOL for the network fee. Please add SOL to your wallet.`);try{const e=await fE(w,y,!1,qI,$I),t=await c.getTokenAccountBalance(e),r=parseFloat(t.value.uiAmount||0);if(r<g){const e=(g-r).toFixed(l);throw new Error(`Insufficient token balance. You have ${r.toFixed(l)} but need ${g.toFixed(l)} for this payment. Please add at least ${e} more tokens to your wallet.`)}}catch(d){if(d.message.includes("Insufficient"))throw d;throw new Error(`You don't have any of this token in your wallet. Please add ${g.toFixed(l)} tokens to continue.`)}const _=await fE(w,y,!1,qI,$I),S=await fE(w,v,!1,qI,$I),C=await fE(w,b,!1,qI,$I),I=new kS;try{await pE(c,S)}catch(h){I.add(mE(y,S,v,w,qI,$I))}try{await pE(c,C)}catch(h){I.add(mE(y,C,b,w,qI,$I))}I.add(yE(_,S,y,f,[],qI)),I.add(yE(_,C,y,m,[],qI));const{blockhash:E,lastValidBlockHeight:A}=await c.getLatestBlockhash();I.recentBlockhash=E,I.feePayer=y;const N=await p.signTransaction(I),M=await c.sendRawTransaction(N.serialize());return s(M),i(!1),{signature:M,success:!0,merchantAmount:o,coinleyAmount:a,totalAmount:g}}catch(yA){console.error("❌ Split payment failed:",yA);let t=yA.message||"Transaction failed";throw t.includes("insufficient")||t.includes("0x1")?t="Insufficient token balance":t.includes("User rejected")&&(t="Transaction was rejected"),c(t),i(!1),new Error(t)}},[t,u]),getSOLBalance:p,getSPLTokenBalance:f,estimateFee:m,resetTransaction:r.useCallback(()=>{i(!1),s(null),c(null)},[]),connection:u()}},bE=({options:e=[],value:n,onChange:i,placeholder:o,renderOption:s,getOptionKey:a,getOptionValue:c,getSearchableText:u,disabled:d=!1})=>{const[h,p]=r.useState(!1),[f,m]=r.useState(""),[g,y]=r.useState({top:0,left:0,width:400,maxHeight:450}),v=r.useRef(null),b=r.useRef(null),w=e.filter(e=>(u?u(e):"").toLowerCase().includes(f.toLowerCase())),x=e.find(e=>c(e)===n),k=()=>{if(b.current){const e=window.innerWidth,t=window.innerHeight,r=Math.min(400,e-40),n=Math.min(450,t-100);y({top:t/2-n/2,left:e/2-r/2,width:r,maxHeight:n})}};r.useEffect(()=>{const e=e=>{v.current&&!v.current.contains(e.target)&&b.current&&!b.current.contains(e.target)&&(p(!1),m(""))},t=()=>{h&&k()};if(h){k();const r=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${r}px`,document.body.style.width="100%",document.addEventListener("mousedown",e),window.addEventListener("resize",t)}return()=>{if(h){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",window.scrollTo(0,-1*parseInt(e||"0"))}document.removeEventListener("mousedown",e),window.removeEventListener("resize",t)}},[h]);const _=h&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-30 transition-opacity",style:{zIndex:999998},onClick:()=>{p(!1),m("")}}),t.jsxs("div",{ref:v,className:"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden",style:{top:g.top,left:g.left,width:g.width,maxHeight:g.maxHeight,zIndex:999999,transform:"translateZ(0)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50",children:[t.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:o||"Select Option"}),t.jsx("button",{onClick:()=>{p(!1),m("")},className:"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsx("div",{className:"p-4 border-b border-gray-200 bg-gray-50",children:t.jsx("input",{type:"text",placeholder:"Search networks and tokens...",value:f,onChange:e=>m(e.target.value),className:"w-full p-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#7042D2]/20 focus:border-[#7042D2] text-base",style:{fontFamily:"Bricolage Grotesque, sans-serif"},autoFocus:!0})}),t.jsx("div",{className:"overflow-y-auto custom-scrollbar",style:{maxHeight:(g.maxHeight||450)-180+"px",minHeight:"200px"},children:0===w.length?t.jsxs("div",{className:"p-8 text-gray-500 text-center",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"text-4xl mb-3",children:"🔍"}),t.jsx("div",{className:"text-lg mb-2",children:"No options found"}),t.jsx("div",{className:"text-sm text-gray-400",children:"Try a different search term"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("span",{className:"font-semibold",children:w.length})," option",1!==w.length?"s":""," available"]}),t.jsx("div",{className:"p-2",children:w.map(e=>t.jsx("button",{type:"button",onClick:()=>{i(c(e)),p(!1),m("")},className:"w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 "+(c(e)===n?"bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30":"text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20"),style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:s(e)},a(e)))})]})}),t.jsx("div",{className:"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center",children:t.jsx("div",{className:"text-xs text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:w.length>5?"↕️ Scroll to see more options":"✨ Select your preferred option"})})]})]});return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"relative",children:t.jsx("button",{ref:b,type:"button",onClick:()=>{d||(h||k(),p(!h))},disabled:d,className:`w-full p-4 border-2 rounded-2xl bg-gradient-to-r from-white to-gray-50 text-left focus:outline-none focus:ring-3 focus:ring-[#7042D2]/20 focus:border-[#7042D2] transition-all duration-300 ease-out shadow-lg hover:shadow-xl ${d?"opacity-50 cursor-not-allowed":"hover:border-[#7042D2]/50 cursor-pointer"} ${h?"border-[#7042D2] ring-3 ring-[#7042D2]/20":"border-gray-200"}`,style:{minHeight:"60px",fontFamily:"Bricolage Grotesque, sans-serif",fontSize:"16px",fontWeight:"500"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center space-x-3",children:x?s(x):t.jsx("span",{className:"text-gray-500",children:o})}),t.jsx("div",{className:"transform transition-transform duration-200 "+(h?"rotate-180":""),children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 text-[#7042D2]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]})})}),"undefined"!=typeof document&&document.body&&l.createPortal(_,document.body),t.jsx("style",{children:"\n .custom-scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #7042D2 #f1f1f1;\n }\n .custom-scrollbar::-webkit-scrollbar {\n width: 12px;\n }\n .custom-scrollbar::-webkit-scrollbar-track {\n background: #f8f9fa;\n border-radius: 10px;\n margin: 4px;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb {\n background: linear-gradient(180deg, #7042D2 0%, #5b34b1 100%);\n border-radius: 10px;\n border: 2px solid #f8f9fa;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb:hover {\n background: linear-gradient(180deg, #5b34b1 0%, #4c2a93 100%);\n }\n .custom-scrollbar::-webkit-scrollbar-corner {\n background: #f8f9fa;\n }\n "})]})},wE=({currentStep:e,targetStep:n,children:i,className:o="",duration:s=300})=>{const[a,c]=r.useState(e===n),[l,u]=r.useState(e===n);return r.useEffect(()=>{e===n?(u(!0),setTimeout(()=>c(!0),10)):(c(!1),setTimeout(()=>u(!1),s))},[e,n,s]),l?t.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${a?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${o}\n `,style:{transitionDuration:`${s}ms`},children:i}):null},xE=e=>parseFloat(e).toFixed(2),kE=({status:e,message:n,theme:i="light",payment:o=null,transactionHash:s=null,selectedPaymentMethod:a=null,selectedNetwork:c=null,merchantName:l="Merchant",onClose:u=null})=>{const[d,h]=r.useState(!1),[p,f]=r.useState(0);r.useEffect(()=>{if("processing"===e){const e=setInterval(()=>{f(e=>e>=90?e:e+15*Math.random())},500);return()=>clearInterval(e)}},[e]);const m=async()=>{if(s)try{await navigator.clipboard.writeText(s),h(!0),setTimeout(()=>h(!1),2e3)}catch(yA){}},g=()=>{switch(e){case"processing":return t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20"}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("div",{className:"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse"})})]});case"success":return t.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return t.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"processing"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Processing Payment"}),t.jsx("p",{className:"text-center text-gray-600 mb-6",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Your transaction has been sent to the blockchain and is being processed..."}),t.jsxs("div",{className:"w-full max-w-xs mb-4",children:[t.jsx("div",{className:"bg-gray-200 rounded-full h-3",children:t.jsx("div",{className:"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out",style:{width:`${p}%`}})}),t.jsxs("div",{className:"text-center mt-2 text-sm text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Processing... ",Math.round(p),"%"]})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Transaction submitted"})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Confirming on blockchain..."})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-gray-300 rounded-full"}),t.jsx("span",{className:"text-sm text-gray-400",children:"Finalizing payment..."})]})]}),t.jsx("div",{className:"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-800 text-center",children:"Please don't close this window. This usually takes 10-30 seconds."})})]}):"success"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Payment Successful!"}),o&&a&&t.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Your payment of ",t.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[o.totalAmount||o.amount," ",a.currency]})," has been completed."]}),s&&t.jsxs("div",{className:"w-full mb-6 px-4",children:[t.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Transaction Details"}),t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100 mb-3",onClick:m,children:[t.jsx("span",{className:"font-mono text-sm text-gray-700",children:(y=s,y?y.length<=16?y:`${y.slice(0,8)}...${y.slice(-8)}`:"")}),t.jsxs("div",{className:"flex items-center",children:[d?t.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(()=>{const e=((e,t)=>{if(!e||!t)return null;const r="string"==typeof t?t:t.shortName||t.name;return{ethereum:`https://etherscan.io/tx/${e}`,bsc:`https://bscscan.com/tx/${e}`,polygon:`https://polygonscan.com/tx/${e}`,arbitrum:`https://arbiscan.io/tx/${e}`,optimism:`https://optimistic.etherscan.io/tx/${e}`,avalanche:`https://snowtrace.io/tx/${e}`,celo:`https://celoscan.io/tx/${e}`,base:`https://basescan.org/tx/${e}`,solana:`https://explorer.solana.com/tx/${e}`,"solana-mainnet":`https://explorer.solana.com/tx/${e}`,"solana-devnet":`https://explorer.solana.com/tx/${e}?cluster=devnet`,"solana devnet":`https://explorer.solana.com/tx/${e}?cluster=devnet`}[null==r?void 0:r.toLowerCase()]||null})(s,c),r=(e=>{if(!e)return"Explorer";const t="string"==typeof e?e:e.shortName||e.name;return{ethereum:"Etherscan",bsc:"BscScan",polygon:"PolygonScan",arbitrum:"Arbiscan",optimism:"Optimistic Etherscan",avalanche:"SnowTrace",celo:"CeloScan",base:"BaseScan",solana:"Solana Explorer","solana-mainnet":"Solana Explorer","solana-devnet":"Solana Explorer (Devnet)","solana devnet":"Solana Explorer (Devnet)"}[null==t?void 0:t.toLowerCase()]||"Explorer"})(c);return c&&e&&t.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 w-full p-3 rounded-lg border border-[#7042D2] bg-white hover:bg-purple-50 transition-colors group",children:[t.jsxs("span",{className:"text-sm font-medium text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["View on ",r]}),t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})()]}),u&&t.jsx("button",{onClick:u,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Close"})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[t.jsx("div",{className:"mb-4",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),t.jsx("p",{className:"text-center text-gray-600",children:n})]});var y},_E={bitcoin:1,ethereum:1027,bsc:1839,polygon:3890,cardano:2010,avalanche:5805,fantom:3513,arbitrum:11841,optimism:11840,USDT:825,USDC:3408,BUSD:4687,DAI:4943,FRAX:6952,TUSD:2563,USDP:5992,USDD:5994,FDUSD:26081,PYUSD:28295,WBTC:3717,LINK:1975,UNI:7083,AAVE:7278,COMP:5692,YFI:5864,MKR:1518,SUSHI:6758,CRV:6538,SNX:2586,UMA:5617,BAL:5728,MANA:1966,SAND:6210,APE:18876,LDO:8e3,GRT:6719,ENS:13855,RPL:2943,SHIB:5994,MATIC:3890,BNB:1839,ADA:2010,SOL:5426,DOT:6636,AVAX:5805,TRX:1958,ALGO:4030,FTM:3513,ARB:11841,OP:11840,"1INCH":8104,DYDX:11156,ICP:8916,FIL:2280,CAKE:7186,RUNE:4157,ALPHA:7232,BNT:1727,KNC:1982,ZRX:1896,REN:2539,LRC:1934,WETH:2396,WMATIC:3890,WBNB:1839,UST:7129,USTC:7129,LUSD:8115,MIM:9681,FEI:8642,TRIBE:8741,RAI:8525,SUSD:2927},SE={ethereum:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bsc:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",polygon:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arbitrum:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avalanche:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",celo:"https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png",optimism:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",base:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",eth:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bnb:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",trx:"https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png",algo:"https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png",matic:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arb:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avax:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",op:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",sol:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png",solana:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png","solana-mainnet":"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png","solana-devnet":"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png"},CE={metamask:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",coinbase:"https://avatars.githubusercontent.com/u/18060234?s=280&v=4",rabby:"https://rabby.io/logo-128.png",zerion:"https://app.zerion.io/favicon-32x32.png",okx:"https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png",binance:"https://bin.bnbstatic.com/static/images/common/favicon.ico",cryptocom:"https://crypto.com/favicon.ico","1inch":"https://1inch.io/favicon.svg",hot:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==",phantom:"https://phantom.app/img/phantom-logo.svg",solflare:"https://solflare.com/assets/logo.svg",backpack:"https://www.backpack.exchange/_next/image?url=%2Fbackpack-logo.png&w=128&q=75",trust:"https://trustwallet.com/assets/images/favicon.png",default:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=="},IE=e=>(e=>{if(!e)return null;const t=_E[e.toUpperCase()];return t?`https://s2.coinmarketcap.com/static/img/coins/64x64/${t}.png`:null})(e),EE=e=>"object"==typeof e&&(null==e?void 0:e.logo)?e.logo:"object"==typeof e&&(null==e?void 0:e.shortName)?SE[e.shortName.toLowerCase()]:"string"==typeof e?SE[e.toLowerCase()]:null,AE=(e,t)=>{const r=e.toLowerCase(),n=t.toLowerCase();for(const[i,o]of Object.entries(CE))if(r.includes(i)||n.includes(i))return o;return CE.default},NE=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),ME=e=>{switch(e){case"trust":return window.ethereum&&!0===window.ethereum.isTrust;case"metaMask":return window.ethereum&&!0===window.ethereum.isMetaMask;case"injected":return window.ethereum&&!window.ethereum.isMetaMask&&!window.ethereum.isCoinbaseWallet;default:return!1}},PE=(e,t)=>{if(!t)return[];if(!["ethereum","bsc","polygon","arbitrum","optimism","avalanche","celo","base"].includes(t.shortName))return[];return[...(e||[]).map(e=>(e=>({type:e.id,name:e.name,icon:AE(e.name,e.id),description:`Connect using ${e.name}`,isInstalled:!0,connector:e,isWagmi:!0}))(e)),...NE()?[{type:"trust",name:"Trust Wallet",icon:"🛡️",description:"Multi-chain wallet with transaction deep links",isInstalled:!1,connector:null,isWagmi:!1,mobileOnly:!0,hasTransactionDeepLinks:!0}]:[]]},TE=(e,t,r,n,i="metamask",o=null)=>{if(!e)return null;try{const t="https://payment.coinley.io",n=new URLSearchParams,o=(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId);if(!o)return null;n.set("paymentId",o),n.set("preferredWallet",i),n.set("isMobile","true");const s=`${t}?${n.toString()}`;let a;switch(i){case"metamask":a=`https://metamask.app.link/dapp/${s.replace("https://","")}`;break;case"trust":const e=(null==r?void 0:r.chainId)||1;a=`https://link.trustwallet.com/open_url?coin_id=${(e=>{const t="string"==typeof e&&e.startsWith("0x")?parseInt(e,16):parseInt(e);return[1,56,137,42161,10,43114,42220,8453].includes(t)?60:{}[t]||60})(e)}&url=${encodeURIComponent(s)}`;break;case"coinbase":a=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(s)}`;break;default:a=s}return a}catch(ud){return null}},OE=(e,t)=>{if(!t)return null;try{switch(e){case"metamask":return t.includes("metamask.app.link")?t:`https://metamask.app.link/dapp/${t.replace("https://","")}`;case"trust":return t.includes("link.trustwallet.com")?t:`https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(t)}`;case"coinbase":return t.includes("go.cb-w.com")?t:`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t)}`;default:return t}}catch(ud){return t}},BE=Object.freeze(Object.defineProperty({__proto__:null,generateMobilePaymentDeepLink:OE,generateQRPaymentURI:TE},Symbol.toStringTag,{value:"Module"})),RE=({walletAddress:e,amount:n,currency:i,network:o,theme:s="light",paymentData:a=null,onPaymentDetected:c=null,config:l=null,selectedToken:d=null,selectedNetwork:h=null,preferredWallet:p="metamask",compact:f=!1})=>{const[m,g]=r.useState(""),[y,v]=r.useState(""),[b,w]=r.useState(!0),[x,k]=r.useState(!1),[_,S]=r.useState(!1),C=r.useRef(null);return r.useEffect(()=>{(async()=>{if(null==a?void 0:a.id){w(!0);try{if(!d||!d.contractAddress)throw new Error("Cannot generate QR code: Token contract address required");if(!h||!h.chainId)throw new Error("Cannot generate QR code: Network chain ID required");const e=TE(a,0,h,0,p);if(e.includes("metamask.app.link")||e.includes("link.trustwallet.com")||e.includes("go.cb-w.com"),!e)throw new Error("Failed to generate Coinley payment URL");g(e);const t=NE(),r=await u.toDataURL(e,{width:f?140:t?350:280,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===s?"#FFFFFF":"#000000",light:"dark"===s?"#000000":"#FFFFFF"}});v(r),w(!1)}catch(ud){w(!1)}}else w(!1)})()},[a,n,i,o,s,d,h,l,p]),r.useEffect(()=>()=>{C.current&&clearInterval(C.current)},[]),t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex gap-3 items-start w-full mb-2",children:[t.jsx("div",{className:"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0",children:b?t.jsx("div",{className:"flex items-center justify-center",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1"}),t.jsx("div",{className:"text-xs text-gray-600",children:"Generating..."})]})}):y?t.jsx("img",{src:y,alt:"Payment QR Code",className:"rounded-lg",style:{width:140,height:140}}):t.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center p-2",children:[t.jsx("div",{className:"text-lg mb-1",children:"⚠️"}),t.jsx("div",{className:"text-xs text-gray-600",children:(null==a?void 0:a.id)?"QR Failed":"Payment not created"})]})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-center",children:[t.jsxs("div",{className:"p-2 bg-gray-50 rounded-lg mb-2",children:[t.jsxs("div",{className:"flex justify-between items-center mb-1",children:[t.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"text-sm font-bold text-[#7042D2]",children:[n," ",i]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),t.jsx("span",{className:"text-xs font-medium text-gray-700",children:o})]})]}),_?t.jsxs("div",{className:"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg",children:[t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Payment Received!"]}):t.jsx("div",{className:"p-1.5 rounded-lg bg-blue-50 border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-700 text-center leading-tight",children:"📱 Scan with phone camera"})})]})]})})},jE=({selectedNetwork:e,onWalletSelect:i,onConnect:o,connectedWallet:s,loading:a,paymentData:c=null,selectedToken:l=null,api:u=null,onSolanaConnect:d=null,solanaWallet:h=null})=>{const[p,f]=r.useState(null),m=r.useMemo(()=>e?bm(e.type||e.shortName||e.id):fm,[e])===mm,{connectors:g}=n.useConnect(),{isConnected:y,address:v}=n.useAccount(),b=r.useMemo(()=>m?h.availableWallets.map(e=>({type:e.id,name:e.name,icon:AE(e.name,e.id)||"🔗",description:e.adapter?"Available":"Not installed",isSolana:!0,wallet:e})):PE(g,e),[m,h.availableWallets,g,e]),w=async(t,r)=>{if(NE())if(c)try{const{generateQRPaymentURI:n,generateMobilePaymentDeepLink:i}=await Promise.resolve().then(()=>BE),o=n(c,l,e,(null==u?void 0:u.config)||{},r);if(!o)throw new Error("Failed to generate payment URL");const s=i(r,o);if(!s)throw new Error(`Failed to generate ${t.name} deep link`);window.location.href=s}catch(ud){alert(`Failed to open ${t.name}: ${ud.message}`)}else alert("Please create a payment first before selecting a mobile wallet.");else alert(`Please install ${t.name} mobile app or use the browser extension if available.`)};return e?0===b.length?t.jsxs("div",{className:"text-center p-4",children:[t.jsxs("p",{className:"text-gray-500 mb-4",children:["No compatible wallets found for ",e.name]}),t.jsx("div",{className:"p-3 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-sm text-amber-800",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"font-medium mb-2",children:"Install a compatible wallet:"}),t.jsx("div",{className:"space-y-1 text-xs",children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:["• ",t.jsx("a",{href:dm.PHANTOM.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Phantom Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:dm.SOLFLARE.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Solflare Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:dm.BACKPACK.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Backpack Wallet"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://metamask.io/download/",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install MetaMask Wallet"})]}),t.jsxs("div",{children:["• ",t.jsx("a",{href:"https://www.coinbase.com/wallet",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Coinbase Wallet"})]})]})})]})})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Select Wallet for ",e.name]}),t.jsx(bE,{options:b,value:(null==s?void 0:s.walletType)||p||"",onChange:async e=>{f(e);const t=b.find(t=>t.type===e);if(t){if(i(e),t.isSolana){try{const t=await h.connectWallet(e);d&&await d({walletType:e,publicKey:t,wallet:h})}catch(ud){console.error("Failed to connect Solana wallet:",ud),alert(`Failed to connect: ${ud.message}`)}return}t.isWagmi&&t.connector?await o(t.connector):t.isWagmi||await w(t,e)}},placeholder:"Choose your wallet...",renderOption:e=>{var r,n,i,o,c,l,u;return t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsxs("div",{className:"w-8 h-8 flex items-center justify-center",children:[e.icon.startsWith("http")||e.icon.startsWith("data:")?t.jsx("img",{src:e.icon,alt:e.name,className:"w-6 h-6 rounded-full object-contain",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="block"}}):t.jsx("div",{className:"text-2xl",children:e.icon}),t.jsx("div",{className:"text-xl",style:{display:"none"},children:"🔗"})]}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800 flex items-center",children:[e.name,!e.isSolana&&ME(e.type)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),e.isSolana&&(null==(r=e.wallet)?void 0:r.adapter)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),e.isSolana&&(null==(n=h.connectedWallet)?void 0:n.id)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"}),!e.isSolana&&(null==s?void 0:s.walletType)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.isSolana&&(null==(i=h.connectedWallet)?void 0:i.id)===e.type?`Connected • ${null==(o=h.publicKey)?void 0:o.slice(0,6)}...${null==(c=h.publicKey)?void 0:c.slice(-4)}`:(null==s?void 0:s.walletType)===e.type?`Connected • ${null==(l=s.account)?void 0:l.slice(0,6)}...${null==(u=s.account)?void 0:u.slice(-4)}`:e.description})]}),a&&p===e.type&&t.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]"})]})},getOptionKey:e=>e.type,getOptionValue:e=>e.type,getSearchableText:e=>`${e.name} ${e.description}`,disabled:a})]}):t.jsx("div",{className:"text-center p-4",children:t.jsx("p",{className:"text-gray-500",children:"Please select a network first"})})},LE=(()=>{if(void 0!==ae&&ae.env)return!1;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.includes("192.168.")}return!1})()||(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search);return"true"===e.get("debug")||"true"===e.get("debugMode")}return!1})(),DE=({paymentData:e,selectedToken:n,selectedNetwork:i,config:o,onPaymentStarted:s=()=>{},onError:a=()=>{}})=>{var c,l;const[u,d]=r.useState(null),[h,p]=r.useState(!1),[f,m]=r.useState([]),[g,y]=r.useState(!1),[v,b]=r.useState(0);r.useEffect(()=>{var t,r,o;(null==e?void 0:e.id)&&(null==n?void 0:n.contractAddress)&&(null==i?void 0:i.chainId)&&((null==(t=null==e?void 0:e.contractCall)?void 0:t.contractAddress)||(null==e?void 0:e.contractAddress))?w("success","✅ Payment data complete",{paymentId:e.id,tokenContract:n.contractAddress,chainId:i.chainId,paymentContract:(null==(o=null==e?void 0:e.contractCall)?void 0:o.contractAddress)||(null==e?void 0:e.contractAddress)}):(w("debug","⏳ Waiting for complete payment data",{hasPaymentId:!!(null==e?void 0:e.id),hasTokenContract:!!(null==n?void 0:n.contractAddress),hasChainId:!!(null==i?void 0:i.chainId),hasPaymentContract:!(!(null==(r=null==e?void 0:e.contractCall)?void 0:r.contractAddress)&&!(null==e?void 0:e.contractAddress)),checkCount:v}),b(e=>e+1))},[e,n,i,v]);const w=(e,t,r=null)=>{const n=(new Date).toLocaleTimeString(),i={id:Date.now()+Math.random(),type:e,message:t,data:r,timestamp:n};LE&&(m(e=>[...e,i].slice(-20)),e.toUpperCase())},x=[{id:"metamask",name:"MetaMask",icon:"🦊",description:"Connect with MetaMask mobile"},{id:"trust",name:"Trust Wallet",icon:"🛡️",description:"Connect with Trust Wallet"},{id:"coinbase",name:"Coinbase Wallet",icon:"💙",description:"Connect with Coinbase Wallet"}];if(!e)return t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⚠️ Payment Required"}),t.jsx("div",{className:"text-sm text-amber-700",children:"Please create a payment before selecting a wallet"})]})});const k=(null==e?void 0:e.id)&&(null==n?void 0:n.contractAddress)&&(null==i?void 0:i.chainId)&&((null==(c=null==e?void 0:e.contractCall)?void 0:c.contractAddress)||(null==e?void 0:e.contractAddress));return t.jsx("div",{className:"space-y-4",children:k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Select Mobile Wallet"}),t.jsx(bE,{options:x,value:u||"",onChange:async t=>{const r=x.find(e=>e.id===t);if(r){d(t),p(!0);try{if(w("info",`🚀 Mobile wallet selected: ${r.name}`),!e)throw new Error("Payment data not available. Please create payment first.");w("debug","🔍 Payment Data Check",{hasPaymentData:!!e,hasSelectedToken:!!n,hasSelectedNetwork:!!i,hasConfig:!!o,paymentId:(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId),tokenAddress:null==n?void 0:n.contractAddress,networkChainId:null==i?void 0:i.chainId,amount:(null==e?void 0:e.totalAmount)||(null==e?void 0:e.amount)||(null==o?void 0:o.amount)});const a=TE(e,0,i,0,t);if(!a)throw new Error("Failed to generate payment URL");w("success","📱 Generated payment URL",{url:a,length:a.length});const c=OE(t,a);if(!c)throw new Error(`Failed to generate ${r.name} deep link`);w("success",`🔗 Deep link generated for ${r.name}`,{deepLink:c}),s({walletType:t,walletName:r.name,paymentUrl:a,deepLink:c}),setTimeout(()=>{w("info",`📱 Opening ${r.name}...`),window.location.href=c},500)}catch(ud){w("error","❌ Mobile wallet connection failed",{error:ud.message,walletId:t,hasPaymentData:!!e,hasSelectedToken:!!n,hasSelectedNetwork:!!i}),a(ud.message),p(!1),d(null)}}},placeholder:"Choose your wallet...",renderOption:e=>t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsx("div",{className:"w-8 h-8 flex items-center justify-center",children:t.jsx("div",{className:"text-2xl",children:e.icon})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name,u===e.id&&h&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse",children:"Opening..."})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.description})]})]}),getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.description}`,disabled:h}),t.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"Select a wallet to open it with your payment details"})]}),h&&u&&t.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse",children:t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"}),t.jsxs("div",{className:"text-sm text-blue-700",children:["Opening ",null==(l=x.find(e=>e.id===u))?void 0:l.name,"..."]})]})}),t.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[t.jsxs("div",{className:"flex justify-between items-center text-sm",children:[t.jsx("span",{className:"text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"font-semibold text-gray-800",children:[e.totalAmount," ",(null==n?void 0:n.symbol)||"USDC"]})]}),t.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[t.jsx("span",{className:"text-gray-600",children:"Network:"}),t.jsx("span",{className:"text-gray-800",children:(null==i?void 0:i.name)||"Ethereum"})]})]}),t.jsx("div",{className:"p-3 bg-purple-50 border border-purple-200 rounded-lg",children:t.jsxs("div",{className:"text-xs text-purple-700",children:[t.jsx("div",{className:"font-medium mb-1",children:"📱 Mobile Payment"}),t.jsx("div",{children:"Your selected wallet app will open with payment details pre-filled"})]})}),LE&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("button",{onClick:()=>y(!g),className:"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors",children:[g?"🔽 Hide Debug Info":"🔧 Show Debug Info"," (",f.length," logs)"]}),g&&t.jsxs("div",{className:"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto",children:[t.jsx("div",{className:"text-white mb-2 font-bold",children:"📱 Mobile Debug Panel"}),0===f.length?t.jsx("div",{className:"text-gray-400",children:"No debug logs yet. Try selecting a wallet..."}):f.map(e=>t.jsxs("div",{className:"mb-3 pb-2 border-b border-gray-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"px-2 py-1 rounded text-xs font-bold "+("error"===e.type?"bg-red-600 text-white":"success"===e.type?"bg-green-600 text-white":"debug"===e.type?"bg-blue-600 text-white":"bg-gray-600 text-white"),children:e.type.toUpperCase()}),t.jsx("span",{className:"text-gray-400",children:e.timestamp})]}),t.jsx("div",{className:"text-yellow-300 mb-1",children:e.message}),e.data&&t.jsx("div",{className:"text-gray-300 text-xs",children:t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer text-blue-300 hover:text-blue-200",children:"📊 Data"}),t.jsx("pre",{className:"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(e.data,null,2)})]})})]},e.id)),t.jsx("button",{onClick:()=>m([]),className:"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700",children:"Clear Logs"})]})]})]}):t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"⏳ Preparing Payment..."}),t.jsx("div",{className:"text-sm text-amber-700",children:"Payment is being prepared. Please wait a moment..."}),t.jsx("div",{className:"mt-3",children:t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto"})})]})})})},UE=({error:e,onRetry:r,onDismiss:n,context:i="payment",className:o=""})=>{if(!e)return null;const s=Gv(e),a=(e=>{switch(e){case"user_rejected":return"info";case"insufficient_funds":case"wrong_network":case"wallet_disconnected":case"payment_pending":return"warning";case"network_error":case"gas_error":case"rate_limited":return"error";default:return"critical"}})(s.type),c=(e=>{switch(e){case"user_rejected":default:return"Try Again";case"insufficient_funds":return"Add Funds & Retry";case"wrong_network":return"Switch Network & Retry";case"wallet_disconnected":return"Reconnect Wallet";case"payment_pending":return"Check Again";case"network_error":case"rate_limited":return"Retry";case"popup_blocked":return"Allow Popups & Retry";case"mobile_wallet_error":return"Open Wallet App"}})(s.type),l={info:{container:"bg-blue-50 border-blue-200",title:"text-blue-800",message:"text-blue-700",icon:"ℹ️",button:"bg-blue-600 hover:bg-blue-700"},warning:{container:"bg-amber-50 border-amber-200",title:"text-amber-800",message:"text-amber-700",icon:"⚠️",button:"bg-amber-600 hover:bg-amber-700"},error:{container:"bg-red-50 border-red-200",title:"text-red-800",message:"text-red-700",icon:"❌",button:"bg-red-600 hover:bg-red-700"},critical:{container:"bg-red-50 border-red-300",title:"text-red-900",message:"text-red-800",icon:"🚨",button:"bg-red-700 hover:bg-red-800"}},u=l[a]||l.error;return t.jsxs("div",{className:`p-4 border rounded-lg ${u.container} ${o}`,children:[t.jsxs("div",{className:"flex items-start space-x-3",children:[t.jsx("div",{className:"flex-shrink-0 text-xl",children:u.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:`font-semibold ${u.title} mb-1`,children:s.title}),t.jsx("div",{className:`text-sm ${u.message} mb-2`,children:s.message}),s.suggestion&&t.jsxs("div",{className:`text-xs ${u.message} opacity-90`,children:["💡 ",s.suggestion]})]}),n&&t.jsx("button",{onClick:n,className:"flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Dismiss error",children:t.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:t.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),r&&t.jsxs("div",{className:"mt-3 flex justify-end space-x-2",children:[n&&"info"===a&&t.jsx("button",{onClick:n,className:"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:r,className:`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${u.button}`,children:c})]}),!1]})},FE="method",zE="confirm",qE="processing",$E="success",WE="wallet",HE="qr",GE="deposit",VE="Bricolage Grotesque, sans-serif",KE=({depositAddress:e,amount:n,currency:i,network:o,networkName:s,paymentId:a,expiresAt:c,requiredConfirmations:l=20,theme:d="light",api:h=null,onPaymentDetected:p=null,onPaymentConfirmed:f=null,onPaymentProcessing:m=null,onExpired:g=null,explorerUrl:y=null})=>{const[v,b]=r.useState(""),[w,x]=r.useState(!0),[k,_]=r.useState(!1),[S,C]=r.useState("awaiting"),[I,E]=r.useState("0"),[A,N]=r.useState(0),[M,P]=r.useState(null),[T,O]=r.useState(!1),[B,R]=r.useState(null),[j,L]=r.useState(null),D=r.useRef(null),U=r.useRef(null),F=r.useRef(!1),z=r.useRef(!1),q=NE();r.useEffect(()=>{(async()=>{if(e){x(!0);try{const t=await u.toDataURL(e,{width:q?200:180,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===d?"#FFFFFF":"#000000",light:"dark"===d?"#1F2937":"#FFFFFF"}});b(t),x(!1)}catch(ud){console.error("Failed to generate QR code:",ud),x(!1)}}else x(!1)})()},[e,d,q]),r.useEffect(()=>{if(!c)return;const e=()=>{const e=(new Date).getTime(),t=new Date(c).getTime()-e;if(t<=0)return O(!0),P(null),void(g&&g());const r=Math.floor(t%36e5/6e4),n=Math.floor(t%6e4/1e3);P(`${r}:${n.toString().padStart(2,"0")}`)};return e(),U.current=setInterval(e,1e3),()=>{U.current&&clearInterval(U.current)}},[c,g]);const $=r.useCallback(async()=>{if(h&&a&&"confirmed"!==S&&"swept"!==S)try{const t=await h.getDepositBalance(a);let r=!1,i="0";t.success&&(i=t.balance||"0",E(i),r=t.isComplete,parseFloat(i)>0&&"awaiting"===S&&(C("detected"),p&&p(t)),r&&"confirming"!==S&&"confirmed"!==S&&(C("confirming"),j||L(Date.now()),!F.current&&m&&(F.current=!0,m({balance:i,expectedAmount:n,depositAddress:e,paymentId:a}))));const o=await h.getDepositStatus(a);let s=null;if(o.success&&o.payment){const e=o.payment;s=e.status,N(e.confirmations||0),e.depositTxHash&&R(e.depositTxHash);const t="completed"===e.status||"swept"===e.status,r=e.depositTxHash||e.sweepTxHash||e.transactionHash;if(t&&r&&!z.current&&(z.current=!0,C("swept"===e.status?"swept":"confirmed"),f)){const t={...e,transactionHash:e.depositTxHash||e.sweepTxHash||e.transactionHash};f(t)}e.sweptAt&&"swept"!==S&&C("swept")}if(r&&j&&!z.current&&B){const t=Date.now()-j;t>=3e4&&(z.current=!0,C("confirmed"),f&&f({id:a,status:"completed",depositAddress:e,amount:i,depositTxHash:B,transactionHash:B,confirmations:A||l,sdkConfirmed:!0,confirmedAt:(new Date).toISOString()}))}}catch(ud){console.warn("Failed to check deposit status:",ud.message)}},[h,a,S,n,e,A,B,j,l,p,f,m]);r.useEffect(()=>{if(h&&a&&!T)return $(),D.current=setInterval($,5e3),()=>{D.current&&clearInterval(D.current)}},[h,a,T,$]);const W=(()=>{if(T)return{message:"Payment expired",color:"text-red-600",bgColor:"bg-red-50",icon:"⏰"};switch(S){case"detected":case"confirming":return{message:"Transfer detected! Processing...",color:"text-blue-600",bgColor:"bg-blue-50",icon:"⏳"};case"confirmed":return{message:"Payment confirmed!",color:"text-green-600",bgColor:"bg-green-50",icon:"✅"};case"swept":return{message:"Payment complete - Funds delivered!",color:"text-green-600",bgColor:"bg-green-50",icon:"🎉"};default:return{message:"Send exact amount to address below",color:"text-gray-600",bgColor:"bg-gray-50",icon:"📤"}}})(),H="dark"===d;return t.jsxs("div",{className:"flex flex-col items-center w-full",style:{fontFamily:VE},children:[t.jsx("div",{className:`w-full p-3 rounded-lg mb-4 ${W.bgColor} border ${H?"border-gray-600":"border-gray-200"}`,children:t.jsxs("div",{className:`flex items-center justify-center ${W.color} font-medium`,children:[t.jsx("span",{className:"mr-2",children:W.icon}),W.message]})}),t.jsxs("div",{className:`flex ${q?"flex-col":"flex-row"} gap-4 w-full`,children:[t.jsx("div",{className:"flex-shrink-0 "+(q?"mx-auto":""),children:t.jsx("div",{className:`p-2 rounded-xl ${H?"bg-gray-800":"bg-white"} shadow-md border ${H?"border-gray-700":"border-gray-200"}`,children:w?t.jsx("div",{className:"flex items-center justify-center",style:{width:q?200:180,height:q?200:180},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600 mx-auto mb-2"}),t.jsx("div",{className:"text-sm "+(H?"text-gray-400":"text-gray-600"),children:"Generating..."})]})}):v?t.jsx("img",{src:v,alt:"Transfer Address QR",className:"rounded-lg",style:{width:q?200:180,height:q?200:180}}):t.jsx("div",{className:"flex items-center justify-center rounded-lg "+(H?"bg-gray-700":"bg-gray-100"),style:{width:q?200:180,height:q?200:180},children:t.jsx("span",{className:"text-sm "+(H?"text-gray-400":"text-gray-500"),children:"QR unavailable"})})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-between",children:[t.jsxs("div",{className:`p-3 rounded-lg mb-3 ${H?"bg-gray-800":"bg-purple-50"} border ${H?"border-gray-700":"border-purple-200"}`,children:[t.jsx("div",{className:"text-xs font-medium mb-1 "+(H?"text-gray-400":"text-purple-600"),children:"Send Exactly:"}),t.jsxs("div",{className:"text-2xl font-bold text-[#7042D2]",children:[n," ",i]}),t.jsxs("div",{className:"text-xs mt-1 "+(H?"text-gray-400":"text-gray-500"),children:["on ",s||o]})]}),t.jsxs("div",{className:`p-3 rounded-lg ${H?"bg-gray-800":"bg-gray-50"} border ${H?"border-gray-700":"border-gray-200"}`,children:[t.jsx("div",{className:"text-xs font-medium mb-2 "+(H?"text-gray-400":"text-gray-600"),children:"Transfer Address:"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("code",{className:`flex-1 text-xs font-mono break-all p-2 rounded ${H?"bg-gray-900 text-gray-300":"bg-white text-gray-800"} border ${H?"border-gray-700":"border-gray-300"}`,children:e}),t.jsx("button",{onClick:async()=>{try{await navigator.clipboard.writeText(e),_(!0),setTimeout(()=>_(!1),2e3)}catch(ud){console.error("Failed to copy:",ud)}},className:"p-2 rounded-lg transition-colors "+(k?"bg-green-500 text-white":H?"bg-gray-700 text-gray-300 hover:bg-gray-600":"bg-gray-200 text-gray-700 hover:bg-gray-300"),title:k?"Copied!":"Copy address",children:k?t.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}):t.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})})]})]}),t.jsxs("div",{className:"flex gap-2 mt-3",children:[M&&!T&&"awaiting"===S&&t.jsxs("div",{className:`flex-1 p-2 rounded-lg text-center ${H?"bg-gray-800":"bg-orange-50"} border ${H?"border-gray-700":"border-orange-200"}`,children:[t.jsx("div",{className:"text-xs "+(H?"text-gray-400":"text-orange-600"),children:"Expires in"}),t.jsx("div",{className:"text-lg font-bold "+(H?"text-orange-400":"text-orange-600"),children:M})]}),parseFloat(I)>0&&t.jsxs("div",{className:`flex-1 p-2 rounded-lg text-center ${H?"bg-gray-800":"bg-green-50"} border ${H?"border-gray-700":"border-green-200"}`,children:[t.jsx("div",{className:"text-xs "+(H?"text-gray-400":"text-green-600"),children:"Received"}),t.jsxs("div",{className:"text-lg font-bold "+(H?"text-green-400":"text-green-600"),children:[I," ",i]})]})]})]})]}),B&&y&&t.jsx("div",{className:"w-full mt-4",children:t.jsxs("a",{href:`${y}/tx/${B}`,target:"_blank",rel:"noopener noreferrer",className:`flex items-center justify-center gap-2 p-2 rounded-lg ${H?"bg-gray-800 text-blue-400 hover:bg-gray-700":"bg-blue-50 text-blue-600 hover:bg-blue-100"} transition-colors`,children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),"View transaction on explorer"]})}),t.jsxs("div",{className:`w-full mt-4 p-3 rounded-lg ${H?"bg-gray-800 border-gray-700":"bg-gray-50 border-gray-200"} border`,children:[t.jsx("div",{className:"text-xs font-medium mb-2 "+(H?"text-gray-300":"text-gray-700"),children:"📋 Instructions:"}),t.jsxs("ol",{className:"text-xs space-y-1 "+(H?"text-gray-400":"text-gray-600"),children:[t.jsx("li",{children:"1. Copy the transfer address or scan QR code"}),t.jsxs("li",{children:["2. Send ",t.jsxs("strong",{children:[n," ",i]})," from any wallet"]}),t.jsxs("li",{children:["3. Wait for ",l," confirmations"]}),t.jsx("li",{children:"4. Payment will be automatically confirmed"})]})]})]})},ZE=new i.QueryClient,YE=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,config:s,onSuccess:a,onError:c,onClose:l,isOpen:u,theme:d="light"})=>{var h;const p=sm(o,e||n,e?null:i),f=wm(),m=Jv(),g=r.useMemo(()=>p.selectedNetwork?bm(p.selectedNetwork.type||p.selectedNetwork.shortName||p.selectedNetwork.id):fm,[p.selectedNetwork])===mm,y=r.useMemo(()=>!(!g||!p.selectedNetwork)&&(e=>{if(!e)return!1;const t=!0===e.isTestnet||"true"===e.isTestnet,r=(e.name||"").toLowerCase().includes("devnet"),n=(e.shortName||"").toLowerCase().includes("devnet"),i=(e.type||"").toLowerCase().includes("devnet"),o=(e.id||"").toLowerCase().includes("devnet");return t||r||n||i||o})(p.selectedNetwork),[g,p.selectedNetwork]),v=r.useMemo(()=>{if(!g||!p.selectedNetwork)return[];return pm()},[g,p.selectedNetwork,y]),b=vE(v,m.connectedWallet),[w,x]=r.useState("metamask"),[k,_]=r.useState(!1),[S,C]=r.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[I,E]=r.useState(!1);r.useEffect(()=>{_(NE())},[]);const{currentStep:A,networks:N,tokens:M,selectedNetwork:P,selectedToken:T,paymentData:O,loading:B,error:R,paymentType:j,loadData:L,createPayment:D,createDepositPayment:U,isDepositSupported:F,failPayment:z,resetState:q,setSelectedNetwork:$,setSelectedToken:W,setPaymentType:H,setCurrentStep:G,setError:V}=p,{connectedWallet:K,address:Z,connectWallet:Y,handleWalletSelection:J,resetState:X}=f,Q=Yv(O,T,P,Z,p.api,f),{executePaymentTransaction:ee,processFinalPayment:te,transactionStep:re,transactionError:ne,currentTransactionHash:ie}=Q;r.useEffect(()=>{A===$E&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[A]),r.useEffect(()=>{if(u){L(),q(),em.trackModalOpened(null==s?void 0:s.merchantName,null==s?void 0:s.amount);const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[u]),r.useEffect(()=>{if("processing"===re||"approve"===re||"splitPayment"===re){const e=setTimeout(()=>{V("Transaction timed out. Please try again."),G(zE),Q.resetTransaction()},12e4);return()=>clearTimeout(e)}},[re]),r.useEffect(()=>{if(A!==qE||j!==GE||!(null==O?void 0:O.id))return;const e=setInterval(async()=>{try{const t=await p.api.getDepositStatus(O.id);if(t.success&&t.payment){const r=t.payment.status,n=t.payment.depositTxHash||t.payment.sweepTxHash||t.payment.transactionHash;"completed"!==r&&"swept"!==r||!n?("completed"!==r&&"swept"!==r||n)&&("failed"!==r&&"sweep_failed"!==r||(clearInterval(e),V("Payment failed. Please try again."),G(zE))):(clearInterval(e),G($E),a&&a({paymentId:O.id,transactionHash:n,depositAddress:t.payment.depositAddress,network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:t.payment}))}}catch(t){console.warn("[DepositPolling] Error checking status:",t.message)}},5e3);return()=>{clearInterval(e)}},[A,j,null==O?void 0:O.id,P,T,a]);const oe=()=>{var e;Q.resetTransaction(),null==(e=b.resetTransaction)||e.call(b),null==X||X(),V(""),E(!1),C(!1),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started"),"undefined"!=typeof window&&(window.coinleyPendingSplitPayment=null)},se=async()=>{em.trackModalClosed("user_cancelled"),oe(),await z(),l()},ae={ethereum:{text:"High fees",color:"text-red-500"},polygon:{text:"~$0.01 fees",color:"text-green-500"},bsc:{text:"~$0.02 fees",color:"text-green-500"},base:{text:"~$0.03 fees",color:"text-green-500"},optimism:{text:"~$0.60 fees",color:"text-yellow-600"},arbitrum:{text:"~$0.50 fees",color:"text-yellow-600"},avalanche:{text:"Low fees",color:"text-green-500"},celo:{text:"Low fees",color:"text-green-500"},solana:{text:"~$0.001 fees",color:"text-green-500"}};return u?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:se,"aria-hidden":"true"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"relative pt-4 w-full max-w-md max-h-[90vh] mx-auto shadow-xl bg-gray-100 rounded-3xl flex flex-col overflow-hidden",style:{zIndex:52},children:[t.jsxs("div",{className:"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full",children:[t.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[t.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",children:t.jsx("img",{src:tm,alt:"Coinley"})}),t.jsx("span",{className:"text-base font-semibold text-gray-800",style:{fontFamily:VE},children:"Payment Details"})]}),A!==$E&&A!==qE&&t.jsx("button",{onClick:se,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),s&&A!==$E&&t.jsx("div",{className:"flex-shrink-0 mb-3 px-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-xs text-gray-600",children:"Total Amount"}),t.jsxs("div",{className:"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight",style:{fontFamily:VE},children:["$",xE(s.amount)]}),t.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"No additional fees"}),t.jsx("div",{className:"text-xs text-gray-600 mt-2",children:"Payment to:"}),t.jsxs("div",{className:"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center",style:{fontFamily:VE},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),s.merchantName||"Merchant"]})]})}),t.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[t.jsx(wE,{currentStep:A,targetStep:FE,children:t.jsxs("div",{className:"pb-4 pt-3 px-5 bg-white rounded-t-2xl",children:[t.jsx("h3",{className:"font-semibold text-center mb-3 text-sm",style:{fontFamily:VE},children:"Choose Payment Method"}),t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:VE},children:"Select Network"}),t.jsx(bE,{options:N,value:(null==P?void 0:P.id)||"",onChange:e=>{const t=N.find(t=>t.id===e);oe(),$(t),W(null),em.trackNetworkSelected(null==t?void 0:t.name,null==s?void 0:s.merchantName)},placeholder:"Choose your network...",renderOption:e=>{var r,n,i;const o=EE(e),s=ae[null==(r=e.shortName)?void 0:r.toLowerCase()];return t.jsxs("div",{className:"flex items-center space-x-3 w-full",children:[o?t.jsx("img",{src:o,alt:e.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:o?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.shortName)?void 0:n.slice(0,2).toUpperCase()})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"font-semibold text-gray-800",children:e.name}),s&&t.jsx("span",{className:`text-xs font-medium ${s.color}`,children:s.text})]}),t.jsx("div",{className:"text-sm text-gray-500",children:null==(i=e.shortName)?void 0:i.toUpperCase()})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.shortName}`,disabled:B})]}),P&&t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:VE},children:"Select Token"}),t.jsx(bE,{options:M.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==P?void 0:P.shortName)||e.networkId===(null==P?void 0:P.id)}),value:(null==T?void 0:T.id)||"",onChange:e=>{const t=M.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==P?void 0:P.shortName)||e.networkId===(null==P?void 0:P.id)}).find(t=>t.id===e);W(t),em.trackTokenSelected(null==t?void 0:t.symbol,null==P?void 0:P.name,null==s?void 0:s.merchantName)},placeholder:"Choose your token...",renderOption:e=>{var r,n;const i=IE(e.symbol);return t.jsxs("div",{className:"flex items-center space-x-3",children:[i?t.jsx("img",{src:i,alt:e.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:i?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(r=e.symbol)?void 0:r.slice(0,2)})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name," (",e.symbol,")"]}),t.jsxs("div",{className:"text-sm text-gray-500",children:[(null==(n=e.Network)?void 0:n.name)||"Unknown Network",e.isStablecoin&&t.jsx("span",{className:"ml-2 text-green-600",children:"• Stablecoin"})]})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.symbol}`,disabled:B})]}),P&&T&&t.jsx("button",{onClick:()=>D(s),disabled:B,className:"w-full bg-[#7042D2] text-white py-4 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200 shadow-lg hover:shadow-xl",style:{fontFamily:VE},children:B?"Creating Payment...":"Continue"})]})}),t.jsx(wE,{currentStep:A,targetStep:zE,children:P&&T&&O&&t.jsxs("div",{className:"pb-4 pt-4 px-4 bg-white rounded-t-2xl",children:[!k&&t.jsx("div",{className:"mb-4",children:t.jsxs("div",{className:"flex border-b border-gray-200",children:[t.jsx("button",{onClick:()=>H(WE),className:"py-3 px-4 text-sm font-semibold transition-all duration-200 "+(j===WE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:VE},children:"Wallet"}),F()&&t.jsx("button",{onClick:()=>H(GE),className:"py-3 px-4 text-sm font-semibold transition-all duration-200 "+(j===GE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:VE},children:"Transfer"}),t.jsx("button",{onClick:()=>H(HE),className:"py-3 px-4 text-sm font-semibold transition-all duration-200 "+(j===HE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:VE},children:"QR Code"})]})}),k?t.jsx(DE,{paymentData:O,selectedToken:T,selectedNetwork:P,config:s,onPaymentStarted:e=>{C(!0),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.setItem("coinley_mobile_payment_started","true"),e.walletName},onError:e=>{V(e)}}):j===WE?t.jsx(jE,{selectedNetwork:P,onWalletSelect:J,onConnect:async e=>{await Y(e,P)},connectedWallet:g?m.connectedWallet:K,loading:B,solanaWallet:m,onSolanaConnect:async({walletType:e,publicKey:t,wallet:r})=>{}}):null,j===HE&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-2",children:[t.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1.5 text-center",style:{fontFamily:VE},children:"Optimize QR for:"}),t.jsx("div",{className:"flex gap-1.5 justify-center flex-wrap",children:[{id:"metamask",name:"MetaMask",icon:"🦊"},{id:"trust",name:"Trust",icon:"🛡️"},{id:"coinbase",name:"Coinbase",icon:"💙"}].map(e=>t.jsxs("button",{onClick:()=>x(e.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 "+(w===e.id?"bg-[#7042D2] text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"),style:{fontFamily:VE},children:[t.jsx("span",{className:"text-sm",children:e.icon}),t.jsx("span",{children:e.name})]},e.id))})]}),t.jsx(RE,{amount:(null==O?void 0:O.totalAmount)||(null==O?void 0:O.amount)||(null==s?void 0:s.amount),currency:null==T?void 0:T.symbol,network:null==P?void 0:P.shortName,theme:d,paymentData:O,config:s,selectedToken:T,selectedNetwork:P,preferredWallet:w,compact:!0})]}),j===GE&&(null==O?void 0:O.isDepositPayment)&&t.jsxs(t.Fragment,{children:[t.jsx(KE,{depositAddress:O.depositAddress,amount:O.amount,currency:null==T?void 0:T.symbol,network:null==P?void 0:P.shortName,networkName:null==P?void 0:P.name,paymentId:O.id,expiresAt:O.expiresAt,requiredConfirmations:O.requiredConfirmations||20,theme:d,api:p.api,explorerUrl:(null==(h=O.explorer)?void 0:h.address)?O.explorer.address.split("/address/")[0]:null,onPaymentDetected:e=>{},onPaymentProcessing:e=>{G(qE)},onPaymentConfirmed:e=>{const t=e.transactionHash||e.depositTxHash||e.sweepTxHash;G($E),a&&t&&a({paymentId:e.id,transactionHash:t,sweepTxHash:e.sweepTxHash,network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e,sdkConfirmed:e.sdkConfirmed||!1})},onExpired:()=>{V("Payment expired. Please create a new payment.")}}),t.jsx("div",{className:"mt-4",children:t.jsx("button",{type:"button",onClick:()=>{oe(),G(FE)},className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:VE},children:"Cancel & Choose Different Method"})})]}),j===GE&&!(null==O?void 0:O.isDepositPayment)&&t.jsxs("div",{className:"text-center py-6",children:[t.jsxs("div",{className:"mb-4",children:[t.jsx("div",{className:"text-4xl mb-2",children:"💸"}),t.jsx("h3",{className:"text-lg font-semibold text-gray-800",style:{fontFamily:VE},children:"Transfer Payment"}),t.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Get a unique address to send crypto from any wallet"})]}),t.jsx("button",{onClick:async()=>{try{await U(s)}catch(yA){}},disabled:B,className:"w-full bg-[#7042D2] text-white py-3 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200",style:{fontFamily:VE},children:B?"Generating Address...":"Generate Transfer Address"}),t.jsx("p",{className:"text-xs text-gray-500 mt-3",children:"Supported on Base, BSC, Arbitrum, Polygon, Optimism & Avalanche"})]}),(R||ne)&&t.jsx("div",{className:"mt-4",children:t.jsx(UE,{error:ne||R,onRetry:()=>{V(""),Q.resetTransaction(),"error"===re&&K&&ee()},onDismiss:()=>{V(""),Q.resetTransaction()},context:"payment"})}),!(j===GE&&(null==O?void 0:O.isDepositPayment))&&t.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:()=>{oe(),G(FE)},className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:VE},children:"Back"}),t.jsx("button",{type:"button",onClick:async()=>{var e,t,r,n,i,o,s,c,l,u,d,h,f,v,w,x,_,C,I,A,N,M,B,R,L,D;if(k&&S){if(!(null==O?void 0:O.id))return void V("Payment ID not found. Please refresh and try again.");try{E(!0),G(qE),V("");const h=await p.api.checkPaymentStatus(O.id),f="completed"===(null==(e=h.payment)?void 0:e.status)||"swept"===(null==(t=h.payment)?void 0:t.status),g=(null==(r=h.payment)?void 0:r.transactionHash)||(null==(n=h.payment)?void 0:n.sweepTxHash)||(null==(i=h.payment)?void 0:i.depositTxHash);if(f&&g)G($E),a&&a({paymentId:O.id,transactionHash:g,senderAddress:h.payment.senderWalletAddress||h.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:h.payment});else if(f&&!g){(async()=>{var e,t,r;for(let n=0;n<12;n++){await new Promise(e=>setTimeout(e,5e3));const n=await p.api.checkPaymentStatus(O.id),i=(null==(e=n.payment)?void 0:e.transactionHash)||(null==(t=n.payment)?void 0:t.sweepTxHash)||(null==(r=n.payment)?void 0:r.depositTxHash);if(i)return G($E),void(a&&a({paymentId:O.id,transactionHash:i,senderAddress:n.payment.senderWalletAddress||n.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:n.payment}))}V("Payment confirmed but transaction details unavailable. Please contact support."),G(zE)})()}else if("pending"===(null==(o=h.payment)?void 0:o.status)){const e=await p.api.verifyQRPayment(O.id),t=(null==(s=e.onChainData)?void 0:s.transactionHash)||(null==(c=e.payment)?void 0:c.transactionHash);if(e.success&&e.verified&&t)G($E),a&&a({paymentId:O.id,transactionHash:t,senderAddress:(null==(l=e.onChainData)?void 0:l.from)||(null==(u=e.payment)?void 0:u.senderWalletAddress)||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";V(`${t}. Please complete the payment in your wallet and try again.`),G(zE)}}else"failed"===(null==(d=h.payment)?void 0:d.status)?(V("Payment failed. Please try creating a new payment."),G(zE)):(V("Payment not found. Please verify the payment ID and try again."),G(zE))}catch(U){V(`Verification failed: ${U.message}. Please ensure payment was completed and try again.`),G(zE)}finally{E(!1)}}else if(j!==HE){if(g&&m.isConnected||K&&Z)try{let e;if(G(qE),V(""),!g&&Q.setTransactionError&&Q.setTransactionError(""),g){const t=(null==O?void 0:O.recipientWallet)||(null==O?void 0:O.merchantWallet)||(null==O?void 0:O.merchantWalletAddress);if(!t)throw new Error("Merchant wallet address not found");if("SOL"===T.symbol||T.isNative){e=(await b.sendSOL(t,parseFloat(O.totalAmount||O.amount))).signature}else{const r=parseFloat(O.totalAmount||O.amount),n=T.decimals||6,i=null==(B=T.symbol)?void 0:B.toUpperCase();let o=T.address||T.contractAddress;if(o&&o.length>=32&&o.length<=44&&!o.startsWith("0x"));else{const e=(y?hm:um)[i];(null==e?void 0:e.address)&&(o=e.address)}if(O.coinleyWallet&&O.merchantPercentage&&O.coinleyPercentage){const i=r*O.merchantPercentage/1e4,s=r*O.coinleyPercentage/1e4;e=(await b.sendSplitPayment({tokenMintAddress:o,merchantAddress:t,coinleyAddress:O.coinleyWallet,merchantAmount:i,coinleyAmount:s,decimals:n})).signature}else{e=(await b.sendSPLToken(o,t,r,n)).signature}}await p.api.processPayment(O.id,e,P.shortName,m.publicKey)}else e=await ee();if(e&&(V(""),Q.setTransactionError(""),G($E),a)){const t={paymentId:O.id,transactionHash:e,senderAddress:g?null==m?void 0:m.publicKey:Z,network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:O};a(t)}}catch(U){G(zE),(null==(R=U.message)?void 0:R.includes("User rejected"))||(null==(L=U.message)?void 0:L.includes("User denied"))||4001===U.code||"ACTION_REJECTED"===U.code?V("Transaction was cancelled by user. Please try again."):V(U.message||"Transaction failed. Please try again."),g?null==(D=b.resetTransaction)||D.call(b):Q.resetTransaction()}}else{if(!(null==O?void 0:O.id))return void V("Payment ID not found. Please refresh and try again.");try{G(qE),V("");const e=await p.api.checkPaymentStatus(O.id),t="completed"===(null==(h=e.payment)?void 0:h.status)||"swept"===(null==(f=e.payment)?void 0:f.status),r=(null==(v=e.payment)?void 0:v.transactionHash)||(null==(w=e.payment)?void 0:w.sweepTxHash)||(null==(x=e.payment)?void 0:x.depositTxHash);if(t&&r)G($E),a&&a({paymentId:O.id,transactionHash:r,senderAddress:e.payment.senderWalletAddress||e.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e.payment});else if(t&&!r){(async()=>{var e,t,r;for(let n=0;n<12;n++){await new Promise(e=>setTimeout(e,5e3));const n=await p.api.checkPaymentStatus(O.id),i=(null==(e=n.payment)?void 0:e.transactionHash)||(null==(t=n.payment)?void 0:t.sweepTxHash)||(null==(r=n.payment)?void 0:r.depositTxHash);if(i)return G($E),void(a&&a({paymentId:O.id,transactionHash:i,senderAddress:n.payment.senderWalletAddress||n.payment.fromAddress||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:n.payment}))}V("Payment confirmed but transaction details unavailable. Please contact support."),G(zE)})()}else if("pending"===(null==(_=e.payment)?void 0:_.status)){const e=await p.api.verifyQRPayment(O.id),t=(null==(C=e.onChainData)?void 0:C.transactionHash)||(null==(I=e.payment)?void 0:I.transactionHash);if(e.success&&e.verified&&t)G($E),a&&a({paymentId:O.id,transactionHash:t,senderAddress:(null==(A=e.onChainData)?void 0:A.from)||(null==(N=e.payment)?void 0:N.senderWalletAddress)||Z||(null==m?void 0:m.publicKey),network:null==P?void 0:P.shortName,currency:null==T?void 0:T.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";V(`${t}. Please complete the payment and try again.`),G(zE)}}else"failed"===(null==(M=e.payment)?void 0:M.status)?(V("Payment failed. Please try creating a new payment."),G(zE)):(V("Payment not found. Please verify the payment ID and try again."),G(zE))}catch(U){V(`Verification failed: ${U.message}. Please ensure payment was completed and try again.`),G(zE)}}},className:"bg-green-600 text-white w-full py-2.5 px-3 font-semibold rounded-xl hover:bg-green-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 text-sm",disabled:j===WE&&!k&&!g&&!K||j===WE&&!k&&g&&!m.isConnected||k&&!S||"processing"===re||b.isProcessing||I,style:{fontFamily:VE},children:I?"Verifying...":"processing"===re||b.isProcessing?"Processing...":k&&S?"I Have Paid":k?"Select Wallet":j===HE?"I Have Paid":"Pay Now"})]})]})}),t.jsx(wE,{currentStep:A,targetStep:qE,children:t.jsx(kE,{status:"processing",message:j===GE?"Transfer received! Confirming on blockchain...":g?b.isProcessing?"Confirming Solana transaction...":"Processing your Solana payment...":"approve"===re?"Approving token spending...":"splitPayment"===re?"Processing payment split...":ie?"Confirming transaction on blockchain...":"Processing your payment...",theme:d,transactionHash:g?b.txSignature:ie,selectedNetwork:P})}),t.jsx(wE,{currentStep:A,targetStep:$E,children:t.jsx(kE,{status:"success",message:"Payment completed successfully!",theme:d,payment:O,transactionHash:g?b.txSignature||(null==O?void 0:O.transactionHash):ie||(null==O?void 0:O.transactionHash),selectedPaymentMethod:T,selectedNetwork:P,merchantName:(null==s?void 0:s.merchantName)||"Merchant",onClose:l})}),(R||ne)&&t.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4",children:[t.jsx("p",{className:"text-red-800 text-sm",children:R||ne}),t.jsx("button",{onClick:()=>{V(""),Q.setTransactionError("")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]}),A!==$E&&t.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",style:{fontFamily:VE},children:[t.jsxs("p",{children:["Powered by ",t.jsx("span",{className:"text-[#7042D2] font-semibold",children:"Coinley"})," - Multi-Wallet Support"]}),t.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})]}):null},JE=e=>t.jsx(n.WagmiProvider,{config:im,children:t.jsx(i.QueryClientProvider,{client:ZE,children:t.jsx(YE,{...e})})}),XE=r.createContext(null),QE=r.forwardRef(({customerEmail:e="",merchantName:t="",onSuccess:n,onError:i,onClose:o,theme:s="light",autoOpen:a=!1,testMode:c=!1,debug:l=!1,merchantWalletAddresses:u={}},d)=>{const h=r.useContext(XE);if(!h)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:p,closePayment:f}=h,m=t=>{try{if(!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const r={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...u,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};p(r,{onSuccess:n,onError:i,onClose:o})}catch(ud){i&&i(ud)}},g=()=>{f()};return r.useImperativeHandle(d,()=>({open:m,close:g})),null});QE.displayName="CoinleyCheckout";const eA=new i.QueryClient,tA="wallet",rA="qr",nA="transfer",iA=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,config:s,onSuccess:a,onError:c,onClose:l,isOpen:d,theme:h="light"})=>{const p=sm(o,e||n,e?null:i),f=wm(),m=Jv(),g=r.useMemo(()=>p.selectedNetwork?bm(p.selectedNetwork.type||p.selectedNetwork.shortName||p.selectedNetwork.id):fm,[p.selectedNetwork])===mm,y=r.useMemo(()=>!(!g||!p.selectedNetwork)&&(e=>{if(!e)return!1;const t=!0===e.isTestnet||"true"===e.isTestnet,r=(e.name||"").toLowerCase().includes("devnet"),n=(e.shortName||"").toLowerCase().includes("devnet"),i=(e.type||"").toLowerCase().includes("devnet"),o=(e.id||"").toLowerCase().includes("devnet");return t||r||n||i||o})(p.selectedNetwork),[g,p.selectedNetwork]),v=r.useMemo(()=>g&&p.selectedNetwork?pm():[],[g,p.selectedNetwork,y]),b=vE(v,m.connectedWallet),[w,x]=r.useState(tA),[k,_]=r.useState(""),[S,C]=r.useState(!1),[I,E]=r.useState(""),[A,N]=r.useState(!1),[M,P]=r.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[T,O]=r.useState(!1);r.useEffect(()=>{N(NE())},[]);const{currentStep:B,networks:R,tokens:j,selectedNetwork:L,selectedToken:D,paymentData:U,loading:F,error:z,paymentType:q,loadData:$,createPayment:W,createDepositPayment:H,failPayment:G,resetState:V,setSelectedNetwork:K,setSelectedToken:Z,setCurrentStep:Y,setError:J}=p,{connectedWallet:X,address:Q,connectWallet:ee,handleWalletSelection:te,resetState:re}=f,ne=Yv(U,D,L,Q,p.api,f),{executePaymentTransaction:ie,processFinalPayment:oe,transactionStep:se,transactionError:ae,currentTransactionHash:ce}=ne;r.useEffect(()=>{U&&D&&L&&w===rA&&le()},[U,D,L,w]);const le=async()=>{if(U)try{const e=`https://payment.coinley.io/?paymentId=${U.id}&amount=${U.totalAmount||U.amount}&token=${null==D?void 0:D.symbol}&network=${null==L?void 0:L.shortName}`,t=await u.toDataURL(e,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"}});E(t)}catch(yA){console.error("Error generating QR code:",yA)}};r.useEffect(()=>{B===$E&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[B]),r.useEffect(()=>{if(d){$(),V(),em.trackModalOpened(null==s?void 0:s.merchantName,null==s?void 0:s.amount);const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(d){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[d]),r.useEffect(()=>{if("processing"===se||"approve"===se||"splitPayment"===se){const e=setTimeout(()=>{J("Transaction timed out. Please try again."),Y(zE),ne.resetTransaction()},12e4);return()=>clearTimeout(e)}},[se]),r.useEffect(()=>{if(B!==qE||q!==GE||!(null==U?void 0:U.id))return;const e=setInterval(async()=>{try{const t=await p.api.getDepositStatus(U.id);if(t.success&&t.payment){const r=t.payment.status,n=t.payment.depositTxHash||t.payment.sweepTxHash||t.payment.transactionHash;"completed"!==r&&"swept"!==r||!n?"failed"!==r&&"sweep_failed"!==r||(clearInterval(e),J("Payment failed. Please try again."),Y(zE)):(clearInterval(e),Y($E),a&&a({paymentId:U.id,transactionHash:n,depositAddress:t.payment.depositAddress,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol,paymentDetails:t.payment}))}}catch(t){console.warn("[DepositPolling] Error checking status:",t.message)}},5e3);return()=>clearInterval(e)},[B,q,null==U?void 0:U.id,L,D,a]);const ue=()=>{var e;ne.resetTransaction(),null==(e=b.resetTransaction)||e.call(b),null==re||re(),J(""),O(!1),P(!1),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started"),"undefined"!=typeof window&&(window.coinleyPendingSplitPayment=null)},de=async()=>{em.trackModalClosed("user_cancelled"),ue(),await G(),l()},he=r.useMemo(()=>{if(!k)return R;const e=k.toLowerCase();return R.filter(t=>{var r;return t.name.toLowerCase().includes(e)||(null==(r=t.shortName)?void 0:r.toLowerCase().includes(e))})},[R,k]),pe=r.useMemo(()=>L?j.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==L?void 0:L.shortName)||e.networkId===(null==L?void 0:L.id)}):[],[j,L]),fe=e=>{ue(),K(e),Z(null),em.trackNetworkSelected(null==e?void 0:e.name,null==s?void 0:s.merchantName)},me=e=>{Z(e),em.trackTokenSelected(null==e?void 0:e.symbol,null==L?void 0:L.name,null==s?void 0:s.merchantName)},ge=async()=>{var e,t,r,n,i,o,s,c,l,u;if(null==U?void 0:U.id)try{O(!0),Y(qE),J("");const d=await p.api.checkPaymentStatus(U.id),h="completed"===(null==(e=d.payment)?void 0:e.status)||"swept"===(null==(t=d.payment)?void 0:t.status),f=(null==(r=d.payment)?void 0:r.transactionHash)||(null==(n=d.payment)?void 0:n.sweepTxHash)||(null==(i=d.payment)?void 0:i.depositTxHash);if(h&&f)Y($E),a&&a({paymentId:U.id,transactionHash:f,senderAddress:d.payment.senderWalletAddress||d.payment.fromAddress,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol,paymentDetails:d.payment});else if("pending"===(null==(o=d.payment)?void 0:o.status)){const e=await p.api.verifyQRPayment(U.id),t=(null==(s=e.onChainData)?void 0:s.transactionHash)||(null==(c=e.payment)?void 0:c.transactionHash);if(e.success&&e.verified&&t)Y($E),a&&a({paymentId:U.id,transactionHash:t,senderAddress:(null==(l=e.onChainData)?void 0:l.from)||(null==(u=e.payment)?void 0:u.senderWalletAddress),network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";J(`${t}. Please complete the payment and try again.`),Y(zE)}}else J("Payment not found or failed. Please try again."),Y(zE)}catch(d){J(`Verification failed: ${d.message}. Please try again.`),Y(zE)}finally{O(!1)}else J("Payment ID not found. Please refresh and try again.")},ye=e=>e?`${e.slice(0,12)}......${e.slice(-12)}`:"";return d?B===qE?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50",onClick:de}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsx("div",{className:"bg-white rounded-2xl p-8 max-w-md w-full",children:t.jsx(kE,{status:"processing",message:w===nA?"Transfer received! Confirming on blockchain...":g?"Processing your Solana payment...":"Processing your payment...",theme:h,transactionHash:g?b.txSignature:ce,selectedNetwork:L})})})]}):B===$E?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsx("div",{className:"bg-white rounded-2xl p-8 max-w-md w-full",children:t.jsx(kE,{status:"success",message:"Payment completed successfully!",theme:h,payment:U,transactionHash:g?b.txSignature||(null==U?void 0:U.transactionHash):ce||(null==U?void 0:U.transactionHash),selectedPaymentMethod:D,selectedNetwork:L,merchantName:(null==s?void 0:s.merchantName)||"Merchant",onClose:l})})})]}):t.jsxs("div",{className:"fixed inset-0 z-50",style:{fontFamily:VE},children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50",onClick:de}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"bg-gray-50 rounded-2xl shadow-2xl w-[709px] h-[698.17px] overflow-hidden flex",children:[t.jsxs("div",{className:"w-56 bg-gray-50 p-6 flex flex-col border-r border-gray-200",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-4",children:"Pay With :"}),t.jsxs("button",{onClick:()=>x(tA),className:"flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all mb-2 "+(w===tA?"bg-white text-[#7042D2] border-l-4 border-[#7042D2] shadow-sm":"text-gray-400 hover:bg-gray-100"),children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"})}),t.jsx("span",{className:"text-sm font-medium whitespace-nowrap",children:"Wallet extension"})]}),t.jsxs("button",{onClick:()=>x(rA),className:"flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all mb-2 "+(w===rA?"bg-white text-[#7042D2] border-l-4 rounded-none border-[#7042D2] shadow-sm":"text-gray-400 hover:bg-gray-100"),children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"})}),t.jsx("span",{className:"text-sm font-medium whitespace-nowrap",children:"Scan QR to pay"})]}),t.jsxs("button",{onClick:()=>x(nA),className:"flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all "+(w===nA?"bg-white text-[#7042D2] border-l-4 border-[#7042D2] shadow-sm":"text-gray-400 hover:bg-gray-100"),children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"})}),t.jsx("span",{className:"text-sm font-medium whitespace-nowrap",children:"Transfer to address"})]})]}),t.jsxs("div",{className:"flex-1 bg-white rounded-r-2xl p-6 overflow-y-auto",children:[t.jsxs("div",{className:"flex justify-between items-center mb-6",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("img",{src:tm,alt:"Coinley",className:"w-6 h-6"}),t.jsx("span",{className:"text-lg font-semibold text-gray-800",children:"coinley"})]}),t.jsx("button",{onClick:de,className:"w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center hover:bg-gray-200 transition-colors",children:t.jsx("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 mb-6",children:[t.jsx("p",{className:"text-sm text-gray-500 mb-2",children:"Payment summary"}),t.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[t.jsx("svg",{className:"w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"})}),t.jsxs("span",{className:"font-medium",children:["Payment to: ",(null==s?void 0:s.merchantName)||"Merchant"]})]}),t.jsxs("div",{className:"flex items-baseline justify-between",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-gray-400",children:"Amount:"}),t.jsxs("p",{className:"text-3xl text-[#7042D2] font-bold text-gray-900",children:["$",xE((null==s?void 0:s.amount)||0)]})]}),(null==U?void 0:U.id)&&t.jsxs("div",{className:"text-right",children:[t.jsx("p",{className:"text-xs text-gray-400",children:"Transaction Hash:"}),t.jsx("p",{className:"text-xs text-gray-600",children:ye(U.id)})]})]})]}),w===tA&&!S&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Select a network"}),t.jsxs("div",{className:"relative mb-4",children:[t.jsx("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),t.jsx("input",{type:"text",placeholder:"Search Network",value:k,onChange:e=>_(e.target.value),className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#7042D2] focus:border-transparent"})]}),t.jsx("div",{className:"grid grid-cols-2 gap-3",children:he.map(e=>t.jsxs("button",{onClick:()=>fe(e),className:"flex items-center gap-3 p-3 rounded-xl border-2 transition-all "+((null==L?void 0:L.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2] hover:bg-purple-50"),children:[t.jsx("img",{src:EE(e),alt:e.name,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.shortName}&background=7042D2&color=fff`}}),t.jsxs("div",{className:"text-left",children:[t.jsx("p",{className:"font-medium text-sm text-gray-900",children:e.name}),t.jsx("p",{className:"text-xs text-gray-400",children:"Blockchain network"})]})]},e.id))})]}),L&&pe.length>0&&t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Choose a token"}),t.jsx("p",{className:"text-sm text-gray-400 mb-4",children:"Select an option from these available tokens"}),t.jsx("div",{className:"grid grid-cols-2 gap-3",children:pe.map(e=>t.jsxs("button",{onClick:()=>me(e),className:"flex items-center gap-3 p-3 rounded-xl border-2 transition-all "+((null==D?void 0:D.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2] hover:bg-purple-50"),children:[t.jsx("img",{src:IE(e.symbol),alt:e.symbol,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.symbol}&background=7042D2&color=fff`}}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("p",{className:"font-medium text-sm text-gray-900",children:e.name||e.symbol}),e.isStablecoin&&t.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[t.jsx("span",{className:"w-1.5 h-1.5 bg-green-500 rounded-full"}),"Stablecoin"]})]}),t.jsx("p",{className:"text-xs text-gray-400",children:ye(e.contractAddress||e.address)})]})]},e.id))})]}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsx("button",{onClick:de,className:"px-8 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:async()=>{L&&D&&(U||await W(s),C(!0))},disabled:!L||!D||F,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:F?"Creating Payment...":"Connect my Wallet"})]})]}),w===tA&&S&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Confirm Payment"}),t.jsx("div",{className:"bg-gray-50 rounded-xl p-4 mb-4",children:t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("img",{src:EE(L),alt:null==L?void 0:L.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.src=`https://ui-avatars.com/api/?name=${null==L?void 0:L.shortName}&background=7042D2&color=fff`}}),t.jsx("span",{className:"font-medium",children:null==L?void 0:L.name})]}),t.jsx("span",{className:"text-gray-400",children:"•"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("img",{src:IE(null==D?void 0:D.symbol),alt:null==D?void 0:D.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.src=`https://ui-avatars.com/api/?name=${null==D?void 0:D.symbol}&background=7042D2&color=fff`}}),t.jsx("span",{className:"font-medium",children:null==D?void 0:D.symbol})]})]})}),t.jsxs("div",{className:"bg-gray-50 rounded-xl p-4 space-y-3",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Product Amount"}),t.jsxs("span",{className:"font-medium",children:["$",xE((null==U?void 0:U.productAmount)||(null==s?void 0:s.amount)||0)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Processing Fee"}),t.jsxs("span",{className:"font-medium",children:["+$",xE((null==U?void 0:U.platformFee)||0)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-gray-500",children:"Network Fee"}),t.jsxs("span",{className:"font-medium",children:["+$",xE((null==U?void 0:U.networkFee)||0)]})]}),t.jsxs("div",{className:"border-t border-gray-200 pt-3 flex justify-between",children:[t.jsx("span",{className:"font-semibold",children:"Total"}),t.jsxs("span",{className:"font-bold text-lg",children:[xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount)||0)," ",null==D?void 0:D.symbol]})]})]})]}),t.jsx("div",{className:"mb-6",children:t.jsx(jE,{selectedNetwork:L,onWalletSelect:te,onConnect:async e=>{await ee(e,L)},connectedWallet:g?m.connectedWallet:X,loading:F,paymentData:U,selectedToken:D,api:p.api,solanaWallet:m,onSolanaConnect:async({walletType:e,publicKey:t,wallet:r})=>{}})}),(X||m.connectedWallet)&&t.jsx("div",{className:"bg-green-50 border border-green-200 rounded-xl p-4 mb-4",children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("svg",{className:"w-5 h-5 text-green-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium text-green-800",children:"Wallet Connected"}),t.jsx("p",{className:"text-sm text-green-600",children:ye(g?m.publicKey:Q)})]})]})}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsx("button",{onClick:()=>{C(!1),ue()},className:"px-8 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors",children:"Back"}),t.jsx("button",{onClick:async()=>{if(g){if(!m.publicKey||!m.connectedWallet)return void J("Please connect your Solana wallet first");try{Y(qE);const e=await b.executeSplitPayment(U,D,L);if(!e.success)throw new Error(e.error||"Transaction failed");{const t=await p.api.processPayment(U.id,e.signature,m.publicKey);if(!t.success)throw new Error(t.message||"Failed to process payment");Y($E),a&&a({paymentId:U.id,transactionHash:e.signature,senderAddress:m.publicKey,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol})}}catch(yA){J(yA.message||"Transaction failed"),Y(zE)}}else{if(!X||!Q)return void J("Please connect your wallet first");try{Y(qE);const e=await ie();if((null==e?void 0:e.success)&&(null==e?void 0:e.transactionHash))Y($E),a&&a({paymentId:U.id,transactionHash:e.transactionHash,senderAddress:Q,network:null==L?void 0:L.shortName,currency:null==D?void 0:D.symbol});else if(null==e?void 0:e.error)throw new Error(e.error)}catch(yA){J(yA.message||"Transaction failed"),Y(zE)}}},disabled:!(X||m.connectedWallet)||F,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:F?"Processing...":`Pay ${xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount)||0)} ${null==D?void 0:D.symbol}`})]})]}),w===rA&&t.jsxs(t.Fragment,{children:[(!L||!D)&&t.jsxs("div",{className:"text-center py-8",children:[t.jsx("div",{className:"mb-4",children:t.jsx("svg",{className:"w-16 h-16 mx-auto text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"})})}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Generate QR Code"}),t.jsx("p",{className:"text-gray-500 mb-6",children:"Please select a network and token to generate your payment QR code"}),t.jsxs("div",{className:"text-left max-w-md mx-auto",children:[t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Network"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:R.slice(0,4).map(e=>t.jsxs("button",{onClick:()=>fe(e),className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==L?void 0:L.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:EE(e),alt:e.name,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.shortName}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.name})]},e.id))})]}),L&&pe.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Token"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:pe.map(e=>t.jsxs("button",{onClick:async()=>{me(e),U||await W(s)},className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==D?void 0:D.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:IE(e.symbol),alt:e.symbol,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.symbol}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.symbol})]},e.id))})]})]})]}),L&&D&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex gap-6 mb-6",children:[t.jsx("div",{className:"flex-shrink-0",children:I?t.jsx("img",{src:I,alt:"Payment QR Code",className:"w-40 h-40"}):t.jsx("div",{className:"w-40 h-40 bg-gray-100 rounded-lg flex items-center justify-center animate-pulse",children:t.jsx("span",{className:"text-gray-400 text-sm",children:"Generating..."})})}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"font-semibold mb-3",children:"Instructions"}),t.jsxs("ol",{className:"text-sm text-gray-600 space-y-2",children:[t.jsx("li",{children:"1. Open your crypto wallet app (metamask, trust wallet etc)"}),t.jsx("li",{children:"2. Scan the QR code above"}),t.jsxs("li",{children:["3. Confirm the payment amount (",xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount))," ",null==D?void 0:D.symbol,")"]}),t.jsx("li",{children:'4. Click "I\'ve paid" button below after sending the payment'})]})]})]}),t.jsxs("div",{className:"flex justify-between py-3 border-t border-gray-100",children:[t.jsx("span",{className:"text-gray-500",children:"Currency"}),t.jsx("span",{className:"font-medium",children:null==D?void 0:D.symbol})]}),t.jsxs("div",{className:"flex justify-between py-3 border-t border-gray-100",children:[t.jsx("span",{className:"text-gray-500",children:"Network"}),t.jsx("span",{className:"font-medium",children:null==L?void 0:L.name})]}),t.jsxs("div",{className:"bg-purple-50 border border-purple-200 rounded-xl p-4 mt-4 flex items-start gap-3",children:[t.jsx("svg",{className:"w-6 h-6 text-[#7042D2] flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),t.jsxs("p",{className:"text-sm text-[#7042D2]",children:["Make sure you're sending on the correct network (",null==L?void 0:L.name,") and using the exact amount shown above."]})]}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsxs("button",{onClick:()=>{if(I){const e=document.createElement("a");e.download=`coinley-payment-${(null==U?void 0:U.id)||"qr"}.png`,e.href=I,e.click()}},className:"px-6 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors flex items-center gap-2",children:[t.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),"Download QR"]}),t.jsx("button",{onClick:ge,disabled:!U||T,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:T?"Verifying...":"I've made the payment"})]})]})]}),w===nA&&t.jsxs(t.Fragment,{children:[(!L||!D||!(null==U?void 0:U.depositAddress))&&t.jsxs("div",{className:"text-center py-8",children:[t.jsx("div",{className:"mb-4",children:t.jsx("svg",{className:"w-16 h-16 mx-auto text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"})})}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Transfer to Address"}),t.jsx("p",{className:"text-gray-500 mb-6",children:"Select a network and token to get the payment address"}),t.jsxs("div",{className:"text-left max-w-md mx-auto",children:[t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Network"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:R.slice(0,4).map(e=>t.jsxs("button",{onClick:()=>fe(e),className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==L?void 0:L.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:EE(e),alt:e.name,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.shortName}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.name})]},e.id))})]}),L&&pe.length>0&&t.jsxs("div",{className:"mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Token"}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:pe.map(e=>t.jsxs("button",{onClick:()=>me(e),className:"flex items-center gap-2 p-3 rounded-xl border-2 transition-all "+((null==D?void 0:D.id)===e.id?"border-[#7042D2] bg-purple-50":"border-gray-100 hover:border-[#7042D2]"),children:[t.jsx("img",{src:IE(e.symbol),alt:e.symbol,className:"w-6 h-6 rounded-full",onError:t=>{t.target.src=`https://ui-avatars.com/api/?name=${e.symbol}&background=7042D2&color=fff`}}),t.jsx("span",{className:"text-sm font-medium",children:e.symbol})]},e.id))})]}),L&&D&&!(null==U?void 0:U.depositAddress)&&t.jsx("button",{onClick:async()=>{try{await H(s)}catch(yA){}},disabled:F,className:"w-full py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:F?"Generating Address...":"Generate Transfer Address"})]})]}),L&&D&&(null==U?void 0:U.depositAddress)&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-2",children:"Wallet Address"}),t.jsxs("div",{className:"flex items-center gap-2 p-4 bg-gray-50 rounded-xl border border-gray-200",children:[t.jsx("span",{className:"flex-1 text-sm font-mono text-gray-700 break-all",children:U.depositAddress}),t.jsx("button",{onClick:()=>(async e=>{try{await navigator.clipboard.writeText(e)}catch(yA){console.error("Failed to copy:",yA)}})(U.depositAddress),className:"p-2 hover:bg-gray-200 rounded-lg transition-colors flex-shrink-0",children:t.jsx("svg",{className:"w-5 h-5 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})})]}),t.jsxs("p",{className:"text-xs text-gray-400 mt-2 flex items-center gap-1",children:[t.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Double-check before sending. Transactions cannot be reversed."]})]}),t.jsxs("div",{className:"mb-4",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-2",children:"Amount"}),t.jsx("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:t.jsxs("span",{className:"text-lg font-semibold",children:[xE((null==U?void 0:U.totalAmount)||(null==s?void 0:s.amount))," ",null==D?void 0:D.symbol]})})]}),t.jsxs("div",{className:"mb-6",children:[t.jsx("h3",{className:"text-sm font-medium text-gray-700 mb-2",children:"Network Fee"}),t.jsx("div",{className:"p-4 bg-gray-50 rounded-xl border border-gray-200",children:t.jsxs("span",{className:"text-lg font-semibold",children:["$",xE((null==U?void 0:U.networkFee)||.5)]})})]}),t.jsxs("div",{className:"bg-orange-50 border border-orange-200 rounded-xl p-4 flex items-start gap-3",children:[t.jsx("svg",{className:"w-6 h-6 text-orange-500 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),t.jsxs("div",{children:[t.jsxs("p",{className:"font-semibold text-orange-700",children:["Send ",null==D?void 0:D.symbol," on ",null==L?void 0:L.name," network"]}),t.jsxs("p",{className:"text-sm text-orange-600",children:["Use the ",null==L?void 0:L.name," network to send your ",null==D?void 0:D.symbol," quickly and securely with lower transaction fees."]})]})]}),t.jsxs("div",{className:"flex gap-3 mt-6",children:[t.jsx("button",{onClick:()=>{ue(),x(tA)},className:"px-8 py-3 border-2 border-[#7042D2] text-[#7042D2] rounded-xl font-semibold hover:bg-purple-50 transition-colors",children:"Go Back"}),t.jsx("button",{onClick:ge,disabled:T,className:"flex-1 py-3 bg-[#7042D2] text-white rounded-xl font-semibold hover:bg-[#5b34b1] disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:T?"Verifying...":"I've made the payment"})]})]})]}),(z||ae)&&t.jsxs("div",{className:"mt-4 p-4 bg-red-50 border border-red-200 rounded-xl",children:[t.jsx("p",{className:"text-red-800 text-sm",children:z||ae}),t.jsx("button",{onClick:()=>{var e;J(""),null==(e=ne.setTransactionError)||e.call(ne,"")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]})]})})]}):null},oA={ethereum:jv,bsc:Iv,polygon:Uv,arbitrum:kv,optimism:Dv,avalanche:_v},sA=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],type:"function"}];const aA=new class{constructor(){this.clients=new Map}getClient(e){if(!this.clients.has(e)){const t=oA[e];if(!t)throw new Error(`Unsupported network: ${e}`);const r=c.createPublicClient({chain:t,transport:c.http()});this.clients.set(e,r)}return this.clients.get(e)}async checkNativeBalance(e,t){try{const r=this.getClient(t),n=await r.getBalance({address:e}),i=c.formatUnits(n,18);return{balance:parseFloat(i),balanceWei:n.toString(),symbol:this.getNativeTokenSymbol(t),decimals:18}}catch(ud){throw new Error(`Failed to check native balance: ${ud.message}`)}}async checkTokenBalance(e,t,r){try{const n=this.getClient(r),i=c.getContract({address:t,abi:sA,client:n}),[o,s,a]=await Promise.all([i.read.balanceOf([e]),i.read.decimals().catch(()=>18),i.read.symbol().catch(()=>"TOKEN")]);return{balance:parseFloat(c.formatUnits(o,s)),balanceWei:o.toString(),symbol:a,decimals:s,tokenAddress:t}}catch(ud){throw new Error(`Failed to check token balance: ${ud.message}`)}}async validateBalance(e,t,r,n,i=!0){try{let o,s=null;o=t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,n):await this.checkNativeBalance(e,n),t.contractAddress&&i&&(s=await this.checkNativeBalance(e,n));const a=o.balance>=r,c=a?0:r-o.balance;let l=0,u=!0,d=0;if(i)if(l=this.estimateGasFee(n,!!t.contractAddress),t.contractAddress)u=s.balance>=l,d=u?0:l-s.balance;else{const e=r+l;u=o.balance>=e,d=u?0:e-o.balance}const h={isValid:a&&u,tokenBalance:o,nativeBalance:s,requiredAmount:r,estimatedGasFee:l,hasEnoughTokens:a,hasEnoughForGas:u,tokenShortfall:c,gasShortfall:d,errors:[]};if(a||h.errors.push(`Insufficient ${t.symbol} balance. Need ${r} ${t.symbol}, have ${o.balance.toFixed(6)} ${t.symbol}`),!u){const e=(null==s?void 0:s.symbol)||this.getNativeTokenSymbol(n);t.contractAddress?h.errors.push(`Insufficient ${e} for gas fees. Need ~${l.toFixed(6)} ${e}, have ${s.balance.toFixed(6)} ${e}`):h.errors.push(`Insufficient ${e} for payment + gas. Need ${(r+l).toFixed(6)} ${e} total, have ${o.balance.toFixed(6)} ${e}`)}return h}catch(ud){return{isValid:!1,errors:[`Failed to check balance: ${ud.message}`],tokenBalance:null,nativeBalance:null}}}estimateGasFee(e,t=!1){return{ethereum:t?.001:5e-4,bsc:t?5e-4:3e-4,polygon:t?.01:.005,arbitrum:t?3e-4:2e-4,optimism:t?3e-4:2e-4,avalanche:t?.001:5e-4}[e]||.001}getNativeTokenSymbol(e){return{ethereum:"ETH",bsc:"BNB",polygon:"MATIC",arbitrum:"ETH",optimism:"ETH",avalanche:"AVAX"}[e]||"ETH"}async getBalance(e,t,r){return t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,r):await this.checkNativeBalance(e,r)}formatBalance(e,t,r=6){return null==e?"Unknown":0===e?`0 ${t}`:e<.001?`${e.toFixed(8)} ${t}`:e<1?`${e.toFixed(6)} ${t}`:`${e.toFixed(4)} ${t}`}async checkMultipleBalances(e,t,r){try{const n=t.map(t=>this.getBalance(e,t,r).catch(e=>({error:e.message,symbol:t.symbol,balance:0})));return await Promise.all(n)}catch(ud){throw ud}}};class cA{constructor(e,t,r){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=r}async request(e,t={}){const r=`${this.baseURL}${e}`,n={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},i=await fetch(r,{...t,headers:n});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`HTTP ${i.status}`)}return i.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(ud){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"},{id:"42220",name:"Celo",shortName:"celo",chainId:"0xa4ec",type:"celo"},{id:"8453",name:"Base",shortName:"base",chainId:"0x2105",type:"base"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(ud){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Binance USD",symbol:"BUSD",contractAddress:"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"USD Coin",symbol:"USDC",contractAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async updatePaymentStatus(e,t,r=null){return await this.request(`/api/payments/${e}/status`,{method:"PUT",body:JSON.stringify({status:t,transactionHash:r})})}}const lA=globalThis||self;!function(){const e=N;"undefined"!=typeof globalThis&&(globalThis.Buffer=e),"undefined"!=typeof window&&(window.Buffer=e),void 0!==lA&&(lA.Buffer=e),"undefined"!=typeof self&&(self.Buffer=e)}();class uA{constructor(e={}){if(!e.publicKey&&!e.apiKey)throw new Error("CoinleyVanilla: publicKey or apiKey is required");if(!e.publicKey&&!e.apiSecret)throw new Error("CoinleyVanilla: apiSecret is required when using apiKey");if(!e.apiUrl)throw new Error("CoinleyVanilla: apiUrl is required");this.config={publicKey:e.publicKey||null,apiKey:e.apiKey||null,apiSecret:e.apiSecret||null,apiUrl:e.apiUrl.replace(/\/$/,""),theme:e.theme||"light",debug:e.debug||!1,...e},this.isOpen=!1,this.root=null,this.container=null,this.callbacks={},this.currentPayment=null,this.config.debug}open(e,t={}){if(!this.isOpen)try{this._validatePaymentConfig(e),this.callbacks=t,this.currentPayment=e,this._createContainer(),this.root=h.createRoot(this.container),this.isOpen=!0,this.root.render(r.createElement(JE,{publicKey:this.config.publicKey,apiKey:this.config.apiKey,apiSecret:this.config.apiSecret,apiUrl:this.config.apiUrl,isOpen:!0,theme:this.config.theme,config:{amount:e.amount,customerEmail:e.customerEmail,merchantName:e.merchantName||"Merchant",callbackUrl:e.callbackUrl||this._getDefaultCallbackUrl(),merchantWalletAddresses:e.merchantWalletAddresses||{},preferredNetwork:e.preferredNetwork,preferredCurrency:e.preferredCurrency,metadata:{...e.metadata,source:"vanilla-sdk",sdkVersion:"2.0.0",timestamp:(new Date).toISOString()}},onSuccess:this._handleSuccess.bind(this),onError:this._handleError.bind(this),onClose:this._handleClose.bind(this)})),this.config.debug}catch(ud){t.onError&&t.onError(ud.message||"Failed to open payment modal")}}close(){this.isOpen&&(this._cleanup(),this.config.debug)}isPaymentOpen(){return this.isOpen}updateConfig(e){this.config={...this.config,...e},this.config.debug}getConfig(){return{...this.config}}getCurrentPayment(){return this.currentPayment?{...this.currentPayment}:null}_validatePaymentConfig(e){if(!e)throw new Error("Payment configuration is required");if(!e.amount||"number"!=typeof e.amount||e.amount<=0)throw new Error("Valid amount (number > 0) is required");if(!e.customerEmail||"string"!=typeof e.customerEmail)throw new Error("Customer email is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customerEmail))throw new Error("Invalid email format");if(e.merchantWalletAddresses){if("object"!=typeof e.merchantWalletAddresses)throw new Error("merchantWalletAddresses must be an object");Object.keys(e.merchantWalletAddresses).length}}_createContainer(){this.container||(this.container=document.createElement("div"),this.container.id="coinley-payment-container",this.container.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n ",document.body.appendChild(this.container))}_getDefaultCallbackUrl(){return"undefined"!=typeof window?`${window.location.origin}/api/webhooks/coinley`:""}_handleSuccess(e,t,r){this.config.debug,this.callbacks.onSuccess&&this.callbacks.onSuccess(e,t,r)}_handleError(e){this.config.debug,this.callbacks.onError&&this.callbacks.onError(e)}_handleClose(){this._cleanup(),this.callbacks.onClose&&this.callbacks.onClose()}_cleanup(){if(this.isOpen=!1,this.root){try{this.root.unmount()}catch(ud){}this.root=null}this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null),this.currentPayment=null}}function dA(){document.querySelectorAll('script[src*="coinley-vanilla"]').forEach(e=>{const t=e.getAttribute("data-public-key"),r=e.getAttribute("data-api-key"),n=e.getAttribute("data-api-secret"),i=e.getAttribute("data-api-url"),o=e.getAttribute("data-theme")||"light",s=e.hasAttribute("data-debug");if((t||r&&n)&&i)try{window.coinley=new uA({publicKey:t,apiKey:r,apiSecret:n,apiUrl:i,theme:o,debug:s})}catch(ud){}})}"undefined"!=typeof window&&(window.CoinleyVanilla=uA,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",dA):dA());class hA{constructor(e="https://payment.coinley.io/"){this.basePaymentUrl=e.endsWith("/")?e:e+"/"}generatePaymentURL(e){const{merchant:t,amount:r,productAmount:n,platformFee:i,networkFee:o,token:s="USDC",network:a="Ethereum Mainnet",merchantAddress:c}=e;if(!t)throw new Error("Merchant name is required");if(!r)throw new Error("Amount is required");if(!c)throw new Error("Merchant address (smart contract) is required");const l=n||.95*r,u=i||.03*r,d=o||.02*r,h=new URLSearchParams({merchant:t,amount:r.toString(),productAmount:l.toString(),platformFee:u.toString(),networkFee:d.toString(),token:s,network:a,merchantAddress:c});return this.basePaymentUrl+"?"+h.toString()}async generateQRCode(e,t={}){const{width:r=300,margin:n=2,colorDark:i="#7c3aed",colorLight:o="#ffffff"}=t;try{const t=this.generatePaymentURL(e);return{qrCodeDataURL:await u.toDataURL(t,{width:r,margin:n,color:{dark:i,light:o}}),paymentURL:t,paymentData:{...e,qrCodeUrl:t}}}catch(ud){throw new Error(`Failed to generate QR code: ${ud.message}`)}}async generateQRCodeToCanvas(e,t,r={}){const{width:n=300,margin:i=2,colorDark:o="#7c3aed",colorLight:s="#ffffff"}=r;try{const r=this.generatePaymentURL(e);return await u.toCanvas(t,r,{width:n,margin:i,color:{dark:o,light:s}}),r}catch(ud){throw new Error(`Failed to generate QR code to canvas: ${ud.message}`)}}validatePaymentData(e){const t=[],r=[];e.merchant||t.push("Merchant name is required"),(!e.amount||e.amount<=0)&&t.push("Valid amount is required"),e.merchantAddress||t.push("Merchant address (smart contract) is required"),e.merchantAddress&&!/^0x[a-fA-F0-9]{40}$/.test(e.merchantAddress)&&t.push("Invalid Ethereum address format for merchantAddress"),e.amount>1e4&&r.push("Large payment amount detected");return(e.platformFee||0)+(e.networkFee||0)>.1*e.amount&&r.push("High fees detected (>10% of total amount)"),{isValid:0===t.length,errors:t,warnings:r}}async createPaymentQR(e){const{merchantName:t,amount:r,productAmount:n,platformFee:i,networkFee:o,token:s,network:a,merchantWalletAddresses:c,selectedNetwork:l="ethereum",...u}=e,d={merchant:t||"Coinley Merchant",amount:r,productAmount:n,platformFee:i,networkFee:o,token:s||"USDC",network:a||"Ethereum Mainnet",merchantAddress:(null==c?void 0:c[l])||(null==c?void 0:c.ethereum)||(null==c?void 0:c.splitPaymentContract),...u},h=this.validatePaymentData(d);if(!h.isValid)throw new Error(`Payment validation failed: ${h.errors.join(", ")}`);return{...await this.generateQRCode(d),validation:h,instructions:{userAction:"Scan this QR code with your mobile wallet to pay",expectedFlow:"QR Scan → Payment Screen → Wallet Connect → Split Payment → Confirmation",supportedWallets:["MetaMask","Trust Wallet","Coinbase Wallet","WalletConnect compatible wallets"]}}}}const pA=new hA;"undefined"!=typeof window&&(window.Buffer=N),"undefined"!=typeof globalThis&&(globalThis.Buffer=N);const fA={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,r=4)=>e?e.length<=t+r?e:`${e.slice(0,t)}...${e.slice(-r)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class mA extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const gA={react:"\nimport { CoinleyProvider, CoinleyCheckout } from 'coinley-test';\n\n// New recommended way - using publicKey only\n<CoinleyProvider\n publicKey=\"pk_your-public-key\"\n apiUrl=\"https://api.coinley.io\"\n>\n <CoinleyCheckout\n ref={checkoutRef}\n onSuccess={({ paymentId, transactionHash, senderAddress, network, currency, paymentDetails }) => {\n console.log('Payment successful!');\n console.log('Payment ID:', paymentId);\n console.log('Transaction Hash:', transactionHash);\n console.log('Sender Address:', senderAddress); // Wallet address that made the payment\n console.log('Network:', network); // e.g., 'ethereum', 'bsc', 'polygon'\n console.log('Currency:', currency); // e.g., 'USDT', 'USDC'\n console.log('Full Details:', paymentDetails);\n }}\n onError={(error) => console.error('Error:', error)}\n onClose={() => console.log('Closed')}\n />\n</CoinleyProvider>\n\n// Legacy way (still supported) - using apiKey + apiSecret\n<CoinleyProvider\n apiKey=\"your-api-key\"\n apiSecret=\"your-api-secret\"\n apiUrl=\"https://api.coinley.io\"\n>\n ...\n</CoinleyProvider>\n ",vanilla:'\n\x3c!-- Include via CDN --\x3e\n<script src="https://unpkg.com/coinley-test@latest/vanilla"><\/script>\n<link rel="stylesheet" href="https://unpkg.com/coinley-test@latest/vanilla/style.css">\n\n<script>\n// New recommended way - using publicKey only\nconst coinley = new CoinleyVanilla({\n publicKey: "pk_your-public-key",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Legacy way (still supported)\nconst coinleyLegacy = new CoinleyVanilla({\n apiKey: "your-api-key",\n apiSecret: "your-api-secret",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Use in checkout\ncoinley.open({\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n}, {\n onSuccess: ({ paymentId, transactionHash, senderAddress, network, currency, paymentDetails }) => {\n console.log(\'Payment successful!\');\n console.log(\'Sender Address:\', senderAddress); // Wallet that made the payment\n console.log(\'Network:\', network); // e.g., \'ethereum\', \'bsc\'\n console.log(\'Currency:\', currency); // e.g., \'USDT\', \'USDC\'\n },\n onError: (error) => console.error(\'Error:\', error),\n onClose: () => console.log(\'Closed\')\n});\n<\/script>\n '};e.CoinleyCheckout=QE,e.CoinleyError=mA,e.CoinleyProvider=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,theme:s="light",debug:a=!1,children:c})=>{const[l,u]=r.useState(!1),[d,h]=r.useState(null),[p,f]=r.useState({}),[m,g]=r.useState(""),y=()=>{u(!1),h(null),p.onClose&&p.onClose()},v={openPayment:(e,t)=>{h(e),t&&f(t),u(!0)},closePayment:y};return t.jsxs(XE.Provider,{value:v,children:[c,l&&d&&t.jsx(JE,{publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,isOpen:l,config:d,theme:s,debug:a,merchantName:m,onSuccess:p.onSuccess,onError:p.onError,onClose:y})]})},e.CoinleyVanilla=uA,e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=JE,e.PaymentAPI=class{constructor(e,t,r=null){t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=r),this.api=d.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{if(this.publicKey)e.headers["x-public-key"]=this.publicKey;else{e.headers["x-api-key"]=this.apiKey,e.headers["x-api-secret"]=this.apiSecret;const t=this.generateMerchantToken();t&&(e.headers.Authorization=`Bearer ${t}`)}return e},e=>Promise.reject(e)),this.api.interceptors.response.use(e=>e,e=>{var t,r,n;if(401===(null==(t=e.response)?void 0:t.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(r=e.response)?void 0:r.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(n=e.response)?void 0:n.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(ud){return null}}async request(e,t={}){var r,n;try{return(await this.api({url:e,method:t.method||"GET",data:t.data||t.body?JSON.parse(t.body||"{}"):void 0,...t})).data}catch(ud){if(null==(n=null==(r=ud.response)?void 0:r.data)?void 0:n.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Request failed")}}async createPayment(e){var t,r;try{return(await this.api.post("/api/payments/create",e)).data}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to create payment")}}async getPayment(e){var t,r;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(ud){return{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:1,type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:56,type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:137,type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(ud){return{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,r;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to verify payment")}}async processPayment(e,t,r,n){var i;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:r,senderAddress:n})).data}catch(ud){if(null==(i=ud.response)?void 0:i.data){const t=ud.response.data,r=t.error||t.message||"Payment processing failed",n=new Error(r);throw n.isAlreadyCompleted=t.isAlreadyCompleted||!1,n.verificationAttempts=t.verificationAttempts||0,n.statusCode=ud.response.status,n.originalData=t,n}throw new Error(ud.message||"Failed to process PaymentSplitter transaction")}}async getContractInfo(e){var t,r;try{return(await this.api.get(`/api/payments/contract/${e}`)).data.contractInfo}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to get contract information")}}async getPaymentSplitterStatus(e){var t,r;try{return(await this.api.get(`/api/payments/splitter-status/${e}`)).data.paymentSplitterStatus}catch(ud){if(null==(r=null==(t=ud.response)?void 0:t.data)?void 0:r.error)throw new Error(ud.response.data.error);throw new Error(ud.message||"Failed to get PaymentSplitter status")}}async checkPaymentSplitterHealth(){try{return(await this.api.get("/api/payments/health")).data.paymentSplitterHealth}catch(ud){return{error:ud.message}}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(ud){return!1}}},e.PaymentQRGenerator=hA,e.QRCodePayment=({apiKey:e,apiSecret:n,apiUrl:i,config:o,onSuccess:s,onError:a,onClose:c,isOpen:l,theme:d="light",mode:h="splitpayment",splitPaymentUrl:p="https://payment.coinley.io/"})=>{var f;const[m,g]=r.useState("network"),[y,v]=r.useState([]),[b,w]=r.useState([]),[x,k]=r.useState(null),[_,S]=r.useState(null),[C,I]=r.useState(null),[E,A]=r.useState(!1),[N,M]=r.useState(""),[P,T]=r.useState(""),[O,B]=r.useState(""),[R,j]=r.useState(""),[L,D]=r.useState(!1),[U,F]=r.useState(""),[z,q]=r.useState(!1),[$,W]=r.useState(null),H=r.useRef(new cA(i,e,n)),G=r.useRef(null);r.useEffect(()=>(l&&(K(),V()),()=>{G.current&&clearInterval(G.current)}),[l]);const V=()=>{g("network"),k(null),S(null),I(null),M(""),T(""),B(""),j(""),D(!1),F(""),q(!1),W(null),G.current&&clearInterval(G.current)},K=async()=>{try{A(!0),M("");const[e,t]=await Promise.all([H.current.getNetworks(),H.current.getTokens()]);v(e.networks||[]),w(t.stablecoins||[])}catch(yA){M("Failed to load payment options.")}finally{A(!1)}},Z=async e=>{if(!_||!x||!C)return!1;try{const t=await aA.validateBalance(e,_,C.totalAmount,x.shortName,!0);return W(t),!!t.isValid||(M(`Insufficient balance: ${t.errors.join(", ")}`),!1)}catch(t){return M(`Failed to check balance: ${t.message}`),!1}};if(!l)return null;const Y="dark"===d;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(Y?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[t.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(Y?"border-gray-700":"border-gray-200"),children:[t.jsxs("div",{className:"text-center flex-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:"splitpayment"===h?"Split Payment QR":"QR Code Payment"}),o.amount&&t.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",o.amount.toFixed(2)]}),t.jsx("p",{className:"text-xs text-blue-600",children:"splitpayment"===h?"📱 Scan to redirect to payment screen":"📱 Scan with mobile wallet"})]}),t.jsx("button",{onClick:c,className:"ml-4 text-gray-500 hover:text-gray-700 "+(Y?"hover:text-gray-300":""),children:"✕"})]}),t.jsxs("div",{className:"p-4 min-h-[400px]",children:[N&&t.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[N,t.jsx("button",{onClick:()=>M(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"network"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsx("h3",{className:"font-medium text-center",children:"Select Network"}),t.jsx("div",{className:"space-y-2",children:y.map(e=>{var r;const n=null==(r=o.merchantWalletAddresses)?void 0:r[e.shortName];return t.jsxs("button",{onClick:()=>{k(e),g("token")},disabled:!n,className:"w-full p-3 border rounded-lg text-left transition-colors "+(n?"hover:border-purple-500 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"):"opacity-50 cursor-not-allowed "+(Y?"border-gray-700":"border-gray-100")),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsxs("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:[e.shortName.toUpperCase(),!n&&" (No merchant address configured)"]})]},e.id)})})]}),"token"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("button",{onClick:()=>g("network"),className:""+(Y?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),t.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==x?void 0:x.name]})]}),t.jsx("div",{className:"space-y-2",children:b.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==x?void 0:x.shortName)}).map(e=>t.jsxs("button",{onClick:()=>{S(e),(async e=>{var t,r;try{A(!0),M("");const n={amount:o.amount,currency:e.symbol,network:x.shortName,customerEmail:o.customerEmail,callbackUrl:o.callbackUrl,metadata:{...o.metadata,merchantWalletAddresses:o.merchantWalletAddresses,paymentMethod:"split_payment_qr",selectedNetwork:x.shortName,selectedToken:e.symbol}},i=await H.current.createPayment(n);I(i.payment);const s=(null==(t=o.merchantWalletAddresses)?void 0:t.splitPaymentContract)||(null==(r=o.merchantWalletAddresses)?void 0:r[x.shortName]);if(!s)throw new Error("Split payment contract address not found in config");const a=new URLSearchParams({merchant:o.merchantName||"Coinley Merchant",amount:i.payment.totalAmount.toString(),productAmount:(.95*i.payment.totalAmount).toFixed(2),platformFee:(.03*i.payment.totalAmount).toFixed(2),networkFee:(.02*i.payment.totalAmount).toFixed(2),token:e.symbol,network:x.name,merchantAddress:s,paymentId:i.payment.id}),c=p+"?"+a.toString();T(c);const l=await u.toDataURL(c,{width:256,margin:2,color:{dark:"#7c3aed",light:"#ffffff"}});B(l),g("scan")}catch(n){M(n.message||"Failed to generate split payment QR code")}finally{A(!1)}})(e)},disabled:E,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsx("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:e.symbol})]},e.id))})]}),"scan"===m&&t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("h3",{className:"font-medium mb-4",children:"splitpayment"===h?"Scan QR Code to Open Payment Screen":"Scan QR Code with Mobile Wallet"}),O?t.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[t.jsx("div",{className:"p-4 rounded-lg "+(Y?"bg-gray-800":"bg-gray-50"),children:t.jsx("img",{src:O,alt:"Payment QR Code",className:"mx-auto",style:{width:"200px",height:"200px"}})}),t.jsxs("div",{className:"text-sm space-y-1 "+(Y?"text-gray-300":"text-gray-600"),children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Amount:"}),t.jsxs("span",{className:"font-medium",children:[null==C?void 0:C.totalAmount," ",null==_?void 0:_.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Network:"}),t.jsx("span",{className:"font-medium",children:null==x?void 0:x.name})]}),"splitpayment"===h&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Merchant:"}),t.jsx("span",{className:"font-medium",children:o.merchantName||"Coinley Merchant"})]})]}),t.jsx("div",{className:"p-3 rounded-lg text-xs "+(Y?"bg-blue-900 text-blue-200":"bg-blue-50 text-blue-600"),children:"splitpayment"===h?t.jsxs(t.Fragment,{children:["📱 Scan this QR code with your mobile wallet to open the payment screen.",t.jsx("br",{}),"The payment screen will auto-connect your wallet and execute the split payment."]}):"📱 Open your mobile wallet and scan this QR code to connect and pay"}),"splitpayment"===h?t.jsx("button",{onClick:()=>window.open(P,"_blank"),className:"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm",children:"🔗 Test Payment Screen (Opens in new tab)"}):t.jsx("button",{onClick:async()=>{try{A(!0),M("");const e="0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4";F(e),D(!0),await Z(e),g("confirm")}catch(e){M("Failed to simulate wallet connection")}finally{A(!1)}},disabled:E,className:"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm",children:E?"Connecting...":"🧪 Simulate Wallet Scan (Test)"})]}):t.jsxs("div",{className:"flex items-center justify-center py-8",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"}),t.jsx("span",{className:"ml-2",children:"Generating QR Code..."})]})]})}),"confirm"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:t.jsx("span",{className:"text-2xl",children:"📱"})}),t.jsx("h3",{className:"font-medium",children:"Mobile Wallet Connected"}),t.jsx("p",{className:"text-sm mt-2 "+(Y?"text-gray-300":"text-gray-600"),children:"Ready to complete payment"})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[t.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),t.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==U?void 0:U.slice(0,6),"...",null==U?void 0:U.slice(-4)]})]}),$&&t.jsx("div",{className:"p-3 rounded-lg border "+($.isValid?"bg-green-50 border-green-200":"bg-red-50 border-red-200"),children:t.jsxs("div",{className:"space-y-2 text-sm",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Required:"}),t.jsxs("span",{className:"font-medium",children:[null==C?void 0:C.totalAmount," ",null==_?void 0:_.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Your Balance:"}),t.jsx("span",{className:"font-medium "+($.hasEnoughTokens?"text-green-600":"text-red-600"),children:aA.formatBalance(null==(f=$.tokenBalance)?void 0:f.balance,null==_?void 0:_.symbol)})]}),$.nativeBalance&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Gas Balance:"}),t.jsx("span",{className:"font-medium "+($.hasEnoughForGas?"text-green-600":"text-red-600"),children:aA.formatBalance($.nativeBalance.balance,$.nativeBalance.symbol)})]})]})}),t.jsx("button",{onClick:async()=>{try{q(!0),M("");const e=`0x${Math.random().toString(16).substring(2,66)}`;await new Promise(e=>setTimeout(e,3e3)),g("success"),null==s||s(C.id,e,{network:x.name,token:_.symbol,amount:C.totalAmount,method:"qr_code",walletAddress:U})}catch(e){M("Transaction confirmation failed")}finally{q(!1)}},disabled:z||!(null==$?void 0:$.isValid),className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium",children:z?"Processing Payment...":(null==$?void 0:$.isValid)?`Confirm Payment of ${null==C?void 0:C.totalAmount} ${null==_?void 0:_.symbol}`:"Insufficient Balance"})]})]}),"success"===m&&t.jsxs("div",{className:"text-center space-y-4",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:t.jsx("span",{className:"text-2xl",children:"✅"})}),t.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),t.jsx("p",{className:"text-sm "+(Y?"text-gray-300":"text-gray-600"),children:"Transaction completed via QR code scan"}),t.jsx("button",{onClick:c,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium",children:"Close"})]}),E&&"scan"!==m&&"confirm"!==m&&t.jsx("div",{className:"flex items-center justify-center py-8",children:t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.RedesignedCoinleyPayment=e=>t.jsx(n.WagmiProvider,{config:im,children:t.jsx(i.QueryClientProvider,{client:eA,children:t.jsx(iA,{...e})})}),e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:n})=>{const[i,o]=r.useState(e);return r.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",i)},[i]),t.jsx("div",{className:`coinley-theme-${i}`,children:n})},e.USAGE_EXAMPLES=gA,e.VERSION="0.0.27",e.generatePaymentQR=(e,t)=>pA.generateQRCode(e,t),e.generatePaymentURL=e=>pA.generatePaymentURL(e),e.paymentQR=pA,e.sdkAnalytics=em,e.useCoinley=()=>{const e=r.useContext(XE);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=fA,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
23
23
  //# sourceMappingURL=index.umd.js.map