UNPKG

bitgo

Version:
2 lines • 31.6 MB
/*! For license information please see BitGoJS.min.js.LICENSE.txt */ !function webpackUniversalModuleDefinition(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory(require("wasmer_wasi_js_bg.wasm")):"function"==typeof define&&define.amd?define(["wasmer_wasi_js_bg.wasm"],factory):"object"==typeof exports?exports.BitGoJS=factory(require("wasmer_wasi_js_bg.wasm")):root.BitGoJS=factory(root["wasmer_wasi_js_bg.wasm"])}(self,(__WEBPACK_EXTERNAL_MODULE__948250__=>(()=>{var __webpack_modules__={570:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var isValue=__webpack_require__(276974),isPlainFunction=__webpack_require__(901550),assign=__webpack_require__(409641),normalizeOpts=__webpack_require__(862939),contains=__webpack_require__(645545);(module.exports=function(dscr,value){var c,e,w,options,desc;return arguments.length<2||"string"!=typeof dscr?(options=value,value=dscr,dscr=null):options=arguments[2],isValue(dscr)?(c=contains.call(dscr,"c"),e=contains.call(dscr,"e"),w=contains.call(dscr,"w")):(c=w=!0,e=!1),desc={value,configurable:c,enumerable:e,writable:w},options?assign(normalizeOpts(options),desc):desc}).gs=function(dscr,get,set){var c,e,options,desc;return"string"!=typeof dscr?(options=set,set=get,get=dscr,dscr=null):options=arguments[3],isValue(get)?isPlainFunction(get)?isValue(set)?isPlainFunction(set)||(options=set,set=void 0):set=void 0:(options=get,get=set=void 0):get=void 0,isValue(dscr)?(c=contains.call(dscr,"c"),e=contains.call(dscr,"e")):(c=!0,e=!1),desc={get,set,configurable:c,enumerable:e},options?assign(normalizeOpts(options),desc):desc}},1032:(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.d(__webpack_exports__,{ev:()=>ed25519});var esm_sha512=__webpack_require__(715460),utils=__webpack_require__(830036),abstract_curve=__webpack_require__(743556),modular=__webpack_require__(826681),abstract_utils=__webpack_require__(379506);const _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_8n=BigInt(8),VERIFY_DEFAULT={zip215:!0};function edwards_twistedEdwards(curveDef){const CURVE=function validateOpts(curve){const opts=(0,abstract_curve.hp)(curve);return abstract_utils.Q5(curve,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...opts})}(curveDef),{Fp,n:CURVE_ORDER,prehash,hash:cHash,randomBytes,nByteLength,h:cofactor}=CURVE,MASK=_2n<<BigInt(8*nByteLength)-_1n,modP=Fp.create,Fn=(0,modular.D0)(CURVE.n,CURVE.nBitLength),uvRatio=CURVE.uvRatio||((u,v)=>{try{return{isValid:!0,value:Fp.sqrt(u*Fp.inv(v))}}catch(e){return{isValid:!1,value:_0n}}}),adjustScalarBytes=CURVE.adjustScalarBytes||(bytes=>bytes),domain=CURVE.domain||((data,ctx,phflag)=>{if((0,abstract_utils.e8)("phflag",phflag),ctx.length||phflag)throw new Error("Contexts/pre-hash are not supported");return data});function aCoordinate(title,n){abstract_utils.aK("coordinate "+title,n,_0n,MASK)}function assertPoint(other){if(!(other instanceof Point))throw new Error("ExtendedPoint expected")}const toAffineMemo=(0,abstract_utils.x)(((p,iz)=>{const{ex:x,ey:y,ez:z}=p,is0=p.is0();null==iz&&(iz=is0?_8n:Fp.inv(z));const ax=modP(x*iz),ay=modP(y*iz),zz=modP(z*iz);if(is0)return{x:_0n,y:_1n};if(zz!==_1n)throw new Error("invZ was invalid");return{x:ax,y:ay}})),assertValidMemo=(0,abstract_utils.x)((p=>{const{a,d}=CURVE;if(p.is0())throw new Error("bad point: ZERO");const{ex:X,ey:Y,ez:Z,et:T}=p,X2=modP(X*X),Y2=modP(Y*Y),Z2=modP(Z*Z),Z4=modP(Z2*Z2),aX2=modP(X2*a);if(modP(Z2*modP(aX2+Y2))!==modP(Z4+modP(d*modP(X2*Y2))))throw new Error("bad point: equation left != right (1)");if(modP(X*Y)!==modP(Z*T))throw new Error("bad point: equation left != right (2)");return!0}));class Point{constructor(ex,ey,ez,et){this.ex=ex,this.ey=ey,this.ez=ez,this.et=et,aCoordinate("x",ex),aCoordinate("y",ey),aCoordinate("z",ez),aCoordinate("t",et),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof Point)throw new Error("extended point not allowed");const{x,y}=p||{};return aCoordinate("x",x),aCoordinate("y",y),new Point(x,y,_1n,modP(x*y))}static normalizeZ(points){const toInv=Fp.invertBatch(points.map((p=>p.ez)));return points.map(((p,i)=>p.toAffine(toInv[i]))).map(Point.fromAffine)}static msm(points,scalars){return(0,abstract_curve.Xf)(Point,Fn,points,scalars)}_setWindowSize(windowSize){wnaf.setWindowSize(this,windowSize)}assertValidity(){assertValidMemo(this)}equals(other){assertPoint(other);const{ex:X1,ey:Y1,ez:Z1}=this,{ex:X2,ey:Y2,ez:Z2}=other,X1Z2=modP(X1*Z2),X2Z1=modP(X2*Z1),Y1Z2=modP(Y1*Z2),Y2Z1=modP(Y2*Z1);return X1Z2===X2Z1&&Y1Z2===Y2Z1}is0(){return this.equals(Point.ZERO)}negate(){return new Point(modP(-this.ex),this.ey,this.ez,modP(-this.et))}double(){const{a}=CURVE,{ex:X1,ey:Y1,ez:Z1}=this,A=modP(X1*X1),B=modP(Y1*Y1),C=modP(_2n*modP(Z1*Z1)),D=modP(a*A),x1y1=X1+Y1,E=modP(modP(x1y1*x1y1)-A-B),G=D+B,F=G-C,H=D-B,X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}add(other){assertPoint(other);const{a,d}=CURVE,{ex:X1,ey:Y1,ez:Z1,et:T1}=this,{ex:X2,ey:Y2,ez:Z2,et:T2}=other;if(a===BigInt(-1)){const A=modP((Y1-X1)*(Y2+X2)),B=modP((Y1+X1)*(Y2-X2)),F=modP(B-A);if(F===_0n)return this.double();const C=modP(Z1*_2n*T2),D=modP(T1*_2n*Z2),E=D+C,G=B+A,H=D-C,X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}const A=modP(X1*X2),B=modP(Y1*Y2),C=modP(T1*d*T2),D=modP(Z1*Z2),E=modP((X1+Y1)*(X2+Y2)-A-B),F=D-C,G=D+C,H=modP(B-a*A),X3=modP(E*F),Y3=modP(G*H),T3=modP(E*H),Z3=modP(F*G);return new Point(X3,Y3,Z3,T3)}subtract(other){return this.add(other.negate())}wNAF(n){return wnaf.wNAFCached(this,n,Point.normalizeZ)}multiply(scalar){const n=scalar;abstract_utils.aK("scalar",n,_1n,CURVE_ORDER);const{p,f}=this.wNAF(n);return Point.normalizeZ([p,f])[0]}multiplyUnsafe(scalar,acc=Point.ZERO){const n=scalar;return abstract_utils.aK("scalar",n,_0n,CURVE_ORDER),n===_0n?I:this.is0()||n===_1n?this:wnaf.wNAFCachedUnsafe(this,n,Point.normalizeZ,acc)}isSmallOrder(){return this.multiplyUnsafe(cofactor).is0()}isTorsionFree(){return wnaf.unsafeLadder(this,CURVE_ORDER).is0()}toAffine(iz){return toAffineMemo(this,iz)}clearCofactor(){const{h:cofactor}=CURVE;return cofactor===_1n?this:this.multiplyUnsafe(cofactor)}static fromHex(hex,zip215=!1){const{d,a}=CURVE,len=Fp.BYTES;hex=(0,abstract_utils.qj)("pointHex",hex,len),(0,abstract_utils.e8)("zip215",zip215);const normed=hex.slice(),lastByte=hex[len-1];normed[len-1]=-129&lastByte;const y=abstract_utils.lX(normed),max=zip215?MASK:Fp.ORDER;abstract_utils.aK("pointHex.y",y,_0n,max);const y2=modP(y*y),u=modP(y2-_1n),v=modP(d*y2-a);let{isValid,value:x}=uvRatio(u,v);if(!isValid)throw new Error("Point.fromHex: invalid y coordinate");const isXOdd=(x&_1n)===_1n,isLastByteOdd=!!(128&lastByte);if(!zip215&&x===_0n&&isLastByteOdd)throw new Error("Point.fromHex: x=0 and x_0=1");return isLastByteOdd!==isXOdd&&(x=modP(-x)),Point.fromAffine({x,y})}static fromPrivateKey(privKey){return getExtendedPublicKey(privKey).point}toRawBytes(){const{x,y}=this.toAffine(),bytes=abstract_utils.z(y,Fp.BYTES);return bytes[bytes.length-1]|=x&_1n?128:0,bytes}toHex(){return abstract_utils.My(this.toRawBytes())}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,_1n,modP(CURVE.Gx*CURVE.Gy)),Point.ZERO=new Point(_0n,_1n,_1n,_0n);const{BASE:G,ZERO:I}=Point,wnaf=(0,abstract_curve.hT)(Point,8*nByteLength);function modN(a){return(0,modular.zi)(a,CURVE_ORDER)}function modN_LE(hash){return modN(abstract_utils.lX(hash))}function getExtendedPublicKey(key){const len=Fp.BYTES;key=(0,abstract_utils.qj)("private key",key,len);const hashed=(0,abstract_utils.qj)("hashed private key",cHash(key),2*len),head=adjustScalarBytes(hashed.slice(0,len)),prefix=hashed.slice(len,2*len),scalar=modN_LE(head),point=G.multiply(scalar),pointBytes=point.toRawBytes();return{head,prefix,scalar,point,pointBytes}}function hashDomainToScalar(context=new Uint8Array,...msgs){const msg=abstract_utils.Id(...msgs);return modN_LE(cHash(domain(msg,(0,abstract_utils.qj)("context",context),!!prehash)))}const verifyOpts=VERIFY_DEFAULT;G._setWindowSize(8);return{CURVE,getPublicKey:function getPublicKey(privKey){return getExtendedPublicKey(privKey).pointBytes},sign:function sign(msg,privKey,options={}){msg=(0,abstract_utils.qj)("message",msg),prehash&&(msg=prehash(msg));const{prefix,scalar,pointBytes}=getExtendedPublicKey(privKey),r=hashDomainToScalar(options.context,prefix,msg),R=G.multiply(r).toRawBytes(),s=modN(r+hashDomainToScalar(options.context,R,pointBytes,msg)*scalar);abstract_utils.aK("signature.s",s,_0n,CURVE_ORDER);const res=abstract_utils.Id(R,abstract_utils.z(s,Fp.BYTES));return(0,abstract_utils.qj)("result",res,2*Fp.BYTES)},verify:function verify(sig,msg,publicKey,options=verifyOpts){const{context,zip215}=options,len=Fp.BYTES;sig=(0,abstract_utils.qj)("signature",sig,2*len),msg=(0,abstract_utils.qj)("message",msg),publicKey=(0,abstract_utils.qj)("publicKey",publicKey,len),void 0!==zip215&&(0,abstract_utils.e8)("zip215",zip215),prehash&&(msg=prehash(msg));const s=abstract_utils.lX(sig.slice(len,2*len));let A,R,SB;try{A=Point.fromHex(publicKey,zip215),R=Point.fromHex(sig.slice(0,len),zip215),SB=G.multiplyUnsafe(s)}catch(error){return!1}if(!zip215&&A.isSmallOrder())return!1;const k=hashDomainToScalar(context,R.toRawBytes(),A.toRawBytes(),msg);return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().equals(Point.ZERO)},ExtendedPoint:Point,utils:{getExtendedPublicKey,randomPrivateKey:()=>randomBytes(Fp.BYTES),precompute:(windowSize=8,point=Point.BASE)=>(point._setWindowSize(windowSize),point.multiply(BigInt(3)),point)}}}const ED25519_P=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ED25519_SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ed25519_1n=(BigInt(0),BigInt(1)),ed25519_2n=BigInt(2),_5n=(BigInt(3),BigInt(5)),ed25519_8n=BigInt(8);function ed25519_pow_2_252_3(x){const _10n=BigInt(10),_20n=BigInt(20),_40n=BigInt(40),_80n=BigInt(80),P=ED25519_P,b2=x*x%P*x%P,b4=(0,modular.zH)(b2,ed25519_2n,P)*b2%P,b5=(0,modular.zH)(b4,ed25519_1n,P)*x%P,b10=(0,modular.zH)(b5,_5n,P)*b5%P,b20=(0,modular.zH)(b10,_10n,P)*b10%P,b40=(0,modular.zH)(b20,_20n,P)*b20%P,b80=(0,modular.zH)(b40,_40n,P)*b40%P,b160=(0,modular.zH)(b80,_80n,P)*b80%P,b240=(0,modular.zH)(b160,_80n,P)*b80%P,b250=(0,modular.zH)(b240,_10n,P)*b10%P;return{pow_p_5_8:(0,modular.zH)(b250,ed25519_2n,P)*x%P,b2}}function adjustScalarBytes(bytes){return bytes[0]&=248,bytes[31]&=127,bytes[31]|=64,bytes}function uvRatio(u,v){const P=ED25519_P,v3=(0,modular.zi)(v*v*v,P),pow=ed25519_pow_2_252_3(u*(0,modular.zi)(v3*v3*v,P)).pow_p_5_8;let x=(0,modular.zi)(u*v3*pow,P);const vx2=(0,modular.zi)(v*x*x,P),root1=x,root2=(0,modular.zi)(x*ED25519_SQRT_M1,P),useRoot1=vx2===u,useRoot2=vx2===(0,modular.zi)(-u,P),noRoot=vx2===(0,modular.zi)(-u*ED25519_SQRT_M1,P);return useRoot1&&(x=root1),(useRoot2||noRoot)&&(x=root2),(0,modular.dQ)(x,P)&&(x=(0,modular.zi)(-x,P)),{isValid:useRoot1||useRoot2,value:x}}const Fp=(()=>(0,modular.D0)(ED25519_P,void 0,!0))(),ed25519Defaults=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:ed25519_8n,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:esm_sha512.Zf,randomBytes:utils.po,adjustScalarBytes,uvRatio}))(),ed25519=(()=>edwards_twistedEdwards(ed25519Defaults))()},1432:(module,__unused_webpack_exports,__webpack_require__)=>{var baseEach=__webpack_require__(484570);module.exports=function baseEvery(collection,predicate){var result=!0;return baseEach(collection,(function(value,index,collection){return result=!!predicate(value,index,collection)})),result}},1795:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var ownKeys,__createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||(ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)Object.prototype.hasOwnProperty.call(o,k)&&(ar[ar.length]=k);return ar},ownKeys(o)},function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k=ownKeys(mod),i=0;i<k.length;i++)"default"!==k[i]&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result});Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tbtcbgsig=void 0;const btc_1=__webpack_require__(48373),utxolib=__importStar(__webpack_require__(83140));class Tbtcbgsig extends btc_1.Btc{constructor(bitgo){super(bitgo,utxolib.networks.bitcoinBitGoSignet)}static createInstance(bitgo){return new Tbtcbgsig(bitgo)}}exports.Tbtcbgsig=Tbtcbgsig},1799:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shake256=exports.shake128=exports.keccak_512=exports.keccak_384=exports.keccak_256=exports.keccak_224=exports.sha3_512=exports.sha3_384=exports.sha3_256=exports.sha3_224=exports.Keccak=exports.keccakP=void 0;const _assert_js_1=__webpack_require__(504161),_u64_js_1=__webpack_require__(452346),utils_js_1=__webpack_require__(544099),SHA3_PI=[],SHA3_ROTL=[],_SHA3_IOTA=[],_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_7n=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113);for(let round=0,R=_1n,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5],SHA3_PI.push(2*(5*y+x)),SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n;for(let j=0;j<7;j++)R=(R<<_1n^(R>>_7n)*_0x71n)%_256n,R&_2n&&(t^=_1n<<(_1n<<BigInt(j))-_1n);_SHA3_IOTA.push(t)}const[SHA3_IOTA_H,SHA3_IOTA_L]=(0,_u64_js_1.split)(_SHA3_IOTA,!0),rotlH=(h,l,s)=>s>32?(0,_u64_js_1.rotlBH)(h,l,s):(0,_u64_js_1.rotlSH)(h,l,s),rotlL=(h,l,s)=>s>32?(0,_u64_js_1.rotlBL)(h,l,s):(0,_u64_js_1.rotlSL)(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(10);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10,idx0=(x+2)%10,B0=B[idx0],B1=B[idx0+1],Th=rotlH(B0,B1,1)^B[idx1],Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10)s[x+y]^=Th,s[x+y+1]^=Tl}let curH=s[2],curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t],Th=rotlH(curH,curL,shift),Tl=rotlL(curH,curL,shift),PI=SHA3_PI[t];curH=s[PI],curL=s[PI+1],s[PI]=Th,s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round],s[1]^=SHA3_IOTA_L[round]}B.fill(0)}exports.keccakP=keccakP;class Keccak extends utils_js_1.Hash{constructor(blockLen,suffix,outputLen,enableXOF=!1,rounds=24){if(super(),this.blockLen=blockLen,this.suffix=suffix,this.outputLen=outputLen,this.enableXOF=enableXOF,this.rounds=rounds,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,_assert_js_1.number)(outputLen),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,utils_js_1.u32)(this.state)}keccak(){utils_js_1.isLE||(0,utils_js_1.byteSwap32)(this.state32),keccakP(this.state32,this.rounds),utils_js_1.isLE||(0,utils_js_1.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(data){(0,_assert_js_1.exists)(this);const{blockLen,state}=this,len=(data=(0,utils_js_1.toBytes)(data)).length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];this.pos===blockLen&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state,suffix,pos,blockLen}=this;state[pos]^=suffix,128&suffix&&pos===blockLen-1&&this.keccak(),state[blockLen-1]^=128,this.keccak()}writeInto(out){(0,_assert_js_1.exists)(this,!1),(0,_assert_js_1.bytes)(out),this.finish();const bufferOut=this.state,{blockLen}=this;for(let pos=0,len=out.length;pos<len;){this.posOut>=blockLen&&this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos),this.posOut+=take,pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){return(0,_assert_js_1.number)(bytes),this.xofInto(new Uint8Array(bytes))}digestInto(out){if((0,_assert_js_1.output)(out,this),this.finished)throw new Error("digest() was already called");return this.writeInto(out),this.destroy(),out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;return to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds)),to.state32.set(this.state32),to.pos=this.pos,to.posOut=this.posOut,to.finished=this.finished,to.rounds=rounds,to.suffix=suffix,to.outputLen=outputLen,to.enableXOF=enableXOF,to.destroyed=this.destroyed,to}}exports.Keccak=Keccak;const gen=(suffix,blockLen,outputLen)=>(0,utils_js_1.wrapConstructor)((()=>new Keccak(blockLen,suffix,outputLen)));exports.sha3_224=gen(6,144,28),exports.sha3_256=gen(6,136,32),exports.sha3_384=gen(6,104,48),exports.sha3_512=gen(6,72,64),exports.keccak_224=gen(1,144,28),exports.keccak_256=gen(1,136,32),exports.keccak_384=gen(1,104,48),exports.keccak_512=gen(1,72,64);const genShake=(suffix,blockLen,outputLen)=>(0,utils_js_1.wrapXOFConstructorWithOpts)(((opts={})=>new Keccak(blockLen,suffix,void 0===opts.dkLen?outputLen:opts.dkLen,!0)));exports.shake128=genShake(31,168,16),exports.shake256=genShake(31,136,32)},1800:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getTxHash=void 0;const util_crypto_1=__webpack_require__(465354);exports.getTxHash=function getTxHash(signedTx){return(0,util_crypto_1.blake2AsHex)(signedTx,256)}},1803:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var ownKeys,Buffer=__webpack_require__(901048).Buffer,__createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||(ownKeys=function(o){return ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)Object.prototype.hasOwnProperty.call(o,k)&&(ar[ar.length]=k);return ar},ownKeys(o)},function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k=ownKeys(mod),i=0;i<k.length;i++)"default"!==k[i]&&__createBinding(result,mod,k[i]);return __setModuleDefault(result,mod),result}),__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Sol=exports.DEFAULT_SCAN_FACTOR=void 0;const bignumber_js_1=__importDefault(__webpack_require__(755553)),base58=__importStar(__webpack_require__(939216)),sdk_core_1=__webpack_require__(32942),sdk_lib_mpc_1=__webpack_require__(986257),statics_1=__webpack_require__(577475),_=__importStar(__webpack_require__(645250)),request=__importStar(__webpack_require__(692335)),lib_1=__webpack_require__(939181),utils_1=__webpack_require__(421528);exports.DEFAULT_SCAN_FACTOR=20;const HEX_REGEX=/^[0-9a-fA-F]+$/;class Sol extends sdk_core_1.BaseCoin{constructor(bitgo,staticsCoin){if(super(bitgo),!staticsCoin)throw new Error("missing required constructor parameter staticsCoin");this._staticsCoin=staticsCoin}static createInstance(bitgo,staticsCoin){return new Sol(bitgo,staticsCoin)}allowsAccountConsolidations(){return!0}supportsTss(){return!0}getDefaultMultisigType(){return sdk_core_1.multisigTypes.tss}getMPCAlgorithm(){return"eddsa"}getChain(){return this._staticsCoin.name}getFamily(){return this._staticsCoin.family}getFullName(){return this._staticsCoin.fullName}getNetwork(){return this._staticsCoin.network}getBaseFactor(){return Math.pow(10,this._staticsCoin.decimalPlaces)}async verifyTransaction(params){const totalAmount={},coinConfig=statics_1.coins.get(this.getChain()),{txParams,txPrebuild,memo,durableNonce}=params,transaction=new lib_1.Transaction(coinConfig),rawTx=txPrebuild.txBase64||txPrebuild.txHex,consolidateId=txPrebuild.consolidateId,walletRootAddress=params.wallet.coinSpecific()?.rootAddress;if(!rawTx)throw new Error("missing required tx prebuild property txBase64 or txHex");let rawTxBase64=rawTx;HEX_REGEX.test(rawTx)&&(rawTxBase64=Buffer.from(rawTx,"hex").toString("base64")),transaction.fromRawTransaction(rawTxBase64);const explainedTx=transaction.explainTransaction();if(void 0!==txParams.recipients){const filteredRecipients=txParams.recipients?.map((recipient=>_.pick(recipient,["address","amount","tokenName"]))),filteredOutputs=explainedTx.outputs.map((output=>_.pick(output,["address","amount","tokenName"])));if(filteredRecipients.length!==filteredOutputs.length)throw new Error("Number of tx outputs does not match with number of txParams recipients");if((await Promise.all(filteredRecipients.map((async(recipientFromUser,index)=>{const recipientFromTx=filteredOutputs[index],userAmount=new bignumber_js_1.default(recipientFromUser.amount),txAmount=new bignumber_js_1.default(recipientFromTx.amount);if(!userAmount.isEqualTo(txAmount))return!1;if(recipientFromUser.address===recipientFromTx.address&&recipientFromUser.tokenName===recipientFromTx.tokenName)return!0;if(recipientFromUser.address!==recipientFromTx.address&&recipientFromUser.tokenName)try{const tokenMintAddress=(0,utils_1.getSolTokenFromTokenName)(recipientFromUser.tokenName);return(0,utils_1.getAssociatedTokenAccountAddress)(tokenMintAddress.tokenAddress,recipientFromUser.address,!0).then((ata=>ata===recipientFromTx.address))}catch{return!1}return!1})))).includes(!1))throw new Error("Tx outputs does not match with expected txParams recipients")}const transactionJson=transaction.toJson();if(memo&&memo.value!==explainedTx.memo)throw new Error("Tx memo does not match with expected txParams recipient memo");if(txParams.recipients){for(const recipients of txParams.recipients){const assetName=recipients.tokenName||this.getChain(),amount=totalAmount[assetName]||new bignumber_js_1.default(0);totalAmount[assetName]=amount.plus(recipients.amount)}const explainedTxTotal={};for(const output of explainedTx.outputs){const assetName=output.tokenName||this.getChain(),amount=explainedTxTotal[assetName]||new bignumber_js_1.default(0);explainedTxTotal[assetName]=amount.plus(output.amount)}if(!_.isEqual(explainedTxTotal,totalAmount))throw new Error("Tx total amount does not match with expected total amount field")}if(void 0===consolidateId&&transactionJson.feePayer!==walletRootAddress)throw new Error("Tx fee payer is not the wallet root address");if(durableNonce&&!_.isEqual(explainedTx.durableNonce,durableNonce))throw new Error("Tx durableNonce does not match with param durableNonce");return!0}async isWalletAddress(params){throw new sdk_core_1.MethodNotImplementedError}generateKeyPair(seed){return seed?new lib_1.KeyPair({seed}).getKeys():(new lib_1.KeyPair).getKeys()}isValidPub(pub){return(0,utils_1.isValidPublicKey)(pub)}isValidPrv(prv){return(0,utils_1.isValidPrivateKey)(prv)}isValidAddress(address){return(0,utils_1.isValidAddress)(address)}async signMessage(key,message){const solKeypair=new lib_1.KeyPair({prv:key.prv});return Buffer.isBuffer(message)&&(message=base58.encode(message)),Buffer.from(solKeypair.signMessage(message))}async signTransaction(params){const factory=this.getBuilder(),rawTx=params.txPrebuild.txHex||params.txPrebuild.txBase64,txBuilder=factory.from(rawTx);txBuilder.sign({key:params.prv});const transaction=await txBuilder.build();if(!transaction)throw new Error("Invalid transaction");return{txHex:transaction.toBroadcastFormat()}}async parseTransaction(params){const transactionExplanation=await this.explainTransaction({txBase64:params.txBase64,feeInfo:params.feeInfo,tokenAccountRentExemptAmount:params.tokenAccountRentExemptAmount});if(!transactionExplanation)throw new Error("Invalid transaction");const solTransaction=transactionExplanation;if(solTransaction.outputs.length<=0)return{inputs:[],outputs:[]};const senderAddress=solTransaction.outputs[0].address,feeAmount=new bignumber_js_1.default(solTransaction.fee.fee);return{inputs:[{address:senderAddress,amount:new bignumber_js_1.default(solTransaction.outputAmount).plus(feeAmount).toNumber()}],outputs:solTransaction.outputs.map((({address,amount,tokenName})=>{const output={address,amount};return tokenName&&(output.tokenName=tokenName),output}))}}async explainTransaction(params){const factory=this.getBuilder();let rebuiltTransaction;try{const transactionBuilder=factory.from(params.txBase64);if(transactionBuilder instanceof lib_1.TransactionBuilder){const txBuilder=transactionBuilder;txBuilder.fee({amount:params.feeInfo.fee}),params.tokenAccountRentExemptAmount&&txBuilder.associatedTokenAccountRent(params.tokenAccountRentExemptAmount)}rebuiltTransaction=await transactionBuilder.build()}catch(e){throw console.log(e),new Error("Invalid transaction")}return rebuiltTransaction.explainTransaction()}async getSignablePayload(serializedTx){const factory=this.getBuilder();return(await factory.from(serializedTx).build()).signablePayload}async presignTransaction(params){if("hot"!==params.walletData.type)return Promise.resolve(params);const txRequestId=params.txPrebuild?.txRequestId;if(void 0===txRequestId)throw new Error("Missing txRequestId");const{tssUtils}=params;await tssUtils.deleteSignatureShares(txRequestId);const recreated=await tssUtils.getTxRequest(txRequestId);let txHex="";if(txHex=recreated.unsignedTxs?recreated.unsignedTxs[0]?.serializedTxHex:recreated.transactions?recreated.transactions[0]?.unsignedTx.serializedTxHex:"",!txHex)throw new Error("Missing serialized tx hex");return Promise.resolve({...params,txPrebuild:recreated,txHex})}getPublicNodeUrl(){return sdk_core_1.Environments[this.bitgo.getEnv()].solNodeUrl}async getDataFromNode(params){const nodeUrl=this.getPublicNodeUrl();try{return await request.post(nodeUrl).send(params.payload)}catch(e){console.debug(e)}throw new Error(`Unable to call endpoint: '/' from node: ${nodeUrl}`)}async getBlockhash(){const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"getLatestBlockhash",params:[{commitment:"finalized"}]}});if(200!==response.status)throw new Error("Account not found");return response.body.result.value.blockhash}async getFeeForMessage(message){const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"getFeeForMessage",params:[message,{commitment:"finalized"}]}});if(200!==response.status)throw new Error("Account not found");return response.body.result.value}async getRentExemptAmount(){const response=await this.getDataFromNode({payload:{jsonrpc:"2.0",id:"1",method:"getMinimumBalanceForRentExemption",params:[165]}});if(200!==response.status||response.error)throw new Error(JSON.stringify(response.error));return response.body.result}async getAccountBalance(pubKey){const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"getBalance",params:[pubKey]}});if(200!==response.status)throw new Error("Account not found");return response.body.result.value}async getAccountInfo(pubKey){const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"getAccountInfo",params:[pubKey,{encoding:"jsonParsed"}]}});if(200!==response.status)throw new Error("Account not found");return{authority:response.body.result.value.data.parsed.info.authority,blockhash:response.body.result.value.data.parsed.info.blockhash}}async getTokenAccountsByOwner(pubKey=""){const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"getTokenAccountsByOwner",params:[pubKey,{programId:"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},{encoding:"jsonParsed"}]}});if(200!==response.status)throw new Error("Account not found");if(0!==response.body.result.value.length){const tokenAccounts=[];for(const tokenAccount of response.body.result.value)tokenAccounts.push({info:tokenAccount.account.data.parsed.info,pubKey:tokenAccount.pubKey});return tokenAccounts}return[]}async getTokenAccountInfo(pubKey){const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"getAccountInfo",params:[pubKey,{encoding:"jsonParsed"}]}});if(200!==response.status)throw new Error("Account not found");return{pubKey,info:response.body.result.value.data.parsed.info}}async createBroadcastableSweepTransaction(params){params.signatureShares;const req=params.signatureShares,broadcastableTransactions=[];let lastScanIndex=0;for(let i=0;i<req.length;i++){const MPC=await sdk_core_1.EDDSAMethods.getInitializedMpcInstance(),transaction=req[i].txRequest.transactions[0].unsignedTx;if(!req[i].ovc||!req[i].ovc[0].eddsaSignature)throw new Error("Missing signature(s)");const signature=req[i].ovc[0].eddsaSignature;if(!transaction.signableHex)throw new Error("Missing signable hex");const messageBuffer=Buffer.from(transaction.signableHex,"hex");if(!MPC.verify(messageBuffer,signature))throw new Error("Invalid signature");const signatureHex=Buffer.concat([Buffer.from(signature.R,"hex"),Buffer.from(signature.sigma,"hex")]),txBuilder=this.getBuilder().from(transaction.serializedTx);if(!transaction.coinSpecific?.commonKeychain)throw new Error("Missing common keychain");const commonKeychain=transaction.coinSpecific.commonKeychain;if(!transaction.derivationPath)throw new Error("Missing derivation path");const derivationPath=transaction.derivationPath,accountId=MPC.deriveUnhardened(commonKeychain,derivationPath).slice(0,64),publicKeyObj={pub:new lib_1.KeyPair({pub:accountId}).getAddress()};txBuilder.addSignature(publicKeyObj,signatureHex);const serializedTx=(await txBuilder.build()).toBroadcastFormat();broadcastableTransactions.push({serializedTx,scanIndex:transaction.scanIndex}),i===req.length-1&&transaction.coinSpecific.lastScanIndex&&(lastScanIndex=transaction.coinSpecific.lastScanIndex)}return{transactions:broadcastableTransactions,lastScanIndex}}async recover(params){if(!params.bitgoKey)throw new Error("missing bitgoKey");if(!params.recoveryDestination||!this.isValidAddress(params.recoveryDestination))throw new Error("invalid recoveryDestination");const bitgoKey=params.bitgoKey.replace(/\s/g,""),isUnsignedSweep=!params.userKey&&!params.backupKey&&!params.walletPassphrase,MPC=await sdk_core_1.EDDSAMethods.getInitializedMpcInstance();let balance=0;const index=params.index||0,currPath=params.seed?(0,sdk_lib_mpc_1.getDerivationPath)(params.seed)+`/${index}`:`m/${index}`,accountId=MPC.deriveUnhardened(bitgoKey,currPath).slice(0,64),bs58EncodedPublicKey=new lib_1.KeyPair({pub:accountId}).getAddress();balance=await this.getAccountBalance(bs58EncodedPublicKey);const factory=this.getBuilder(),walletCoin=this.getChain();let txBuilder,rentExemptAmount,blockhash=await this.getBlockhash(),authority="",totalFee=new bignumber_js_1.default(0),totalFeeForTokenRecovery=new bignumber_js_1.default(0);if(params.tokenContractAddress){const tokenAccounts=await this.getTokenAccountsByOwner(bs58EncodedPublicKey);if(0===tokenAccounts.length)throw Error("Did not find token account to recover tokens, please check token account");{const recovereableTokenAccounts=[];for(const tokenAccount of tokenAccounts)if(params.tokenContractAddress===tokenAccount.info.mint){const tokenAmount=new bignumber_js_1.default(tokenAccount.info.tokenAmount.amount),network=this.getNetwork(),token=(0,utils_1.getSolTokenFromAddress)(tokenAccount.info.mint,network);!_.isUndefined(token)&&tokenAmount.gt(new bignumber_js_1.default(0))&&(tokenAccount.tokenName=token.name,recovereableTokenAccounts.push(tokenAccount));break}if(0===recovereableTokenAccounts.length)throw Error("Not enough token funds to recover");{rentExemptAmount=await this.getRentExemptAmount(),txBuilder=factory.getTokenTransferBuilder().nonce(blockhash).sender(bs58EncodedPublicKey).associatedTokenAccountRent(rentExemptAmount.toString()).feePayer(bs58EncodedPublicKey);const recipientTokenAccounts=await this.getTokenAccountsByOwner(params.recoveryDestination);for(const tokenAccount of recovereableTokenAccounts){let recipientTokenAccountExists=!1;for(const recipientTokenAccount of recipientTokenAccounts)if(recipientTokenAccount.info.mint===tokenAccount.info.mint){recipientTokenAccountExists=!0;break}const recipientTokenAccount=await(0,utils_1.getAssociatedTokenAccountAddress)(tokenAccount.info.mint,params.recoveryDestination),tokenName=tokenAccount.tokenName;txBuilder.send({address:recipientTokenAccount,amount:tokenAccount.info.tokenAmount.amount,tokenName}),recipientTokenAccountExists||(txBuilder.createAssociatedTokenAccount({ownerAddress:params.recoveryDestination,tokenName}),totalFeeForTokenRecovery=totalFeeForTokenRecovery.plus(rentExemptAmount))}}}}else txBuilder=factory.getTransferBuilder().nonce(blockhash).sender(bs58EncodedPublicKey).send({address:params.recoveryDestination,amount:balance.toString()}).feePayer(bs58EncodedPublicKey);if(params.durableNonce){const durableNonceInfo=await this.getAccountInfo(params.durableNonce.publicKey);blockhash=durableNonceInfo.blockhash,authority=durableNonceInfo.authority,txBuilder.nonce(blockhash,{walletNonceAddress:params.durableNonce.publicKey,authWalletAddress:authority})}const serializedMessage=(await txBuilder.build()).solTransaction.serializeMessage().toString("base64"),baseFee=await this.getFeeForMessage(serializedMessage),feePerSignature=params.durableNonce?baseFee/2:baseFee;if(totalFee=totalFee.plus(new bignumber_js_1.default(baseFee)),totalFeeForTokenRecovery=totalFeeForTokenRecovery.plus(new bignumber_js_1.default(baseFee)),totalFee.gt(balance))throw Error("Did not find address with funds to recover");if(params.tokenContractAddress){if(new bignumber_js_1.default(balance).lt(totalFeeForTokenRecovery))throw Error("Not enough funds to pay for recover tokens fees, have: "+balance+" need: "+totalFeeForTokenRecovery.toString());txBuilder.fee({amount:feePerSignature})}else{const netAmount=new bignumber_js_1.default(balance).minus(totalFee);txBuilder=factory.getTransferBuilder().nonce(blockhash).sender(bs58EncodedPublicKey).send({address:params.recoveryDestination,amount:netAmount.toString()}).feePayer(bs58EncodedPublicKey).fee({amount:feePerSignature}),params.durableNonce&&txBuilder.nonce(blockhash,{walletNonceAddress:params.durableNonce.publicKey,authWalletAddress:authority})}if(!isUnsignedSweep){if(!params.userKey)throw new Error("missing userKey");if(!params.backupKey)throw new Error("missing backupKey");if(!params.walletPassphrase)throw new Error("missing wallet passphrase");const unsignedTransaction=await txBuilder.build(),userKey=params.userKey.replace(/\s/g,""),backupKey=params.backupKey.replace(/\s/g,"");let userPrv;try{userPrv=this.bitgo.decrypt({input:userKey,password:params.walletPassphrase})}catch(e){throw new Error(`Error decrypting user keychain: ${e.message}`)}const userSigningMaterial=JSON.parse(userPrv);let backupPrv;try{backupPrv=this.bitgo.decrypt({input:backupKey,password:params.walletPassphrase})}catch(e){throw new Error(`Error decrypting backup keychain: ${e.message}`)}const backupSigningMaterial=JSON.parse(backupPrv),signatureHex=await sdk_core_1.EDDSAMethods.getTSSSignature(userSigningMaterial,backupSigningMaterial,currPath,unsignedTransaction),publicKeyObj={pub:bs58EncodedPublicKey};txBuilder.addSignature(publicKeyObj,signatureHex)}params.durableNonce&&txBuilder.sign({key:params.durableNonce.secretKey});const completedTransaction=await txBuilder.build(),serializedTx=completedTransaction.toBroadcastFormat(),derivationPath=params.seed?(0,sdk_lib_mpc_1.getDerivationPath)(params.seed)+`/${index}`:`m/${index}`,inputs=[];for(const input of completedTransaction.inputs)inputs.push({address:input.address,valueString:input.value,value:new bignumber_js_1.default(input.value).toNumber()});const outputs=[];for(const output of completedTransaction.outputs)outputs.push({address:output.address,valueString:output.value,coinName:output.coin?output.coin:walletCoin});const parsedTx={inputs,outputs,spendAmount:1===completedTransaction.inputs.length?completedTransaction.inputs[0].value:0,type:""},feeInfo={fee:totalFeeForTokenRecovery.toNumber(),feeString:totalFee.toString()},coinSpecific={commonKeychain:bitgoKey};if(isUnsignedSweep){return{txRequests:[{transactions:[{unsignedTx:{serializedTx,scanIndex:index,coin:walletCoin,signableHex:completedTransaction.signablePayload.toString("hex"),derivationPath,parsedTx,feeInfo,coinSpecific},signatureShares:[]}],walletCoin}]}}return{serializedTx,scanIndex:index}}async recoverCloseATA(params){if(!params.bitgoKey)throw new Error("missing bitgoKey");if(!params.recoveryDestination||!this.isValidAddress(params.recoveryDestination))throw new Error("invalid recoveryDestination");if(!params.closeAtaAddress||!this.isValidAddress(params.closeAtaAddress))throw new Error("invalid closeAtaAddress");const bitgoKey=params.bitgoKey.replace(/\s/g,""),MPC=await sdk_core_1.EDDSAMethods.getInitializedMpcInstance();let balance=0;const index=params.index||0,currPath=params.seed?(0,sdk_lib_mpc_1.getDerivationPath)(params.seed)+`/${index}`:`m/${index}`,accountId=MPC.deriveUnhardened(bitgoKey,currPath).slice(0,64),bs58EncodedPublicKey=new lib_1.KeyPair({pub:accountId}).getAddress(),accountBalance=await this.getAccountBalance(bs58EncodedPublicKey);if(balance=await this.getAccountBalance(params.closeAtaAddress),balance<=0)throw Error("Did not find closeAtaAddress with sol funds to recover");const factory=this.getBuilder();let txBuilder,blockhash;const recovertTxns=[],rentExemptAmount=await this.getRentExemptAmount(),tokenInfo=await this.getTokenAccountInfo(params.closeAtaAddress),tokenBalance=Number(tokenInfo.info.tokenAmount.amount);if(tokenBalance>0){if(console.log(`closeATA address ${params.closeAtaAddress} has token balance ${tokenBalance}, it needs to be withdrawn before closing ATA address`),!params.recoveryDestinationAtaAddress||!this.isValidAddress(params.recoveryDestinationAtaAddress))throw new Error("invalid recoveryDestinationAtaAddress");blockhash=await this.getBlockhash(),txBuilder=factory.getTokenTransferBuilder().nonce(blockhash).sender(bs58EncodedPublicKey).associatedTokenAccountRent(rentExemptAmount.toString()).feePayer(bs58EncodedPublicKey);const serializedMessage=(await txBuilder.build()).solTransaction.serializeMessage().toString("base64"),feePerSignature=await this.getFeeForMessage(serializedMessage),baseFee=params.durableNonce?2*feePerSignature:feePerSignature;if(new bignumber_js_1.default(baseFee).gt(accountBalance))throw Error("Did not find address with funds to recover");txBuilder.fee({amount:feePerSignature});const network=this.getNetwork(),token=(0,utils_1.getSolTokenFromAddress)(tokenInfo.info.mint,network);txBuilder.send({address:params.recoveryDestinationAtaAddress,amount:tokenBalance,tokenName:token?.name});const tokenRecoveryTxn=await this.signAndGenerateBroadcastableTransaction(params,txBuilder,bs58EncodedPublicKey),serializedTokenRecoveryTxn=(await tokenRecoveryTxn).serializedTx,broadcastTokenRecoveryTxn=await this.broadcastTransaction({serializedSignedTransaction:serializedTokenRecoveryTxn});console.log(broadcastTokenRecoveryTxn),recovertTxns.push(broadcastTokenRecoveryTxn)}if(params.closeAtaAddress){blockhash=await this.getBlockhash();const ataCloseBuilder=()=>{const txBuilder=factory.getCloseAtaInitializationBuilder();return txBuilder.nonce(blockhash),txBuilder.sender(bs58EncodedPublicKey),txBuilder.accountAddress(params.closeAtaAddress??""),txBuilder.destinationAddress(params.recoveryDestination),txBuilder.authorityAddress(bs58EncodedPublicKey),txBuilder.associatedTokenAccountRent(rentExemptAmount.toString()),txBuilder};txBuilder=ataCloseBuilder()}const closeATARecoveryTxn=await this.signAndGenerateBroadcastableTransaction(params,txBuilder,bs58EncodedPublicKey),serializedCloseATARecoveryTxn=(await closeATARecoveryTxn).serializedTx,broadcastCloseATARecoveryTxn=await this.broadcastTransaction({serializedSignedTransaction:serializedCloseATARecoveryTxn});return console.log(broadcastCloseATARecoveryTxn),recovertTxns.push(broadcastCloseATARecoveryTxn),recovertTxns}async signAndGenerateBroadcastableTransaction(params,txBuilder,bs58EncodedPublicKey){if(!params.userKey)throw new Error("missing userKey");if(!params.backupKey)throw new Error("missing backupKey");if(!params.walletPassphrase)throw new Error("missing wallet passphrase");const unsignedTransaction=await txBuilder.build(),userKey=params.userKey.replace(/\s/g,""),backupKey=params.backupKey.replace(/\s/g,"");let userPrv;try{userPrv=this.bitgo.decrypt({input:userKey,password:params.walletPassphrase})}catch(e){throw new Error(`Error decrypting user keychain: ${e.message}`)}const userSigningMaterial=JSON.parse(userPrv);let backupPrv;try{backupPrv=this.bitgo.decrypt({input:backupKey,password:params.walletPassphrase})}catch(e){throw new Error(`Error decrypting backup keychain: ${e.message}`)}const backupSigningMaterial=JSON.parse(backupPrv),index=params.index||0,currPath=params.seed?(0,sdk_lib_mpc_1.getDerivationPath)(params.seed)+`/${index}`:`m/${index}`,signatureHex=await sdk_core_1.EDDSAMethods.getTSSSignature(userSigningMaterial,backupSigningMaterial,currPath,unsignedTransaction),publicKeyObj={pub:bs58EncodedPublicKey};txBuilder.addSignature(publicKeyObj,signatureHex);return{serializedTx:(await txBuilder.build()).toBroadcastFormat(),scanIndex:index}}async recoverConsolidations(params){const isUnsignedSweep=!params.userKey&&!params.backupKey&&!params.walletPassphrase,startIdx=params.startingScanIndex||1,endIdx=params.endingScanIndex||startIdx+exports.DEFAULT_SCAN_FACTOR;if(startIdx<1||endIdx<=startIdx||endIdx-startIdx>10*exports.DEFAULT_SCAN_FACTOR)throw new Error(`Invalid starting or ending index to scan for addresses. startingScanIndex: ${startIdx}, endingScanIndex: ${endIdx}.`);if(!params.durableNonces)throw new Error("Missing durable nonces");if(!params.durableNonces.publicKeys)throw new Error("Invalid durable nonces: missing public keys");if(!params.durableNonces.secretKey)throw new Error("Invalid durable nonces array: missing secret key");const bitgoKey=params.bitgoKey.replace(/\s/g,""),MPC=await sdk_core_1.EDDSAMethods.getInitializedMpcInstance(),baseAddressPath=params.seed?(0,sdk_lib_mpc_1.getDerivationPath)(params.seed)+"/0":"m/0",accountId=MPC.deriveUnhardened(bitgoKey,baseAddressPath).slice(0,64),baseAddress=new lib_1.KeyPair({pub:accountId}).getAddress();let durableNoncePubKeysIndex=0;const durableNoncePubKeysLength=params.durableNonces.publicKeys.length,consolidationTransactions=[];let lastScanIndex=startIdx;for(let i=startIdx;i<endIdx;i++){const recoverParams={userKey:params.userKey,backupKey:params.backupKey,bitgoKey:params.bitgoKey,walletPassphrase:params.walletPassphrase,recoveryDestination:baseAddress,seed:params.seed,index:i,durableNonce:{publicKey:params.durableNonces.publicKeys[durableNoncePubKeysIndex],secretKey:params.durableNonces.secretKey},tokenContractAddress:params.tokenContractAddress};let recoveryTransaction;try{recoveryTransaction=await this.recover(recoverParams)}catch(e){if("Did not find address with funds to recover"===e.message||"Did not find token account to recover tokens, please check token account"===e.message||"Not enough token funds to recover"===e.message){lastScanIndex=i;continue}throw e}if(isUnsignedSweep?consolidationTransactions.push(recoveryTransaction.txRequests[0]):consolidationTransactions.push(recoveryTransaction),lastScanIndex=i,durableNoncePubKeysIndex++,durableNoncePubKeysIndex>=durableNoncePubKeysLength)break}if(0===consolidationTransactions.length)throw new Error("Did not find an address with funds to recover");if(isUnsignedSweep){const lastTransactionCoinSpecific={commonKeychain:consolidationTransactions[consolidationTransactions.length-1].transactions[0].unsignedTx.coinSpecific.commonKeychain,lastScanIndex};consolidationTransactions[consolidationTransactions.length-1].transactions[0].unsignedTx.coinSpecific=lastTransactionCoinSpecific;return{txRequests:consolidationTransactions}}return{transactions:consolidationTransactions,lastScanIndex}}getTokenEnablementConfig(){return{requiresTokenEnablement:!0,supportsMultipleTokenEnablements:!0}}getBuilder(){return new lib_1.TransactionBuilderFactory(statics_1.coins.get(this.getChain()))}async broadcastTransaction({serializedSignedTransaction}){(0,utils_1.validateRawTransaction)(serializedSignedTransaction,!0,!0);const response=await this.getDataFromNode({payload:{id:"1",jsonrpc:"2.0",method:"sendTransaction",params:[serializedSignedTransaction,{encoding:"base64"}]}});if(response.body.error)throw new Error("Error broadcasting transaction: "+response.body.error.message);return{txId:response.body.result}}}exports.Sol=Sol},1839:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const{Buffer}=__webpack_require__(901048),{URL}=__webpack_require__(654419),Bignumber=__webpack_require__(755553).BigNumber,utils=__webpack_require__(411974),constants=__webpack_require__(355710),MT=constants.MT,NUMBYTES=constants.NUMBYTES,SHIFT32=constants.SHIFT32,SYMS=constants.SYMS,TAG=constants.TAG,HALF=constants.MT.SIMPLE_FLOAT<<5|constants.NUMBYTES.TWO,FLOAT=constants.MT.SIMPLE_FLOAT<<5|constants.NUMBYTES.FOUR,DOUBLE=constants.MT.SIMPLE_FLOAT<<5|constants.NUMBYTES.EIGHT,TRUE=constants.MT.SIMPLE_FLOAT<<5|constants.SIMPLE.TRUE,FALSE=constants.MT.SIMPLE_FLOAT<<5|constants.SIMPLE.FALSE,UNDEFINED=constants.MT.SIMPLE_FLOAT<<5|constants.SIMPLE.UNDEFINED,NULL=constants.MT.SIMPLE_FLOAT<<5|constants.SIMPLE.NULL,MAXINT_BN=new Bignumber("0x20000000000000"),BUF_NAN=Buffer.from("f97e00","hex"),BUF_INF_NEG=Buffer.from("f9fc00","hex"),BUF_INF_POS=Buffer.from("f97c00","hex");class Encoder{constructor(options){options=options||{},this.streaming="function"==typeof options.stream,this.onData=options.stream,this.semanticTypes=[[URL,this._pushUrl],[Bignumber,this._pushBigNumber]];const addTypes=options.genTypes||[],len=addTypes.length;for(let i=0;i<len;i++)this.addSemanticType(addTypes[i][0],addTypes[i][1]);this._reset()}addSemanticType(type,fun){const len=this.semanticTypes.length;for(let i=0;i<len;i++){if(this.semanticTypes[i][0]===type){const old=this.semanticTypes[i][1];return this.semanticTypes[i][1]=fun,old}}return this.semanticTypes.push([type,fun]),null}push(val){return!val||(this.result[this.offset]=val,this.resultMethod[this.offset]=0,this.resultLength[this.offset]=val.length,this.offset++,this.streaming&&this.onData(this.finalize()),!0)}pushWrite(val,method,len){return this.result[this.offset]=val,this.resultMethod[this.offset]=method,this.resultLength[this.offset]=len,this.offset++,this.streaming&&this.onData(this.finalize()),!0}_pushUInt8(val){return this.pushWrite(val,1,1)}_pushUInt16BE(val){return this.pushWrite(val,2,2)}_pushUInt32BE(val){return this.pushWrite(val,3,4)}_pushDoubleBE(val){return this.pushWrite(val,4,8)}_pushNaN(){return this.push(BUF_NAN)}_pushInfinity(obj){const half=obj<0?BUF_INF_NEG:BUF_INF_POS;return this.push(half)}_pushFloat(obj){const b2=Buffer.allocUnsafe(2);if(utils.writeHalf(b2,obj)&&utils.parseHalf(b2)===obj)return this._pushUInt8(HALF)&&this.push(b2);const b4=Buffer.allocUnsafe(4);return b4.writeFloatBE(obj,0),b4.readFloatBE(0)===obj?this._pushUInt8(FLOAT)&&this.push(b4):this._pushUInt8(DOUBLE)&&this._pushDoubleBE(obj)}_pushInt(obj,mt,orig){const m=mt<<5;return obj<24?this._pushUInt8(m|obj):obj<=255?this._pushUInt8(m|NUMBYTES.ONE)&&this._pushUInt8(obj):obj<=65535?this._pushUInt8(m|NUMBYTES.TWO)&&this._pushUInt16BE(obj):obj<=4294967295?this._pushUInt8(m|NUMBYTES.FOUR)&&this._pushUInt32BE(obj):obj<=Number.MAX_SAFE_INTEGER?this._pushUInt8(m|NUMBYTES.EIGHT)&&this._pushUInt32BE(Math.floor(obj/SHIFT32))&&this._pushUInt32BE(obj%SHIFT32):mt===MT.NEG_INT?this._pushFloat(orig):this._pushFloat(obj)}_pushIntNum(obj){return obj<0?this._pushInt(-obj-1,MT.NEG_INT,obj):this._pushInt(obj,MT.POS_INT)}_pushNumber(obj){switch(!1){case obj==obj:return this._pushNaN(obj);case isFinite(obj):return this._pushInfinity(obj);case obj%1!=0:return this._pushIntNum(obj);default:return this._pushFloat(obj)}}_pushString(obj){const len=Buffer.byteLength(obj,"utf8");return this._pushInt(len,MT.UTF8_STRING)&&this.pushWrite(obj,5,len)}_pushBoolean(obj){return this._pushUInt8(obj?TRUE:FALSE)}_pushUndefined(obj){return this._pushUInt8(UNDEFINED)}_pushArray(gen,obj){const len=obj.length;if(!gen._pushInt(len,MT.ARRAY))return!1;for(let j=0;j<len;j++)if(!gen.pushAny(obj[j]))return!1;return!0}_pushTag(tag){return this._pushInt(tag,MT.TAG)}_pushDate(gen,obj){return gen._pushTag(TAG.DATE_EPOCH)&&gen.pushAny(Math.round(obj/1e3))}_pushBuffer(gen,obj){return gen._pushInt(obj.length,MT.BYTE_STRING)&&gen.push(obj)}_pushNoFilter(gen,obj){return gen._pushBuffer(gen,obj.slice())}_pushRegexp(gen,obj){return gen._pushTag(TAG.REGEXP)&&gen.pushAny(obj.source)}_pushSet(gen,obj){if(!gen._pushInt(obj.size,MT.ARRAY))return!1;for(const x of obj)if(!gen.pushAny(x))return!1;return!0}_pushUrl(gen,obj){return gen._pushTag(TAG.URI)&&gen.pushAny(obj.format())}_pushBigint(obj){let tag=TAG.POS_BIGINT;obj.isNega