{"version":3,"file":"static/chunks/7135-309dfd74ad37bbb6.js","mappings":"uKAKA,gBAAqC,GAAY,CACjD,EACA,YACA,GACA,cACA,KACA,QACA,UACA,mBACA,mBACA,SACA,CACA,cACA,mCACA,gCACA,CACA,cACA,mBACA,+CACS,QAAmB,kBAC5B,mCACA,8BACA,iBACA,cACO,EAEP,0CAAgE,QAAO,kBAA8B,QAAO,2BAC5G,aACM,mCACN,gCAEA,CACA,gBACA,qBACA,6BAEA,CACA,oBACA,UACA,UACA,CACA,mBACA,eAEA,QACA,8BACA,eACA,UACA,SACA,CACA,YAKA,OAJA,UACA,8BACA,+DACA,0BACA,kBACA,CACA,KACA,sBAAkD,OAAe,EACjE,UACA,KACA,+BACA,+BACA,2BACA,yBACA,mBACA,iBAEA,CACA,MACI,IAAa,YACjB,iCACA,wBACA,kBACA,qBACA,gCACA,sCACU,oBACV,+BACA,oBACA,OACA,QACA,EACA,GAGA,CACA,2BACA,UACA,CAAO,CACP,CAAK,CACL,CACA,wBCnFO,SAAS,EAMd,EACA,GACwD,IAClD,EAAS,QAAc,CAAC,GAExB,CAAC,EAAQ,CAAU,IAFgB,CAE1B,KAAU,CACvB,IACE,IAAI,EACF,EACA,IAIA,QANkB,GAMlB,CAAU,KACd,EAAS,WAAW,EACtB,EAAG,CAAC,EAAU,EAAQ,EAEtB,GAFqB,CAEf,EAAe,uBACb,cACJ,GACE,EAAS,UAAU,IAAa,CAAC,WAAW,IAC9C,CAAC,EAAQ,EAEX,IAFW,CADmD,CAG/C,iBAAiB,EAChC,IAAM,EAAS,iBAAiB,GAG5B,EAAe,cAGnB,CAAC,EAAW,KACV,EAAS,OAAO,EAAW,GAAe,MAAM,GAAI,CAAZ,EAE1C,CAAC,EAAQ,EAGX,GACE,CAJS,CAIF,OACP,OAAgB,CAAC,EAAS,QAAQ,aAAc,CAAC,EAAO,KAAK,CAAC,EAE9D,CADA,KACM,EAAO,MAGf,MAAO,CAAE,GAAG,SAAQ,EAAQ,YAAa,EAAO,OAClD,sBChEA,mBACA,YACA,wCACA,2BACA,CAAC,UAA8B,oJCK/B,EAAgC,mCAAiC,CACjE,EAA8B,iCAA+B,CAC7D,EAAoB,uBAAqB,CACzC,EAAe,kBAAgB,CAC/B,QAEA,SAKA,eAEA,aAAuB,mCAAiC,CAExD,0BAEA,aAEA,8BAEA,wCACA,mBAEA,8CADA,0CAEA,2BACA,+EACA,sEACA,kCAAmD,GAAU,SAC7D,CAOA,oBAMA,OALA,gBACA,MACA,yBAA6C,uBAAqB,oBAClE,oBACA,CAAS,EACT,KAOA,cAEA,OADA,gBAAyB,gBAAwB,EACjD,KAOA,kBAEA,OADA,gBAAyB,wBAAgC,EACzD,KAOA,kBAEA,OADA,gBAAyB,wBAAgC,EACzD,KAOA,kBAEA,OADA,gBAAyB,wBAAgC,EACzD,KAOA,mBAEA,OADA,gBAAyB,yBAAiC,EAC1D,KAOA,oBAEA,OADA,gBAAyB,0BAAkC,EAC3D,KAOA,iBAEA,OADA,gBAAyB,uBAA+B,EACxD,KAOA,kBAEA,OADA,gBAAyB,wBAAgC,EACzD,KASA,gBAEA,OADA,gBAAyB,oBAA4B,EACrD,KASA,gBAEA,OADA,gBAAyB,+BAAwC,+BAA6B,qBAAsB,EACpH,KASA,gBAEA,OADA,gBAAyB,+BAAwC,+BAA6B,qBAAsB,EACpH,IACA,CAUA,cAEA,OADA,gBAAyB,oBAA4B,EACrD,KASA,0BAEA,OADA,gBAAyB,uBAA+B,EACxD,KASA,0BAEA,OADA,gBAAyB,kCAA2C,+BAA6B,qBAAsB,EACvH,KASA,0BAEA,OADA,gBAAyB,kCAA2C,+BAA6B,qBAAsB,EACvH,KASA,wBAEA,OADA,gBAAyB,uBAA+B,EACxD,KAOA,4BAEA,OADA,gBAAyB,mBAA2B,EACpD,IACA,CAMA,6BAEA,OADA,gBAAyB,mBAA2B,EACpD,KAOA,UAEA,OADA,oBAAyB,aAAkB,EAC3C,KAGA,cAaA,OAZA,eACA,YAEA,mBAEA,0BAEA,sBACA,yDAEA,GAGA,CACA,0BACA,SACA,WAAyB,QAAW,WACpC,WACA,sBACA,sBAMA,GALA,QACA,yDACA,mBACA,yCAEA,iBACA,yCAEA,CAGA,wBACA,wCAA0D,OAAmB,6CAC7E,2BACA,CACA,6CACA,sDAWA,GATA,qBACA,qCAGA,8BAAkE,6BAA2B,CAC7F,YACA,uCAEA,aACA,4CACA,+BAA2C,OAAS,kCAA+B,SAAc,GAEjG,QACA,CAMA,6BACA,SACA,KACA,KACA,iBACA,wBACA,yGAEA,gCAAqD,KAAQ,KAC7D,gBACA,eAEA,GAAoB,8BAA4B,qCAEhD,wBACA,UACA,QACA,CACA,8CAA8D,KAAO,iBAAiB,cAAmB,EACzG,CACA,SAIA,KAJA,CACA,UACA,QACA,CAKA,iBACA,wCAGA,uBACA,CADkE,CAClE,iCACA,CADyF,OAEzF,CACA,cACA,QACA,MACA,SACA,SACA,oBACA,gBACA,SACA,oCACA,cACa,CACb,CACA,UAA8B,mCAAiC,CAC/D,4CACA,qCACA,wBACA,mCACA,6EACA,kBACA,OACA,0BACA,qCACA,+EACA,oBACA,OAuCA,OAtCA,iBACA,QACA,gBACA,kBACA,yBAA6C,+BAA6B,QAC1E,gCACA,kDACA,sDACA,2BAA6C,GAAU,kBACvD,kBACA,eACA,iBACA,sDACA,oBACA,EACA,qCAAmG,IAAiB,EACpH,EACA,OACA,gEACA,4EACA,kEACA,8EACA,gBACA,SACA,SACA,oBACA,gBACA,SACA,yBACA,cACA,uBAEA,YACA,aACA,cACA,CAAS,EAGT,wEACA,CACA,kBACA,MAAoB,qDAAmD,EACvE,cACA,cACA,0BACA,oCACA,iBACA,CAAS,EACT,qCACA,CACA,sBACA,MAAoB,yDAAuD,EAC3E,cACA,cACA,uBACA,sBACA,oBACA,eACA,kCACA,iCACA,kBACA,kBACA,gBACA,oBACA,iBACA,CAAS,EACT,qCACA,CACA,sBACA,MAAoB,yDAAuD,EAC3E,cACA,6BACA,kBACA,kBACA,kBACA,gBACA,oBACA,6BACA,CAAS,EACT,qCACA,CACA,uBACA,MAAoB,0DAAwD,EAC5E,cACA,6BACA,iBACA,CAAS,EACT,qCACA,CACA,sBACA,MAAoB,yDAAuD,EAC3E,cACA,6BACA,uBACA,qBACA,iBACA,CAAS,EACT,qCACA,CACA,wBACA,MAAoB,2DAAyD,EAC7E,cACA,cACA,6BACA,gBACA,kBACA,gCACA,kCACS,EACT,qCACA,CACA,4BAwBA,EAvBA,qCACA,wBACA,mCACA,6EACA,kBACA,OACA,0BACA,qCACA,+EACA,oBACA,OACA,GACA,cACA,kBACA,eACA,yBAA6C,+BAA6B,QAC1E,6BACA,+CACA,mDACA,2BAA6C,GAAU,kBACvD,kBACA,cACA,EAEA,UACA,uDACA,2FAEA,EAAkB,4CAA0C,EAC5D,KACA,mCACA,oDAAoH,IAAiB,EACrI,EACA,mDACA,+DACA,qDACA,iEACA,kBACA,cACA,CAAa,CACb,MAEA,EAAkB,0CAAwC,EAAG,gBAA+B,EAE5F,qCACA,CACA,iBACA,MACA,kBAEA,sCACA,EAAkB,6DAA2D,EAC7E,cACA,kBACA,4BACA,oBACA,4BACA,0CACA,kBACA,oBACA,8BACa,EACb,kBACA,eAEA,MAEA,EAAkB,6DAA2D,EAC7E,cACA,kBACA,4DACa,EAEb,qCACA,CAEA,oBACA,eACA,UACA,8BACA,mBACA,uCACA,UACA,yCACA,cACA,kCACA,oBACA,wCACA,cACA,uCACA,gBACA,yCACA,aACA,gCAAkD,iCAA0C,SAC5F,cACA,gCAAkD,wDAAqE,SACvH,SACA,6BACA,SACA,mCACA,CACA,CACA,8BACA,4BACA,UAEA,kBACA,4BAEA,yBACA,0CAEA,qFACA,8CAA2E,YAAa,CACxF,CAMA,0BACA,sCACA,KACA,UACA,UACA,uBACA,yDAGA,CACA,+BACA,IACA,eACA,qBACA,sBACA,mCACA,GACA,2BACA,kBACA,oCACA,iBAEA,CAAiB,CACjB,MAhBA,oCAkBA,YAAwB,WAAyB,KACjD,yCACA,GACA,UACA,CACA,oBAAiB,0BACjB,CAIA,cACA,2DAWA,cACA,0BAAqC,yCAAuC,WAC5E,sCAEA,KACA,uBACA,8CAGA,cACA,kBACA,2BAEA,0CACA,GACA,UACA,CAAa,EACb,sBACA,CACA,OAAiB,iFACjB,CAMA,gBAEA,OADA,aAAuB,mCAAiC,CACxD,kBACA,CAMA,cACA,wCACA,oCACA,eACA,qDACA,YAAoB,GAAa,gCACjC,OACA,CACA,aAAqB,QAA6B,EAClD,aACA,2BACA,iCACA,oDACA,CAAS,YACT,CAUA,iBACA,mBACA,CACA,kBACA,IAAgB,0BAAwC,MACxD,mBAEA,MACA,0BACA,gBAEA,qCACA,4BACA,sBAAqC,uBAA8C,CAEnF,kCAIA,mBAEA,kBAAgB,sBAAkC,mDAClD,aACA,KACA,GAAgB,GAAM,OACtB,CACA,wBACA,cACA,oBACA,2CACA,UACA,iBACA,eACA,cACA,CAAqB,CACrB,EACA,OACS,GACT,kBACA,sBAEA,YADA,wCAAyE,mCAA+C,gBAAgB,iBAA2B,EAMnK,OAJgB,GAAM,QACtB,MAAsB,GAAM,kBAAkB,GAAS,qCAAsB,EAAkB,EAE/F,qBACA,CACA,CACY,GAAM,QAAU,GAAM,WAClC,MAAkB,GAAM,kBAAkB,GAAS,qCAAsB,EAAkB,EAE3F,mCACA,OACA,4DACA,eACA,yBACA,QAAqB,EAAM,oDAC3B,mBACA,cAAuC,IAAiB,CACxD,CACA,CAQA,mBACA,SAA+B,WAAc,GAAG,SAAY,EAAE,+BAA4C,QAAM,SAAY,EAE5H,WADA,cACA,SACA,CACA,CAEA,cAAkC,oCAAkC,kGClwBpE,EAAgB,mBAAiB,CACjC,EAA4B,+BAA6B,OAMzD,EACA,eAEA,wBAEA,MAEA,gBACA,4EAEA,CAAa,CAEb,gBACA,iFAEA,EAEA,WAEA,MACA,iBACA,oCACA,gCACA,8CACA,sBAA0D,2CAAwC,EAClG,yCACA,sEAAgG,gDAAmD,GACnJ,aACA,EAAqB,EACrB,OACA,iCACA,cACyB,EACzB,QACA,KACA,KAEA,CACA,CAAiB,CACJ,CASb,iBACA,oCACA,gCACA,8CACA,uCAAsD,0BAAwC,EAC9F,oIAAqK,gDAAmD,GAAI,QAAc,2BAC1O,OACA,iCACA,cACqB,EACrB,QACA,KACA,IACA,CACA,CACA,CAAa,EAEb,cAAwB,GAAS,6BACjC,4CACA,0BACA,+BACA,oCACA,oCACA,0CACA,4BACA,4BACA,2CACA,CAEA,cACA,qBAGA,cACA,qBAGA,eACA,sBAiBA,aACA,2BAaA,gBACA,2EACA,uEACA,6CACA,uCAA8C,0BAAwC,EACtF,2CACA,KACA,8DACA,oBAAuC,6DAAgE,EACvG,yBAA4C,8DAAgE,EAC5G,uDACA,yCACA,8CACA,uDACA,yCACA,8CACA,UACA,8BACA,sBACA,YACA,WACA,CAAa,CACJ,EACT,yBACA,cACA,kBACS,EACT,GACA,KACA,IACA,EACA,OACA,YACA,QACA,KACA,oBACA,gCACA,0CAC8B,QAAmB,UAAgB,QAAc,6DAC/E,OACA,0CAC8B,QAAmB,UAAgB,QAAc,6DAC/E,OACA,OACA,2EACsB,QAAmB,gBAAsB,QAAc,6DAC7E,MACA,CAAa,CAEb,CASA,oBACA,WAAmB,GAAS,EAC5B,KACA,wBACA,sBACA,iCACA,mDACA,mDACA,+DACA,sDACS,CACT,CAUA,gCACA,OAAe,GAAS,qBACxB,KACA,wBACA,sBACA,iCACA,mDACA,+DACA,sDACS,CACT,CAQA,sBACA,OAAe,GAAS,mCACxB,sBACA,0CACA,oCACS,CACT,CAKA,mBACA,mDACA,2CAA2D,+FAE3D,OACA,0CACA,oCAEA,CAKA,oBACA,mDACA,4CACA,CACA,wBACA,qCAA0D,EAAM,sEAEhE,iCAAsE,IAAuB,CAAG,IAAuB,EAGvH,yGACA,8HACA,CACA,mBACA,OAEA,iBACA,0BAAsD,iEAAgF,EACtI,0BACA,KACA,4DACA,kBACA,yDACA,kDACA,uDACA,gDACqB,CACrB,kCACA,sCACiB,wBACjB,CAAa,CAEb,gBACA,2CAGA,gBACA,2CAEA,MAEA,gBACA,oBACA,KACA,6DACA,mBACA,yDACA,kDACA,uDACA,gDACyB,CACzB,uBAAiD,kEAAiF,EAC7G,0BAGrB,gBACA,4CAGA,gBACA,2CAEA,CAAa,CAEb,CAEA,0BACA,IACA,gBACA,CACA,SACA,8BACA,CACA,CAUA,iBACA,YAA6B,GAAS,6CAOtC,OANA,oBACA,uDAEA,iBACA,iDAEA,CACA,CACA,mBACA,OACA,KACA,iCACA,2CACA,YACA,CACA,CACA,kBACA,OACA,KACA,gCACA,yCACA,OAAoB,QAAc,yBAClC,6DACA,YACA,CACA,CACA,uCACA,MAAkB,QAAc,kBAChC,sBACA,gBACA,cAEA,uDACsB,KAAwB,yDAC9C,EAEA,qBACA,MACA,GACA,YADA,SAEA,OAA+B,KAAkB,EAAO,kEAExD,gDAA2E,UAAqB,8BAEhG,CACA,uDAAuE,cAAkB,IAAM,GAAG,oBAAoB,OAAO,EAC7H,CAAS,CACT,CAGA,aACA,4BACA,8FAA8G,cAAc,GAE5H,6BACA,CAIA,eACA,iEACA,CAWA,iCACA,cACA,OAAiB,YAAwB,QAAmB,mCAC5D,CACA,8ECnZA,MAAgB,mBAAiB,CA8FjC,cACA,6DACA,CAEA,cACA,sBACA,sCACA,SAEA,yCAAoE,gBACpE,OACA,iBACA,6BACA,iBACA,kBACA,OACA,yDACA,CACA,8CCrHA,OACA,oBACA,kBACA,kBACA,cAAsB,CACtB,oBAGA,eACA,aACA,aAKA,cACA,aACA,aACA,cACA,cAGA,cACA,aAGA,MAAoB,CAGpB,OAEA,wBAAoD,CAEpD,uBAAmD,CAEnD,uBAAmD,CAEnD,0BAAsD,CAEtD,wBACA,qGCtCA,iBAA0B,mBAAiB,CAC3C,eACA,SACA,cACA,0BACA,KACA,KAAkB,8BAA4B,UAAc,4BAA0B,gBAAwB,iBAAe,aAC7H,EAAS,EACT,cACA,uBACA,8CAAiE,iBAAe,+BAChF,CACA,CACA,SACA,mBAEA,CAMA,gBACA,WAAe,sBAAoB,kCACnC,UACA,eACc,iBAAe,cAC7B,aACA,CAQA,kBACA,kCAAkD,cAAiB,MACnE,WACA,OACA,EACA,6CAEA,iCADA,KAEA,CACK,EACL,CAOA,kBACA,eAA+B,cAAiB,IAChD,WACA,+BAEA,iCADA,CAEA,CAAK,CACL,CASA,wBACA,mCACA,EACA,gBACe,EAAM,0BACrB,gBACe,iBAAe,0BAC9B,KAEA,EADA,oBACA,QAEW,iBAAe,kBAC1B,CAQA,kBACA,+CACA,SACA,mBACA,OAAe,iBAAe,0BAC9B,oCACA,sBACA,OAAmB,EAAM,gBACzB,kDACA,wCAAwD,EAAK,YAAY,EAAM,GAC/E,QACA,CACA,SACA,gBACA,qBAIA,6BAHA,WAKA,CACA,OAAW,iBAAe,kBAC1B,CAQA,gBACA,MACA,mBAWA,CACA,4BAAkD,mBAAiB,wBACnE,MACA,qCAAqD,GAAuB,KAAK,QAAc,OAC/F,GACA,KAhBA,CACA,sCACA,gBACA,qCAAqD,GAAuB,KAAK,QAAc,OAC/F,cACA,yCAAyD,GAAuB,cAAc,OAAa,yCAAyC,2CAA2C,UAC/L,WAAgC,mBAAiB,oBACjD,WAA4B,GAE5B,OAQA,eACA,CASA,kBACA,8BACA,mCACA,kBACA,oBAEA,yDAEA,eACA,iBACA,gBACe,EAAM,yCACrB,gBACe,iBAAe,yCAC9B,KACA,wBAEA,8MEtKA,EAAe,kBAAgB,OAE/B,EAKA,eACA,4BACA,aACA,CAYA,qBACA,+BACA,mCAEA,sDACA,GACA,OACA,kBACA,oBACA,qCAAkD,EAAM,yBACxD,cAA2B,mBAAiB,aAC5C,EAEA,OADA,8BACA,CACA,CAeA,iCACA,6BAKA,OAJA,mCACA,GACA,sDAEA,yBACA,CAOA,wBACA,mCAaA,iBACA,gGACA,OACA,mBACA,WAAwB,+BAA6B,OACrD,yCACA,6CACA,yBACA,wDACA,mEACA,0DACA,qEACA,wDACA,sDACA,CACA,CAOA,wBACA,0CASA,yBACA,4HACA,8BACA,yCAEA,iDACA,CAMA,qBAEA,MADA,wDACA,aACA,EACA,eACA,WAA4B,EAAM,gCAClC,KAAsB,EAAM,8BAC5B,GAEA,CAOA,uBACA,oDACA,4BAEA,OADA,6DACA,MAQA,wBACA,qEACA,CAMA,gCACA,UAAgB,oBAAuB,EACvC,8BACA,kBACA,CAMA,iCACA,UAAgB,qBAAwB,EACxC,2EAAqG,yBAAsB,GAC3H,CAMA,0BACA,yCAA8E,iBAC9E,OACA,yBACA,6BACA,iCACA,kBACA,OACsB,uBAAqB,wBAE3C,CAOA,yBACA,SAEA,oBAMA,EACA,EANA,YACA,EAA2B,EAAM,iBACjC,sBACA,UACA,+BAGA,UACA,OACA,cACA,EAA+B,EAAM,iBACrC,MACA,SACA,YACA,2BACA,cACA,yBACA,EACA,KACA,SACA,eACA,OACA,SACA,YACA,eACA,EACA,KACA,CACA,QACA,mDAA2E,EAAa,EACxF,CACA,CACA,QACA,CAOA,yBACA,mCACA,OAGA,OACA,QACA,SACA,6BACA,EACA,MAAe,QAAiB,CAAC,mCAAiC,4BAClE,CAcA,uDACA,yBACA,eAA2C,IAAuB,EAClE,kFAAsG,IAAuB,EAAE,2BAE/H,MAAyE,IAAuB,6BAChG,CACA,yBACA,eAA2C,IAAuB,EAClE,kFAAsG,IAAuB,EAAE,2BAE/H,MAAyE,IAAuB,6BAChG,CACA,QACA,CAUA,sCACA,cACA,gBACA,WACA,UAAsC,uBAA0B,EAGhE,0CACA,kCAAyF,EAAM,YAAc,gCAAqC,IAGlJ,2BACA,KAA2B,EAAM,gCAAsC,EACvE,sBACA,KAA+B,EAAM,wBAA6B,EAClE,aACA,CAEA,QACA,CAOA,4BACA,UACA,uBACA,WACA,EAEA,sBACA,EACA,SACA,YACA,aACA,UACA,CACA,CAKA,oBACA,4BACA,IACA,KACA,KACA,WACA,WACA,kCAEA,UAEA,6BAEA,UAEA,eAEA,UAEA,WAEA,UAEA,6BAEA,SAEA,IACA,CAEA,EACA,UACA,IACA,gCACA,gBACA,kCACA,CACA,MACA,QACA,CACA,EACA,kBACA,SACA,oBAEA,aADA,cACA,CACA,gBACA,wBACA,mBACA,iBACA,IAEA,QACA,eACA,cACA,MAEA,aACA,uBACA,iBACA,KAAsB,EAAO,EAAE,EAAY,EAAE,EAAO,EACpD,IACA,CACA,WACA,CACA,mBACA,CACA,oBACA,eACA,IACA,WACA,iBACA,cACA,MAEA,iBACA,wBACA,wBACA,SAEA,GACA,CAEA,EACA,cACA,4CACA,8DC3YA,0BACA,mBACA,iBACA,MAAoB,iBAEpB,sBACK,KACL,QACA,oCACA,cACA,SArCA,KAyCA,OAHA,GACA,mBAEA,CACA,CAAK,CACL,CAuCA,wBACA,QACA,cACA,iBACA,MAAoB,iBAKpB,OAHA,sBACA,uBAEA,eACK,KACL,4CA7FA,KAiGA,CAjG4D,MA8F5D,GACA,mBAEA,CACA,CAAK,EACL,OACA,kBACA,gBACA,cACA,CACA,CAGA,iBAEA,SAEA,EADA,SAGA,QACA,WACA,eACA,OACA,2BAGA,aAEA,CADA,qBAHA,KAOA,CACA,QACA,uCCxHA,SAOA,mBACA,yBACA,mBACA,0BACA,eACA,CAcA,gBACA,aAAgB,uIAAiJ,EAQjK,GANA,cAAgD,GAAmB,WACnE,SAAsB,IAAoB,CAC1C,OACA,UACA,CAAS,EAET,wBACA,sEAAsF,WAA6B,wCAAwC,SAAoB,GAE/K,sBACA,sKAEQ,GAAM,+DAAwE,OAAc,iBAAiB,UAAqB,QAAQ,0BAAqC,WAAW,+DAAiF,MAAM,4BAAuC,WAAW,8DAAgF,GAE3Z,yCACA,kEACA,OACA,8CACA,uCACA,kEACA,OACA,gDAEA,YACA,0BACA,6CAAgE,gDAAoE,EACpI,mCAAsD,iDAAoE,EAC1H,GACA,cACA,wBACA,KACA,kBACA,mDACA,mDACA,UACA,EAEA,OADA,iCACA,CACA,4BACA,mBACA,gBACA,KACA,KAEA,EACA,YACY,GAAM,qDAA8D,QAAe,UAAU,UAAqB,aAAa,UAAiB,IAC5J,0BACA,6CACA,cACA,kBACA,oBACA,KACA,KACiB,EACjB,mCACA,cACA,kBACA,oBACA,KACA,MACiB,EACjB,GACA,cACA,wBACA,kCACA,4BACA,mDACA,KACA,UACA,EAEA,OADA,iCACA,CACA,4BACA,mBACA,gBACA,KACA,KAEA,EACA,YACY,GAAM,mDAA4D,QAAe,UAAU,WAAsB,6BAA6B,UAAiB,IAC/J,GAAM,qDAA8D,QAAe,cAAc,SAAmB,OAAO,UAAqB,WAC5J,wCACA,cACA,0BAAkD,2CAAqD,EAGvG,gBAAwC,2CAAqD,EAE7F,qBACA,cACA,0BAAkD,mBAA2C,EAG7F,gBAAwC,mBAA2C,EAEnF,oBAAiD,oBAAkC,EACnF,0BACA,yBACA,wBACY,GAAM,qDAA8D,UAAoB,wBAAwB,oBAA+B,MAAM,UAA0B,wBAAwB,SAAmB,OAAO,UAAqB,WAClQ,OACA,iCACA,WAA4B,+BAA6B,qBACzD,KACA,kBACA,sCACA,sCACA,UACA,EAEA,OADA,iCACA,CACA,6BACA,KACA,mBACA,gBACA,cACA,eACA,0CACA,mDACA,KACA,cAAgC,kDAA2E,CAE3G,EAGA,EADA,iDACA,aACA,iBAEA,OADY,GAAM,uCAAgD,QAAe,+BAA+B,WAAsB,6BAA6B,UAAiB,IACpL,UAEQ,GAAM,gDAAyD,QAAe,mBAAmB,SAAoB,gBAAgB,SAAmB,cAAc,UAAoB,IAClM,8CACA,EAAiC,EAAM,2CACvC,EAA8B,EAAM,6CACpC,EAA4B,EAAM,2BAClC,EAAyB,EAAM,2BAO/B,GAJA,sCACA,wCACA,kDACA,mDACA,CAUA,GATY,GAAM,gFAAyF,QAAkB,IAC7H,MACA,wBACA,oCACA,sBACA,kCACiB,CACjB,YACa,EACb,4BAA6F,IAAa,MAC1G,iNAIA,kBAAgE,IAAa,YAC7D,GAAM,6FACtB,YAEA,YACgB,GAAM,oIAGN,GAAM,+IAEtB,WACA,CACA,GAhCA,aAgCA,CAEA,GADY,GAAM,iEAA0E,SAAmB,cAAc,SAAoB,GACjJ,4BAA8E,IAAQ,MACtF,mHAEA,qBAAsD,IAAQ,WAE9D,OADgB,GAAM,wFACtB,UAEA,qBAAsD,IAAQ,WAO9D,OANA,YACoB,GAAM,4FAGN,GAAM,yIAE1B,WAEA,sBAAuD,IAAQ,YAO/D,OANA,YACoB,GAAM,sHAGN,GAAM,iKAE1B,UAEA,CAEA,OADQ,GAAM,+EACd,CAAiB,kCACjB,CACA,qBACA,8BACA,EAIA,iBAHA,wBAA2C,gBAAyB,YAAmC,CAKvG,CAcA,gCACA,SACA,+BACA,+BAEA,kBACA,wHAGA,aAAmC,EAAwC,kBAC3E,OAEA,EAAqB,WAHsD,CAGtD,8DAErB,+CAEA,mCAEA,YAA0C,EAAkB,mBAC5D,2BACA,OAAwB,yBAAuB,OAC/C,4BACA,WACA,sBACA,WAA4B,EAAM,KAAM,IAAoB,uBAI5D,wBAEA,wEACA,iBACA,wBACA,wDAEA,qDAEA,qDACA,QAGA,YAAqB,yDADrB,IAEA,CAAS,IAET,oBACA,YAEA,eAAoB,yDAAiE,EACrF,MACA,MAEA,OAGA,MADA,kBACA,OAAoD,EAAM,SAC1D,EAAqC,EAAM,mCAC3C,mBAAgD,IAAoB,CAAC,GAAG,GAGxE,8BAAyD,IAAoB,WAC7E,EACA,IACA,gBACA,YACA,SACA,YACA,WACA,WAAoC,+BAA6B,OACjE,kBACA,6CACA,QACA,+CACA,qBACA,EAEA,CACA,SACgB,GAAM,2DAA2D,MAAe,cAAc,IAAiB,qBAC/H,MACA,CACA,CAAS,EACT,OACA,UACA,MACA,EAEA,OADA,0BACA,CACA,CACA,oCCvVA,cACA,2DACA,sEKFA,oEHAA,iBAEA,OAAM,EAEN,aACA,QAHqB,GAGrB,SAGA,sBACA,6BAGA,WACA,kBAEA,aACA,oBAEA,iBACA,eACA,wBACA,WAAqB,yBAAuB,IAC5C,aAAuB,8CAA4C,kBACnE,CAMA,QACA,0BACA,mCAEA,EADA,EAC4B,uCAAqC,2BAGrC,iCAA+B,2BAI3D,QACA,CACA,CAEA,MAAM,EAIN,WACA,SALoB,EAKpB,SAKA,SACA,wBAKA,aACA,oBAKA,aACA,OACA,kBACA,oBAEA,CACA,iBACA,gBACA,uBACA,aAAuB,2CAAyC,GAChE,CACA,oCChFA,uBACA,iBACA,SACA,gBACA,kCACA,eACA,CACA,CAMA,QAEA,kBAEA,IAAuB,EACvB,sBAKA,cADA,qBAA2E,EAAW,IAKtF,GAHA,YACA,sBAEA,sBACA,iEAEA,gBACA,kBACA,CASA,gBACA,EAUA,cATA,mBACA,EAEA,kBACA,IAAoC,EAAa,EAGjD,KAAqC,EAAa,EAElD,cACA,KACA,iCACA,wBAGA,mBACA,CACA,qCACA,SAIA,OAHA,kBACA,MACA,CAAS,EACT,CACA,CACA,+BACA,QACA,OAEA,WACA,OACA,IACA,wCAEA,iBAAuC,IAAM,oBAC7C,YACA,aAEA,CACA,MAEA,CACA,gDAAgE,UAAY,GAAG,aAAe,EAI9F,OAHA,GACA,SAA4B,GAAiB,EAE7C,SACA,+BACA,gBACA,+CACA,CAAS,CACT,CACA,oCAEA,OADA,6BACA,CACA,2CACA,gBACA,+CACA,CACA,CACA,kBAAsD,EAEtD,OACA,oBACA,uBACA,IACA,EACA,gCACA,YACA,SACA,CAAS,EACT,+BACA,CACA,qBAA6D,EAE7D,OACA,oBACA,uBACA,MAEA,gCACA,cACA,YACA,OACA,SACA,CAAS,EACT,+BACA,CACA,uBAA+D,EAE/D,OACA,oBACA,uBACA,MAEA,gCACA,gBACA,YACA,OACA,SACA,CAAS,EACT,+BACA,CACA,CC/IA,gBAAsC,EACtC,oBAD4D,CAC5D,MACA,EACA,QACA,GACA,IACA,WAEA,CACA,SACA,mBAIA,wCACA,iDACA,0EALA,QASA,4DACA,KACA,sCAEgB,GAAM,uCAAuC,GAAU,qBAAqB,EAAY,MAAM,EAAI,EAClH,OACU,sBAEV,QACA,CACA,kBAAsD,EACtD,qDACA,CACA,qBAA6D,EAC7D,wDACA,CACA,uBAA+D,EAC/D,0DACA,CACA,CACA,cACA,qBAGA,mDACA,qBACA,YACA,aACA,aACA,eACA,QACA,YACA,cACA,YACA,SACA,0BCvDA,wCAEA,YACA,kBACA,CAAC,YACD,OACA,UACA,UACA,WACA,kBACA,CAAK,CA4BL,OAAM,EACN,eACA,MAAiC,GAAO,SACxC,OAH+B,SAI/B,iCAEA,KACA,uBAGA,oGAAoH,GAA4B,iCAEhJ,yCAnDA,EAoDA,CACA,gBACA,uBAEA,qBACA,4BAYA,mDAEA,OACA,SACA,QAHA,CAA0B,wBAAyB,EAAU,GAI7D,mDACA,EACA,GACA,QAA+B,QAAM,KAErC,qBAAwC,mBAAmB,4BAAG,GAAU,IACxE,GADwE,CACxE,MACA,iDAA2E,SAAgB,EAC3F,OACA,IACA,gBACA,CACA,MAEA,CAQA,MAPA,UACA,SAEA,gBAEA,IADA,gBACA,SAEA,QACA,CACA,QACA,CASA,gBACA,gEAAoF,kBAAiD,GAAK,sDAAsG,SAChP,iBACA,OAAiB,4BACjB,CAMA,gBACA,4DAAuE,sBAAkC,QACzG,CAMA,iBACA,gEAAoF,kBAAiD,oBAErI,OAAiB,QADjB,gBACiB,OACjB,CACA,2BC/HA,EAAU,aAAW,CACrB,EAAc,iBAAe,CAC7B,EAAkB,qBAElB,OAAM,EAqBN,iBACA,SAtBmB,OAsBnB,EACA,EACA,CACA,MAAuB,EAAa,8BACpC,wBAAyD,EAAa,yCACtE,gBAAiD,EAAa,gCAC9D,CACA,qBACA,wBACA,gBACA,gBACA,CAEA,YACA,kBACA,CAEA,cACA,kBACA,4FACA,qBAGA,uBACA,qBAGA,UACA,cACA,oFACA,iBAWA,gBACA,yBACA,kEAEA,oCACA,OACA,wEACA,wEACA,WAAwB,EAAa,iCACrC,sBACA,0BAEA,CAMA,8BACA,MAAe,OAAmB,GAClC,CAKA,mBACA,wCAMA,kBACA,uCAMA,kBACA,uCAkBA,uBACA,WAAmB,EAAyB,EAC5C,CAgBA,qCAjB4C,CAkB5C,WAAmB,EAAyB,GAAY,mBAA2B,OACnF,CAsBA,UAvB4C,IAuB5C,GACA,mBACA,0FAEA,WAAmB,GAAU,EAAG,6BAAqC,CACrE,CAgBA,gCACA,mBACA,yFAEA,OAAe,GAAS,qBACxB,KACA,wBACS,CACT,CAaA,oBACA,mBACA,yFAEA,WAAmB,GAAS,EAAG,6BAAqC,CACpE,CAiBA,+BACA,mBACA,yFAEA,OAAe,GAAS,cAAe,6BAAqC,CAC5E,CAsBA,6CACA,mBACA,yFAEA,6BAAgD,6BAAqC,CACrF,CAcA,2BACA,mBACA,yFAEA,cAAiC,6BAAqC,CACtE,CAgBA,gCACA,mBACA,yFAEA,sBAAyC,6BAAqC,CAC9E,CAaA,wBACA,mBACA,0FAEA,cAAkC,6BAAqC,CACvE,CAkBA,4CACA,IAAa,GAAO,CAAK,EAAO,IAChC,gBADgC,qEACqE,4BAErG,WAAwD,EAAO,iBAC/D,CACgB,EAF+C,0BAElC,MACb,EAAO,mBAAsB,CAAtB,CAAmC,yCAC1D,EAAwB,sCAA0C,EAAO,qCAEzE,OADA,CAAwB,GAAG,EAAa,qCAAwC,GAAO,uBAEvF,CACA,CACgB,EAAa,kCACb,EAAa,oCACb,EAAa,gCAC7B,CACA,OACA,cACA,gBACA,WACA,CACA,CAKA,uCACA,IAAa,GAAO,CAAK,EAAO,IAChC,YADoB,IAAY,oEACoE,4BAEpG,IAAa,EAAO,iBACpB,GADoB,GACpB,iHAEA,OACA,OAAoB,EAAO,iBAC3B,GAD2B,EACT,EAAO,eACzB,KADyB,CACN,EAAO,gBAE1B,CAMA,GAR0B,IAQ1B,kCACA,IAAa,GAAO,CAAK,EAAO,IAChC,gBADgC,sEACsE,4BAEtG,IAAa,EAAO,mBACpB,CADoB,KACpB,qHAEA,OACA,OAAoB,EAAO,mBAC3B,CAD2B,IACT,EAAO,iBACzB,GADyB,GACN,EAAO,kBAE1B,CAMA,CAR0B,MAQ1B,uBACA,OACA,kBAA+B,EAAQ,GAAG,wBAAmC,kBAC7E,QACA,CACA,CAKA,mCACA,OACA,0BACA,0DACA,wEACA,CACA,CAqBA,yBACA,UAAgB,mBAAsB,EAEtC,MAAwC,EADxC,oBAA0D,CACK,kBADL,GAA4B,KAAc,CACrC,KAC/D,WAAmB,iBAAe,KAClC,CAWA,uCACA,OAAe,EAAa,eAAgB,EAAa,SAA7B,iBAA6B,MACzD,CA0BA,6BACA,UAAgB,mBAAsB,EAGtC,QADA,IAAwC,EADxC,oBAA0D,CACK,qBADL,GAA+B,KAAc,CACxC,MAI/D,OADA,6BACA,CACA,CAaA,0CACA,OAAe,EAAa,iBAAkB,EAAa,OAA/B,mBAA+B,UAC3D,CAYA,uBACA,UAAgB,mBAAsB,EACtC,mBACA,CAUA,qCAGA,OAAe,EAAa,cAAgB,GAAG,EAAa,OAAhC,mBAAgC,WAAwC,GAAO,sBAA2B,CACtI,CACA,CCthBA,MAAM,EAKN,eACA,oBANuB,EAOvB,IACA,gBAEA,MACA,gBACA,CACA,CACA,YACA,uBACA,2CACA,cAAwB,GAAY,EAAe,qCACnD,KAEA,OADA,UAAgC,EAAa,gBAC7C,UAD6C,IAI7C,UACA,CACA,cACA,oFAEA,iBAkBA,yBAEA,KACA,uBAGA,GAFA,uBAEA,8BACA,gBACA,OAEA,cACA,uDACA,kCACA,IACA,KACA,QAAwB,WAAsB,KAC9C,WAEA,KADA,4DAEA,KAEA,CAEA,eACA,OAEA,iDACA,EAAgC,6BAA2B,IAE3D,MAAmC,EADX,oBACyB,SADE,IACF,GACjD,OACA,UACA,YACA,eACA,CACA,CAwBA,oCAEA,qCACA,KACA,SAEA,uBAEA,yCACA,6DACA,iBAGA,qCACQ,GAAM,kCAAkC,EAAK,qBAAqB,kBAAkB,QAAc,2CAA2C,cAAwB,OAE7K,+CAYA,OAXA,UAAkB,GAAmB,EACrC,gCACA,uBACA,4EACA,CAAS,EACT,YACA,UAAgC,GAAU,WAC1C,gBACA,aACA,CAAS,EACT,OACA,CACA,CASA,oCACA,2CACA,8EAEA,sGACA,MACA,0DAA0E,2CAG1E,QACA,CACA,gBC3JA,EAAsB,yBAAuB,CAC7C,EAA8B,0BAAwB,CAOtD,MAAoC,QAAO,aAC3C,mBACA,SACA,WACc,8CAA4C,IAC5C,2CAAyC,GACvD,CAAC,CAED,OAAM,EASN,eACA,aAVoB,CAUpB,IACA,sBACA,4BAAsC,EAAiB,EACvD,CACA,gBACA,WAAmB,GAAmB,EAHiB,MAIvD,0BACA,oCACA,iFACA,CAAS,CACT,CAEA,UACA,8BACA,CAiBA,oBAEA,OADA,4CACA,KAMA,iBACA,OACA,mCACA,WACA,EAEA,OADA,yBACA,CAAiB,eACjB,CAmBA,wBAEA,OADA,sBACA,KAaA,eAEA,OADA,mBAAmC,iBACnC,KAUA,mBACA,iBACA,CAAgB,kCAChB,CAAgB,iCAEhB,CAcA,aACA,qDACA,MACA,2CAA2D,EAAO,GAClE,QACA,CAeA,cACA,wBACA,MACA,2CAA2D,EAAO,GAClE,QACA,CAcA,wBACA,UAAgB,uCAAyE,8GACzF,OACA,KAEA,QAAqB,GAAU,6BAC/B,4BAAyC,GAAU,kDACnD,WAAwB,GAAU,iCAClC,eAA4B,GAAU,qCACtC,QAAqB,GAAU,8BAC/B,yBACA,4CACA,gDACA,4CACA,gDACA,wFACA,6DACA,sEACA,6DACA,+CACA,6CACA,CACA,CAcA,kBACA,MAAwB,6BAA2B,IACnD,8BAAsC,EAAc,KACpD,CAaA,aACA,CAfoD,MAepD,oBAAoC,uBAAsC,CAC1E,CA4BA,2BACA,IAAa,GAAO,CAAK,EAAO,IAChC,aADoB,IAAY,gEACiE,yBAEjG,MAAgC,EAAO,OAAQ,cAAR,EAA2B,YAClE,EAAuB,EAAO,OAAQ,cAAR,EAA2B,UACzD,MACA,MAA2B,6BAA2B,IACtD,8BAA0C,EAAc,KACxD,CACA,2CACA,kEACA,oCACA,CACA,4CAAwD,gBAAmB,qCAAqC,EAAK,EACrH,CAgBA,gBAEA,KACA,4DACA,MACA,0CAA0D,EAAK,EAAE,uBAAmC,GACpG,oCACA,CAaA,cACA,8BAAsC,EAAe,KACrD,CAYA,cACA,CAdqD,MAcrD,8BACA,CAUA,SACA,0BAAkC,yBAAuB,GACzD,CAiBA,iCACA,IAAa,GAAO,CAAK,EAAO,IAChC,aADoB,IAAY,kEACmE,yBAEnG,OAAe,EAAO,OAAQ,EAAiB,YAAzB,EAAwC,CAAf,QAAe,GAC9D,2BAAyC,GACzC,cAD0D,cAC1D,EACA,CAUA,0BACA,kEACA,oCACA,CAuCA,0BACA,gCACA,YACA,KACA,mCACA,qCACA,OAAoB,GAAU,cAC9B,oCACS,EACT,QAMA,MAJA,oBACA,4CAEQ,GAAM,2CAAiD,GAAS,KAAK,GAAS,kBAAkB,eAAoB,GAC5H,CAAiB,2EACjB,CACA,oCACA,mCACA,6CACA,EAA6B,QAAmB,iCAChD,uBAAmD,GAAU,aAC7D,CAyBA,4BACA,kCACA,gEACA,MACA,OACA,gCACA,YACA,KACA,mCACA,WACA,QACA,CAAS,EACT,QACA,OACA,KACA,8BACA,gCACA,yBACA,cACA,CACA,CA+BA,yCACA,kCACA,wCACA,gEACA,MACA,OACA,gCACA,YACA,KACA,cACA,WACA,QACA,CAAS,EACT,QACA,OACA,KACA,8BACA,gCACA,yBACA,cACA,CACA,CAyBA,mDACA,0CACA,mFAEA,kCACA,gEACA,MACA,OACA,kCACA,OACA,aAA0B,GAAU,qBACpC,qBAEA,CACA,CClkBA,QAKA,eAoCA,gDAyCA,wDAoCA,wDA8BA,wDAgCA,0DAiCA,4DA4BA,sDAiCA,wDAiDA,oDAyCA,oDAuCA,oDAuCA,gDA6DA,yEAqDA,yEAmDA,yEAmDA,qEAEA,4EAEA,8EACA,gBACA,CACA,gBACA,iBACA,uBAEA,OADA,6CACA,mBACA,CACA,CACA,iBACA,iBACA,uBACA,kDACA,CACA,CACA,gDC3pBA,OAAM,EACN,eACA,aAFoB,qBAEpB,KACA,EADmD,EACnD,+BACA,wBAAkC,EAAa,QAC/C,kBAD+C,EAC/C,KAAmC,EAAc,qBACjD,OADiD,SACjD,KAA+B,GAAU,4BACzC,uBAAiC,GAAY,gDAC7C,4BAAsC,GAA+B,0DACrE,6BAAuC,EAAgC,qBACvE,SADuE,QACvE,KAAgC,GAAW,+EAC3C,CAMA,4BAEA,OADA,8BACA,KAOA,oBAEA,OADA,yCACA,KAiBA,wBAEA,OADA,6CACA,KAQA,eAEA,OADA,oCACA,KAQA,6BAGA,OAFA,8BACA,4FACA,KAOA,kCAEA,OADA,qCACA,KAGA,kCACA,gHAKA,wFACA,qGALA,CACA,8BACA,CAOA,CAEA,aACA,2BAGA,cACA,4BAGA,YACA,0BAGA,UACA,wBAGA,kBACA,yBAGA,WACA,WAAmB,GAAmB,EACtC,wBACA,uCACA,iDACA,kDACA,4BACS,CACT,CAIA,WACA,+BAKA,wBACA,+BACA,CAMA,yBACA,WAAmB,EAAc,CACjC,YAAyB,EAAa,aADL,WACK,UACtC,cAA2B,EAAa,oCACxC,UAAuB,EAAa,+BACpC,CAAS,CACT,CAKA,iBACA,WAAmB,EAAc,CACjC,YAAyB,EAAa,aADL,IACK,oBACtC,cAA2B,EAAa,uCACxC,gBACA,CAAS,CACT,CAKA,iBACA,WAAmB,EAAc,CACjC,YAAyB,EAAa,aADL,IACK,oBACtC,cAA2B,EAAa,uCACxC,gBACA,CAAS,CACT,CAMA,sBACA,WAAmB,EAAc,EACjC,CAkBA,yBAnBiC,OAoBjC,IAAmB,EAAe,EAAa,0BAAd,QAAc,GAC/C,CAMA,qBACA,WAAmB,EAAc,EACjC,CACA,CGtGA,gBACA,QHmGiC,CGlGvB,EAAa,sBACb,EAAa,EADA,wBACA,QACvB,UCnHA,uCACA,OAAW,GAAU,gBACrB,EACA,kCACA,OAAW,GAAU,WACrB,EACA,sCACA,OAAW,GAAU,gBACrB,EACA,iCACA,OAAW,GAAU,WACrB,EACA,sCACA,OAAW,GAAU,gBACrB,EACA,iCACA,OAAW,GAAU,WACrB,sBCb8B,0BAAwB,gGYHtD,gBAA6B,GAAS,CACtC,IACA,GACA,cACA,GACA,QACA,6BACA,wBACA,WACA,wBACA,2BACA,iBACA,CACA,cACA,eACA,sCACA,CACA,WACA,yBAEA,eACA,sBACA,gBACA,sBACA,gBACA,qBACA,cACA,UACA,CAAO,EAEP,CACA,kBACA,iCACA,kBACA,gBACA,uBACA,cACA,UACA,CAAK,CACL,CACA,iBACA,iBACA,8BACA,kBAEA,qBAGA,CACA,WACA,4BACA,kCACA,CACA,iBACA,QAAoB,QAAa,EACjC,OACA,wBAGA,2BAFA,6CAIA,eACA,SAAyB,qCAAqC,CAC9D,CAAO,CACP,aACA,SAAyB,aAAe,CACxC,CAAO,CACP,gBACA,SAAyB,gBAAkB,CAC3C,CAAO,CACP,4BACA,mCACA,qCACA,+BACA,CAAK,EACL,oCACA,sBACA,IACA,OACA,SAAyB,sCAAsC,EAC/D,gCACA,EACA,MAEA,uCACA,wBACA,SACA,eACA,UACA,YACA,UACA,CAAW,CAEX,CACA,4BAiBA,OAhBA,iCACA,EACA,EACA,mBACA,MAEA,uDACA,iCACA,EACA,KACA,qBACA,mBACA,MAEA,4DACA,SAAuB,sBAAuB,EAC9C,CACA,CAAM,SACN,IAyBA,MAxBA,+BACA,EACA,EACA,mBACA,MAEA,6BACA,EACA,EACA,oBAEA,iCACA,OACA,EACA,qBACA,mBACA,MAEA,+BACA,OACA,EACA,EACA,oBAEA,CACA,EAAQ,OACR,SAAyB,qBAAsB,CAC/C,CACA,EAAM,OACN,qBACA,CACA,CACA,MAsDA,WArDA,KACA,eACA,aACA,OACA,KACA,4BACA,sBAEA,aACA,OACA,KACA,WACA,CACA,gBACA,OACA,KACA,WACA,CACA,eACA,OACA,KACA,kBACA,YACA,eACA,mBACA,WACA,oBACA,iBACA,sBACA,sBACA,CACA,eACA,OACA,KACA,YACA,eACA,mBACA,WACA,iBACA,WACA,CACA,aACA,OACA,KACA,YACA,cACA,8BACA,sBACA,YACA,cACA,CACA,CACA,GACA,YACI,IAAa,YACjB,oBACA,qBACA,CAAO,EACP,gBACA,cACA,eACA,QACA,CAAO,CACP,CAAK,CACL,CACA,EACA,aACA,OACA,eACA,YACA,WACA,eACA,mBACA,YACA,cACA,iBACA,aACA,CACA,sKCnOA,EAAgB,mBAAiB,WCFjC,iFAEA,OAAM,UAAU,MAMhB,MANgB,CAMhB,mBACA,gBACA,YACA,4BAEA,OACA,UACA,SACA,OACA,2BACA,gBAEA,CAOA,mBACA,QACA,aACA,iBACA,WACA,eACA,cAGA,GAFA,8BACA,gBAA0B,aAAa,OAAO,EAAK,IAAI,cAAc,EACrE,kBACA,4DACA,wEACA,cACA,8BACA,uBACA,CACA,CACA,CC9BgB,mBAAiB,CACD,mCAAiC,CACrC,+BAA6B,CAC3C,iBAAe,CAC7B,MAA4B,+BAA6B,CACzD,EAAgB,mBAAiB,OA4EjC,EACA,eACA,oBACA,iBAA2B,+BAA6B,cACxD,4CACA,4CACA,0BACA,oCACA,oCACA,4CACA,sCACA,iJACA,iJACA,2CACA,qBACA,qCAEA,gCACA,EACA,iCACA,gDAEA,2CACA,EACA,mBACA,mCAEA,8BACA,CACA,CAOA,SACA,cACA,kBACA,sBACA,wBACA,sBACA,kCACA,kCACA,0CACA,oCACA,KACS,CACT,CAMA,mCACA,oCAEA,GADA,qGACA,wBACA,MACA,yCAAyD,kBAAuB,WAAW,kBAA+B,GAE1H,cACA,KACA,oBACA,cACS,CACT,CAQA,4BACA,wCACA,gCACA,kBACA,cACA,mBACA,aACA,kBACA,aACA,kBAEA,MADA,0BAA2E,EAC3E,4BACA,UACA,2CAA2D,QAAM,KAAgB,kBAEjF,kCACA,cAA+B,uBAA2B,CAC1D,CAOA,2BACA,yCAEA,MADA,YFhMA,YAEA,gCADA,uDAAyG,GACzG,cACA,0BAAqD,oBAAwB,GAC7E,iBACK,GACL,sCACA,SAEA,qDAEA,KACA,wBAEA,UACA,SAWA,OAVA,8CACA,mBACA,gEACA,4BACA,sCACA,eACA,wCACA,gBACA,gEACA,4BACA,CACA,EACA,UACA,WAEA,wBACA,CACA,gBACA,kBAGA,CACA,kFACA,KAAkB,EAAM,6BAA4C,iBAAe,0DACnF,+BACA,CACA,EACA,OACA,QACA,qBACA,qBACA,UACA,oCACA,YACA,YACA,qBACA,YACA,YACA,YACA,mDACA,sEACA,EAAa,EACb,SACA,oBACA,oBACA,kCACA,CAAa,CACb,UACA,yBACA,SACA,qBACA,gBACA,CAAa,CACb,CAAS,EACT,OACA,QACA,QACA,8BACA,qCACiB,CACjB,OACA,6BACA,oCACiB,CACJ,CACb,MACA,2EACA,KACA,CACA,IAA6B,EAAM,0CACnC,oBACA,sDACA,gBACqB,CACrB,GACA,yEACA,KACA,CACA,IAA6B,EAAM,0CACnC,oBACA,sDACA,gBACqB,CACrB,GACA,MAAuB,CACV,CACb,MACA,SAA0B,CAC1B,QAAyB,CACzB,MACA,CAAa,CACJ,CACT,gBACA,aACA,mBACA,cACA,CAAS,CACT,gBACA,oBACA,cACA,gBACA,wBACA,kBACA,wBACA,CACA,EEuE4D,IAE5D,CAEA,YACA,mBAGA,iBACA,wBAGA,cACA,qBAGA,cACA,qBAGA,eACA,sBAiBA,aACA,2BAGA,wBACA,uCAGA,WACA,yBAGA,YACA,OAKA,8BAIA,gCAIA,yBACA,CACA,CAQA,wBACA,kCACA,CAKA,uBACA,0DACA,CAMA,uBACA,2DACA,CAKA,oBACA,uDACA,CAMA,qBACA,yDACA,CAOA,kCACA,wDACA,iBACA,UACA,MACA,CAAS,CACT,CAOA,sBACA,oDACA,wEACA,2BAAyC,cAAwB,CACjE,CAQA,mCACA,oDACA,oDACA,iBACA,6BACA,MACA,CAAS,EACT,2BAAyC,cAAwB,CACjE,CAQA,gCAEA,EACA,eAFA,iEAEA,CAEA,mDACA,0CAEA,2CACA,sBACA,0CACA,oCACA,SACA,CAAS,CACT,CAKA,mBACA,mDACA,2CAA2D,+FAE3D,OACA,0CACA,mCACA,CACA,CAKA,oBACA,mDACA,4CACA,CAOA,gBACA,MAAe,QAAc,iBAC7B,CAWA,mCACA,cACA,OAAiB,YAAwB,QAAmB,mCAC5D,CAUA,iBACA,0DAOA,OANA,oBACA,uDAEA,iBACA,iDAEA,CACA,CASA,+BACA,wBAAgB,kDAAkE,EAClF,QACA,EAA6B,EAAU,mBAEvC,CAFuC,EAEvC,2BACA,SAEA,YACA,+CAEA,IAEA,kCACA,cACA,mFACA,WAhZA,OAKA,EAEA,EANA,aACA,WAMA,IALA,UAKA,CALmB,CAKnB,WAEA,gBAEA,GArBA,KAqBA,GApBA,KAoBA,GACA,MAtBA,KAsBA,EAEA,YAEA,YAA4B,IAAqB,IACjD,MAEA,gBACA,aACA,MAGA,0BASA,GAJA,EACA,eAEA,eA1CA,KA2CA,gBAEA,KAEA,CACA,CACA,0BACA,EAuWA,GACA,QACA,CAEA,8CACA,kBAEA,aACA,6BAEA,aACA,OACA,sDACA,cAEA,UACA,GAEA,MAAoB,EAAU,EAAe,IAAM,cAArB,EAAqB,mCACnD,WACA,YAEA,EACA,CACA,MACA,MAA0B,KAAM,kCAChC,EAAyB,KAAM,2CAC/B,wCAAoE,QAAc,UAAU,EAAM,mBAAmB,EAAK,IAAI,EAAa,GAE3I,OADA,UACA,CACA,CACA,QACA,CAYA,4BACA,qBAAgB,2BAAyC,MACzD,cACA,6CACA,sCAA0D,QAAc,6BAExE,OACA,gBAAiC,IAAM,oCACvC,kBAAmC,IAAM,gCACzC,CACA,CACA,MAAiC,IAAM,oDACvC,mCACA,YACA,WACA,CAAS,EACT,EAA8B,IAAM,iDACpC,mCASA,OARY,GAAM,QAClB,MAAkB,GAAM,kBAAkB,GAAS,cACnD,SACA,CAAsB,kDAA6E,CACnG,CAAsB,+CAAuE,CAC7F,CACa,EAEb,CACA,wCACA,mBACA,0CACA,eACA,CACA,CAUA,yCACA,MAAkB,QAAc,kBAChC,6CACA,gBACA,cAEA,uDACsB,KAAwB,yDAC9C,EAEA,qBACA,KACA,iBACA,cACA,OAA+B,KAAkB,EAAC,EAAM,wGACxD,eACA,gCACA,wBACA,cACA,4BACA,QACA,CAAyB,EACzB,qBACA,gEAEA,0FACA,OAAmC,KAAwB,wEAE3D,gBAEA,YACA,cAEA,oBADA,6EACA,8BACA,MACA,oDAAoF,cAAkB,IAAM,GAAG,oCAAoC,OAAkB,0BAA0B,UAAqB,UAEpN,qBAC8B,KAAkB,6FAChD,QAEA,WACA,6BAA6D,IAAM,wBACnE,OAA+B,KAAkB,mFACjD,CACA,CAEA,IAAiB,8BAA4B,SAC7C,uDAA2E,cAAkB,IAAM,GAAG,oBAAoB,OAAO,EAEjI,CAAS,MACT,CACA,uBACA,OAEA,gBACA,oBACA,KACA,yBACiB,wBAGjB,SACA,gCAGA,UACA,4CAGA,cACA,qCAGA,YACA,mCAGA,QACA,6CAEA,CACA,CACA,kCACA,OAEA,gBACA,6EAGA,SACA,oEAGA,UACA,uEAGA,cACA,yEAGA,YACA,uEAGA,QACA,kEAEA,CACA,CACA,qBACA,OAEA,iBACA,4BACA,OACA,yGACA,KAEA,CAAa,CAEb,SACA,kFAGA,UACA,qFAGA,cACA,uFAGA,YACA,qFAGA,QACA,gFAEA,CACA,CACA,6BACA,OAEA,kBACA,EACA,KACA,gCACA,yCACA,yBACA,EAGA,gBACA,yBACA,KACA,yBACiB,wBAGjB,eACA,qCAGA,gBACA,iDAGA,kBACA,wCAGA,cACA,iDAEA,CACA,CACA,2BACA,OAEA,kBACA,2DAKA,iBACA,4BACA,OACA,uIAAgK,KAAW,GAAI,QAAc,2BAC7L,KAEA,CAAa,CAIb,SACA,8HAA8J,QAAc,2BAK5K,UACA,iIAAiK,QAAc,2BAK/K,YACA,iIAAiK,QAAc,2BAK/K,eAEA,6CACoB,QAAc,0CAClC,2BACA,WACA,gDACA,UACA,qDAEA,iBACA,CAAqB,EACrB,qCACA,KACA,kCACA,oCAEA,iDACA,CAAqB,CAAE,QAAc,yBACrC,CACA,oIAA6J,QAAc,0BAC3K,CAAa,CAEb,CACA,wCACA,OAEA,kBACA,wEAKA,gBACA,kFAKA,eACA,+EAKA,gBACA,kFAKA,kBACA,kFAKA,cACA,6EAEA,CACA,CAGA,aACA,4BACA,+FAA+G,cAAc,GAE7H,8BAKA,eACA,iEACA,CACA,mBACA,OACA,KACA,kBACA,iCACA,2CACA,YACA,CACA,CACA,wBACA,+BACA,EAAuB,QAAc,yBACrC,4DACA,OACA,KACA,kBACA,SACA,yCACA,SACA,aACA,MACA,CACA,CAEA,0BACA,IACA,gBACA,CACA,SACA,oCACA,CACA,CACA,gBAEA,WACA,GAIA,gBACA,oHAOA,mBACA,mCACA,sBAAqD,IAAM,uBAC3D,MAAuB,QAAkB,kCACzC,CAAa,CASb,yBACA,mCACA,EAA+B,IAAM,6BACrC,EAAmC,IAAM,WAAiB,QAAkB,mCAC5E,EAAkC,IAAM,4BACxC,sBAAqD,IAAM,mBAC3D,MAAuB,QAAkB,kCACzC,CAAa,CASb,iBACA,mCACA,EAA+B,IAAM,6BACrC,wBACA,mCACA,UAAmC,QAAgB,eACnD,cACA,MAAuC,IAAM,uBAC7C,EAAsC,IAAM,4BAC5C,OACwB,QAAkB,yDAClB,QAAkB,qBAAwB,IAAM,mDACxE,CACiB,GACjB,CAAa,EAEb,QACA,CACA,uBAEA,WACA,GAIA,iBACA,gBACA,sGACA,CAAa,CAOb,sBACA,kCACA,SACA,wCACA,kBAC2B,QAAkB,4CAE7C,QACA,CAAa,CAUb,2BACA,kCACA,SACA,EAA+B,IAAM,6BACrC,EAAmC,IAAM,WAAiB,QAAkB,mCAC5E,EAAkC,IAAM,4BACxC,oCACA,kBAC2B,QAAkB,4CAE7C,QACA,CAAa,CAOb,iBACA,+BACA,SACA,EAA+B,IAAM,6BACrC,iBACA,UAAmC,QAAgB,cACnD,QACA,+BACA,OACwB,QAAkB,oCAClB,QAAkB,sEAC1C,CACiB,EACjB,CAAa,EAEb,QACA,CACA,kDC99BA,SAEA,iBACA,8BAGA,gBACA,8BAGA,YACA,OAAe,2BAAyB,gCACxC,CAEA,WACA,OAAe,2BAAyB,gCACxC,CACA,eACA,uBACA,iBACA,qBACA,gBACA,oBACA,YACA,OAAiC,2BAAyB,mBAC1D,OAAiC,2BAAyB,iBAC1D,CACA,WACA,SAAkB,wCAAwC,UAM1D,UACA,6BACA,CAEA,gBACA,cAAgC,QAAe,CAC/C,CAEA,eACA,cAAgC,QAAe,CAC/C,CAEA,qBACA,cAAgC,aAAoB,CACpD,CAEA,oBACA,cAAgC,aAAoB,CACpD,CACA,4HCjDgC,mCAAiC,CACjE,MAAe,kBAAgB,CA6C/B,cACA,YAGA,mDACA,6BACA,qCAAqD,kFAAkF,SAAa,GAEpJ,iBACA,SACA,yBAEA,OADA,WACA,CACA,CACA,uBACA,6BACA,qCAAqD,iEAAiE,EAAM,gBAAgB,SAAa,GAEzJ,sBACA,qBAEA,OADA,qBACA,CACA,CAEA,8CAA0D,SAAa,GAEvE,CA0IA,sBACA,UAAgC,kCAAgC,EAChE,aACA,yBACA,wBACA,aACA,CAAK,EACL,EAAuB,oCAAkC,GACzD,YACA,2BACA,UACA,CAAK,EAEL,MADA,wBACA,8BACA,oBACA,0EAAkF,WAAuB,IAAI,iBAA6B,GAE1I,OACA,iCACA,sBAEA,8BACA,CACA,CAkBA,sBACA,mBACA,iBACA,uBACA,cACA,OACA,2BACA,yDACA,eACA,6DACA,mBACA,gEAEA,yBACA,kDAA6E,uBAAqB,KACzF,EACT,oBACA,mEACS,EACT,sBACA,uEACS,EACT,sCACA,KA9QA,EA+QA,0CAAsD,0BAA2D,EAAE,GACnH,EADuF,EACvF,uCAGA,OAFA,qCACA,4BAnRA,EAqRA,2CAAuD,0BAA2D,EAAE,EAEpH,CAAK,EAFmF,IAGxF,YACA,UACA,gBAA+B,yBAAuB,MACtD,SACA,mCACA,oCAGA,WAFA,kCACA,yBA/RA,CAiSA,EAEA,uCACA,YAAoB,GAAU,EAC9B,iBACA,QAIA,2BAA8C,uBAAqB,4BAEnE,6BAAqD,+BAA6B,kBAElF,qBACA,OAAoC,QAAM,KAC1C,SAAkC,QAAM,CAAC,uBAAqB,QAE9D,SACA,uBACA,UAA4B,GAAQ,CACpC,4EAEA,CACA,IAA4B,OAAM,CAClC,oEAEA,MACA,CAiBA,GAfA,mBACA,UAGA,gCAjUA,EA+TA,SAIA,uBACA,IAA4B,SAAQ,EACpC,kDACA,CACA,CACA,QAA4B,GAAM,EAClC,4EACA,CACA,EAAa,EACb,IACA,YAAwB,GAAU,CAClC,mDAA6F,uBAAqB,KAClH,MACA,CACA,CAEA,cACA,QAAoB,UAAY,EAChC,iBACA,QAGA,yEAEA,SACA,uCAAmF,0BAA6B,EAChH,MACA,CACA,CAEA,sBACA,gBAA+B,yBAAuB,MACtD,SACA,mCACA,iBACA,SAtWA,EAuWA,wCACA,kCACA,+BAEA,mCACA,aA5WA,EA+WA,qCACA,UAEA,QAnXA,CAoXA,CAAS,EACT,UACA,8FAEA,iBACA,kDAAyF,uBAAqB,UAE9G,aACA,wEAEA,cACA,QAAoB,UAAY,CAChC,wCAA+E,0BAA6B,EAC5G,oBACA,oEAEA,MACA,uBACA,UAAoB,aAAiB,CACrC,wEACA,kDAAyF,uBAAqB,UAE9G,mBACA,QAAoB,aAAe,CACnC,mDAAyF,uBAAqB,KAC9G,uEAEA,aACA,wEAEA,EACA,UACA,OAGA,yBACA,kBAEA,gDACA,mDACA,CAAS,EACT,6BACA,sBAEA,gDACA,yDACA,CAAS,EAET,wBACA,gBACA,CAAS,EACT,qBACA,aAEA,mDACA,CAAS,EACT,sBACA,cACA,CAAS,EACT,oBACA,YACA,CAAS,EACT,gBACA,YAA4B,iBAAoB,KAEhD,IADA,IAAgC,+BAA6B,EAAG,6BAAiC,EACjG,OAIA,UAAuB,mCAAiC,CAOxD,OANA,cAEA,mBACA,mBACA,CAAK,EACL,4BACA,CACA,CA9TA,CAjBA,IACA,cAKA,MADA,CAHA,YACA,0DACA,GACA,QAEA,EAUA,YACA,mBACA,SACA,WACc,8CAA4C,IAC5C,2CAAyC,GACvD,CAAC,EA+TD,8BAEA,EADA,IAAY,yBAA8C,EAO1D,IACA,QAWA,EAsBA,EA9BA,2DAAqH,GAAM,4BAE3H,iBAGA,QADA,aACA,OACA,OAUA,GAPA,aACA,aAAoD,IAAM,wCAC9C,GAAM,uEAA8F,UAA2B,gBAAgB,EAAQ,IACnK,oBACA,CAAa,EACD,GAAM,qEAA4F,EAAQ,wBAE1G,GAAM,QAAU,GAAM,WAElC,YAA2C,OAAwC,KACnF,OAAkB,GAAM,kBAAkB,GAAS,oBACnD,kBACA,CAAa,CACb,CACA,iGAWA,OAVA,WACY,GAAM,yEAAgG,EAAQ,cAAc,UAA2B,eAGvJ,GAAM,0EAAiG,aAA8B,EAAE,WAA4B,OAAO,uBAAqB,sBAAuC,GAGlP,gBACA,gJAEA,CACA,UACA,gBACA,yBACA,eACA,8BACA,CAEA,CACA,SAGA,kGAQA,GAPA,UACA,qBAEA,2BACA,sBACA,eAEY,GAAM,4BAClB,YACY,GAAM,4FAA4F,kDAC9G,YAAmC,OAAwC,MAO3E,GANgB,GAAM,SAAW,GAAM,WAEvC,MAAsB,GAAM,kBAAkB,GAAS,oBACvD,kBACA,CAAiB,EAEjB,2BACA,uCACA,eACA,0CACA,8BACA,wCACA,sBACA,sCACqB,CAGrB,MAEY,GAAM,mHAElB,QACA,CACA,EACA,SACA,mBACA,aAA4B,qBAAmB,EAC/C,yBAMA,gCAAsD,4BAA0B,eAAoB,+BACpG,2BAEA,+BAAqD,sBAAoB,CACzE,mCAGA,EAQA,qBACA,cACA,CACA,2BAGA,CACA,gBACA,gCACA,mBACA,mEACA,uCACA,cAEA,6DChlBgB,mBAAiB,CAClB,kBAAgB,CAD/B,IAEA,EAA4B,+BAA6B,kDCNzD,EAAe,kBAAgB,CAO/B,sBAEA,MADA,eACA,OAA8E,2CAAyC,SACvH,yBACA,wBACA,cACA,oBACA,2CACA,UACA,iBACA,eACA,cACA,CAAS,EACT,WACA,uCACA,cAA6D,mBAAiB,IAC9E,CAAa,EACb,CACK,EAEL,OADA,oCAEA,mFCzBA,EAAiB,wBAAsB,OAEvC,EAUA,iBACA,cACA,gBACA,CAYA,iBACA,8EACA,OACA,wBACA,6BACA,mCACA,wBACA,kCACA,2BACA,qCACA,iBACA,2BACA,yBACA,yBACA,2BACA,uBACA,yBACA,qCACA,mCAEA,CAgBA,iCACA,4FACA,OACA,kBACA,0CACA,4CACA,qBACA,CACA,CAkBA,uBACA,SACA,YAAiC,QAAU,GAAW,GAA0B,GAChF,uBACA,eACA,iBACA,KACA,mCACA,iBACA,CAAiB,EAEjB,sBACY,GAAM,yDAA+D,GAAS,aAAa,cAAuB,uBAAuB,mBAAwB;AAC7K,kBAAqC,WAAgB,WAAW,qCAA0C,EADmE,EAE7K,kBACA,QAA+B,2CAA8D,CAC7F,CAAa,CACb,CACA,QACA,CAkBA,wBACA,SACA,8BACA,YAAiC,QAAU,GAAW,GAA0B,GAChF,uBACA,KACA,KACA,eACA,6BACA,IACA,2CACA,iBACA,iBAEA,CACA,MACA,iBACA,CAGA,0BACA,uBAA2C,EAAO,EAAE,uCAA4D,mBAA0C,EAAE,aAA8B,KAAO,EAAE,WACnM,kCAAwD,mBAA8C,EAAE,aAAkC,EAC1I,KAA2B,iBAE3B,eACA,kBACA,KACA,gDACA,SACA,iBACA,CAAiB,EAEjB,sBACY,GAAM,sDAA4D,GAAS,gBAAgB,cAAuB,uBAAuB,mBAAwB;AAC7K,kBAAqC,WAAgB,WAAW,qCAA0C,EADmE,EAE7K,kBACA,QAA+B,2CAA8D,CAC7F,CAAa,CACb,CACA,QACA,CACA,oDE5KWA,EAAiB,CAC1BC,WAAOC,EACPC,UAAMD,EACNE,UAAWF,OACXG,MAAOH,OACPI,UAAMJ,CACR,EAAE,EACuBK,EAAAA,aAAmB,EAAiBA,EAAb,WAAW,EAAqB,CAACP,GCR7EQ,EAAY,CAAC,OAAQ,GDQwE,ICRhE,QAAQ,CAGzC,SAASC,IAAiS,MAAOA,CAA3RA,EAAWC,OAAOC,MAAM,CAAGD,OAAOC,MAAM,CAACC,IAAI,GAAK,SAAUC,CAAM,EAAI,IAAK,IAAIC,EAAI,EAAGA,EAAIC,UAAUC,MAAM,CAAEF,IAAK,CAAE,IAAIG,EAASF,SAAS,CAACD,EAAE,CAAE,IAAK,IAAII,KAAOD,EAAcP,KAAN,EAAaS,SAAS,CAACC,cAAc,CAACC,IAAI,CAACJ,EAAQC,KAAQL,CAAF,CAASK,EAAI,CAAGD,CAAM,CAACC,EAAI,CAAM,CAAE,OAAOL,EAAQ,EAAmBS,KAAK,CAAC,IAAI,CAAEP,UAAY,CAClV,SAASQ,EAAQC,CAAC,CAAEC,CAAC,EAAI,IAAIC,EAAIhB,OAAOiB,IAAI,CAACH,GAAI,GAAId,OAAOkB,qBAAqB,CAAE,CAAE,IAAIC,EAAInB,OAAOkB,qBAAqB,CAACJ,EAAIC,KAAMI,EAAIA,EAAEC,MAAM,CAAC,SAAUL,CAAC,EAAI,OAAOf,OAAOqB,wBAAwB,CAACP,EAAGC,GAAGO,UAAU,EAAE,CAAC,CAAIN,EAAEO,IAAI,CAACX,KAAK,CAACI,EAAGG,EAAI,CAAE,OAAOH,CAAG,CAC9P,SAASQ,EAAcV,CAAC,EAAI,IAAK,IAAIC,EAAI,EAAGA,EAAIV,UAAUC,MAAM,CAAES,IAAK,CAAE,IAAIC,EAAI,MAAQX,SAAS,CAACU,EAAE,CAAGV,SAAS,CAACU,EAAE,CAAG,CAAC,EAAGA,EAAI,EAAIF,EAAQb,OAAOgB,GAAI,CAAC,GAAGS,OAAO,CAAC,SAAUV,CAAC,YACpJW,EADwKZ,CACrK,CAAEN,EADsKO,CACnK,CAAEY,EADoKX,CAAC,CAACD,CACjK,CADmK,CAChIP,CAA/BA,EAAMoB,SACzCA,CAAgB,EAAI,IAAIxB,EAAIyB,SAC5BA,CAAc,CAAEd,CAAC,EAAI,GAAI,UAAY,OAAOC,GAAK,CAACA,EAAG,OAAOA,EAAG,IAAIF,EAAIE,CAAC,CAACc,OAAOC,WAAW,CAAC,CAAE,GAAI,KAAK,IAAMjB,EAAG,CAAE,IAAIV,EAAIU,EAAEH,IAAI,CAACK,EAAGD,GAAK,WAAY,GAAI,UAAY,OAAOX,EAAG,OAAOA,CAAG,OAAU4B,UAAU,+CAAiD,CAAE,MAAO,CAAC,WAAajB,EAAIkB,OAASC,MAAAA,CAAK,CAAGlB,EAAI,EADrQA,EAAG,UAAW,MAAO,UAAY,OAAOZ,EAAIA,EAAIA,EAAI,EAAI,EADzCI,EAAAA,IAAiBkB,EAAO1B,GAAF,IAASmC,cAAc,CAACT,EAAKlB,EAAK,CAAEmB,MAAOA,EAAOL,YAAY,EAAMc,cAAc,EAAMC,UAAU,CAAK,GAAaX,CAAG,CAAClB,EAAI,CAAGmB,CADR,GAAK3B,OAAOsC,yBAAyB,CAAGtC,OAAOuC,gBAAgB,CAACzB,EAAGd,OAAOsC,yBAAyB,CAACtB,IAAMH,EAAQb,OAAOgB,IAAIS,OAAO,CAAC,SAAUV,CAAC,EAAIf,OAAOmC,cAAc,CAACrB,EAAGC,EAAGf,OAAOqB,wBAAwB,CAACL,EAAGD,GAAK,EAAI,CAAE,OAAOD,CAAG,CAW/a,SAAS0B,EAAQC,CAAI,EAC1B,OAAOC,GAAsB7C,EAAAA,GAAb,UAAgC,CAArB,EAAgCE,EAAS,CAClEH,KAAM4B,EAAc,CAAC,EAAGiB,EAAK7C,IAAI,CACnC,EAAG8C,GAAQC,SARJA,EAAaC,CAAI,EACxB,OAAOA,GAAQA,EAAKC,GAAG,CAAC,CAACC,EAAM1C,IAAM,EAAaP,SAAF,IAAqB,CAACiD,EAAKC,GAAG,CAAEvB,EAAc,CAC5FhB,IAAKJ,CACP,EAAG0C,EAAKlD,IAAI,EAAG+C,EAAaG,EAAKE,KAAK,GACxC,EAI0BP,EAAKO,KAAK,EACpC,CACO,SAASC,EAASP,CAAK,EAC5B,IAAIQ,EAAOC,IACT,IAOIzD,EAPA,CACAE,MAAI,MACJH,CAAI,OACJ2D,CAAK,CACN,CAAGV,EACJW,EA3BN,SAASC,CAA+B,CAAEC,CAAQ,EAAI,GAAc,MAAVhD,EAAgB,MAAO,CAAC,EAAG,IAAkEC,EAAKJ,EAAnED,EAASqD,SAC3DjD,CAAM,CAAEgD,CAAQ,EAAI,GAAc,MAAVhD,EAAgB,MAAO,CAAC,EAAG,IAAIJ,EAAS,CAAC,EAAG,IAAK,IAAIK,KAAOD,EAAU,GAAIP,EAAN,KAAaS,SAAS,CAACC,cAAc,CAACC,IAAI,CAACJ,EAAQC,GAAM,CAAE,GAAI+C,EAASE,OAAO,CAACjD,IAAQ,EAAG,SAAUL,CAAM,CAACK,EAAI,CAAGD,CAAM,CAACC,EAAI,CAAM,OAAOL,CAAQ,EADtJI,EAAQgD,GAAuB,GAAIvD,OAAOkB,qBAAqB,CAAE,CAAE,IAAIwC,EAAmB1D,OAAOkB,qBAAqB,CAACX,GAAS,IAAKH,EAAI,EAAGA,EAAIsD,EAAiBpD,MAAM,CAAEF,IAAK,EAAQsD,CAAgB,CAACtD,EAAE,GAAMmD,EAASE,OAAO,CAACjD,KAAQ,GAAG,OAAsBC,SAAS,CAACkD,oBAAoB,CAAChD,IAAI,CAACJ,EAAQC,KAAgBL,CAAM,CAACK,EAAI,CAAGD,CAAM,CAACC,EAAAA,CAAQ,CAAE,OAAOL,CAAQ,EA2BjcuC,EAAO5C,GACzC8D,EAAenE,GAAQ0D,EAAK1D,IAAI,EAAI,MAIxC,OAFI0D,EAAKzD,SAAS,GAAEA,EAAYyD,EAAKzD,SAAAA,EACjCgD,EAAMhD,SAAS,GAAEA,EAAY,CAACA,EAAYA,EAAY,IAAM,GAAC,CAAKgD,EAAMhD,SAAAA,EACxDG,EAAAA,aAAmB,CAAC,MAAOE,EAAS,CACtD8D,OAAQ,eACRC,KAAM,eACNC,YAAa,GACf,EAAGZ,EAAKvD,IAAI,CAAEA,EAAMyD,EAAU,CAC5B3D,UAAWA,EACXC,MAAO6B,EAAcA,EAAc,CACjCjC,MAAOmD,EAAMnD,KAAK,EAAI4D,EAAK5D,KAAK,EAC/B4D,EAAKxD,KAAK,EAAG+C,EAAM/C,KAAK,EAC3BqE,OAAQJ,EACRK,MAAOL,EACPM,MAAO,4BACT,GAAId,GAAsBvD,EAAAA,IAAb,SAAgC,CAAC,CAAtB,OAA+B,KAAMuD,GAAQV,EAAMyB,QAAQ,CACrF,EACA,YAAuB3E,IAAhB4E,EAAyCvE,EAAAA,IAAb,GAAjBuE,MAAiD,CAACA,CAAtB,CAAkCC,QAAQ,CAAE,KAAMlB,GAAQD,EAAKC,IAASD,EAAK5D,EAC7H,YAD2IA,uBE/C3I,SACA,cACA,oCACA,oBACA,6BAEA,qBACA,qCACA,YAEA,CACA,QAIA,OAHA,qBACA,yBACA,4BACA,KAEA,UACA,mBACA,IACA,mBACA,QACA,CACA,wBACA,CACA,EAEA,OADA,iCACA,YACA,CACA,oBACA,qCAYA,OAXA,GACA,kCACA,sCACA,8DAIA,sCACA,6DAGA,KAEA,eCxCA,SACA,+BACA,4CAEA,aACA,0BAEA,YACA,yBAEA,kBACA,+BAEA,eACA,4BAEA,wBACA,qCAEA,qBACA,kCAEA,aACA,0BAOA,oBACA,EACmB,IAAU,CAE7B,YAMA,aACA,wBACA,IACA,qBACA,GACA,QACA,CACA,mBACA,CACA,CACA,cACA,aACA,OAAoB,IAAa,CACjC,SACA,iBACA,YACA,sBACA,kBACA,4BACA,WAAwB,CACxB,CACA,CAKA,aACA,CARyC,GAQzC,SAAwB,oBACxB,CACA,CCtEA,UAAmB,eAAe,mECGlC,UACA,sBACA,SACA,qCACA,8BAA0D,GAAO,sFAEjE,qCACA,8BAA0D,GAAO,uFAEjE,gBACA,CACA,uBACA,CAQA,eACA,IAEA,uBADA,KACA,YAGA,KASA,gBACA,YAAoB,WAAkB,KACtC,oBACA,CAMA,UACA,cACA,cACA,0DACA,EAEA,OADA,UACA,CACA,EACA,UACA,qBACA,SACA,YAAoB,WAAuB,IAC3C,eACA,SAEA,QACA,EACA,UACA,sBACA,IACA,WACA,CACA,MACA,mBACA,CAEA,QACA,EACA,aACA,2CCpEA,EAYA,iEAtBA,uBAEA,mBAEA,qBAEA,OAEA,gCAGA,YAEA,mBAEA,6BAEA,+BAEA,4BACA,CAAC,UAA4B,EAG7B,YAEA,mBAEA,+BAEA,4BACA,CAAC,UAAsC,+FCzBvC,eAA+B,SAAc,GAC7C,GAAc,OAAY,GAAG,kCACnB,QAAM,WAChB,MAAyB,QAAwB,MACjD,+BAAgD,IAAM,6BACtD,CAAS,EACT,GAAa,SAGb,EAMA,mBA0CA,yCACA,yBAAwD,oBAAyB,gBAAa,UAAe,KAAK,YAAiB,kBAAkB,SAAmB,EAC/J,EAgDT,2BACA,4CACA,+BAA6D,gBAAuB,YAAiB,KAAO,EAAE,gBAAuB,WAAgB,OAAS,OAAO,SAAc,YAAY,eAAsB,sBAAsB,UAAe,UAAU,2BAAgC,kBAAkB,eAAoB,EAC7T,KACb,OAAqB,kDACrB,EA2CA,iDACA,2CAA0E,WAAgB,kBAAkB,SAAmB,EACtH,EAqCT,iDACA,wCAAuE,WAAgB,kBAAkB,SAAmB,EACnH,EAuCT,mDACA,0CAAyE,WAAgB,kBAAkB,SAAmB,EACrH,EAwCT,qDACA,8BAA6D,UAAe,yBAAyB,WAAgB,OAAO,UAAe,KAAK,YAAiB,kBAAkB,SAAmB,EAC7L,EAmCT,+CACA,2BAA0D,UAAe,mBAAmB,WAAgB,kBAAkB,SAAmB,CACjJ,CAAS,EA6CT,2BACA,wBACA,SACA,IAEA,GADA,oEACA,QAEA,MACA,uBAA+C,UAAe,2BAA2B,YAAiB,gBAC1G,CACA,UACA,uBAA+C,UAAe,yCAAyC,YAAiB,gBAExH,CAEA,OADA,2EACA,sCACA,wBAA2D,UAAe,uBAAuB,WAAgB,aAAa,WAAgB,kBAAkB,SAAmB,EACtK,IACb,EAkDA,0DACA,iCAA2D,UAAe,UAAU,iCAAsC,kBAAkB,eAAoB,EACvJ,EA0CT,0DACA,sBAAgD,SAAc,UAAU,gBAAuB,cAAuB,IAAM,6BAA6B,MAAQ,KAAK,UAAe,kBAAkB,eAAoB,EAClN,EAwCT,oDACA,sBAAgD,SAAc,UAAU,gBAAuB,cAAuB,IAAM,6BAA6B,MAAQ,KAAK,UAAe,kBAAkB,eAAoB,CAC3N,CAAS,EAwCT,gDACA,sBAAgD,SAAc,SAAS,gBAAuB,cAAuB,IAAM,6BAA6B,MAAQ,KAAK,UAAe,kBAAkB,eAAoB,EACjN,EA8DT,8EACA,iCAA2D,UAAe,UAAU,iCAAsC,kBAAkB,eAAoB,EACvJ,EAsDT,8EACA,sBAAgD,SAAc,eAAe,MAA6B,KAAK,UAAe,kBAAkB,eAAoB,EAC3J,EAoDT,wEACA,sBAAgD,SAAc,eAAe,MAA6B,KAAK,UAAe,kBAAkB,eAAoB,EAC3J,EAoDT,oEACA,sBAAgD,SAAc,cAAc,MAA6B,KAAK,UAAe,kBAAkB,eAAoB,EAC1J,EAET,qEACA,4CAA2E,UAAe,kBAAkB,SAAmB,EACtH,EAET,uEACA,6CAA4E,UAAe,kBAAkB,SAAmB,EACvH,EACT,iBACA,qBACA,kBACA,CACA,WACA,uBACA,CACA,WACA,iBACA,uBAGA,GADA,kBACA,WACA,gDACgB,GAAM,+CACtB,CACA,sBACA,GAEA,kCACA,oCACA,oBACA,MAKA,OAHA,YACgB,GAAM,iDAEtB,CACA,CACA,CACA,kBACA,iBACA,+BACA,OAAqB,YAAmB,GAAU,2DAClD,CACA,CACA,wBACA,iBACA,sCACA,qGACA,yGACA,OAAqB,wCACrB,CACA,CACA,wBACA,iBACA,4CACA,OACA,KACA,8CACA,WAA4B,+BAA6B,iCACzD,CACA,CACA,CACA","sources":["webpack://_N_E/./node_modules/@tanstack/query-core/build/modern/mutationObserver.js","webpack://_N_E/../useMutation.ts","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/lifecycle-events.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/composer.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app-factory.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/transaction/legacy-bridge.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/logging.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app-arc56.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/app-deploy.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app-manager.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/indexer-lookup.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app-deployer.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/network-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/app-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/urlTokenBaseHTTPClient.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/algo-http-client-with-retry.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/dispenser-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/client-manager.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/kmd-account-manager.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/account-manager.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/algorand-client-transaction-creator.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/algorand-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/asset.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/dispenser-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/network-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/amount.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/account/account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/account/get-account-config-from-environment.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/account/get-account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/account/get-dispenser-account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/account/mnemonic-account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/localnet/get-kmd-wallet-account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/localnet/get-localnet-dispenser-account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/localnet/get-or-create-kmd-wallet-account.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/localnet/is-localnet.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/transfer/transfer.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/transfer/transfer-algos.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/index.mjs","webpack://_N_E/./node_modules/@tanstack/query-core/build/modern/mutation.js","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app-spec.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/logic-error.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app-client.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/amount.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/transaction/transaction.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/app.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/transaction/perform-atomic-transaction-composer-simulate.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/asset-manager.mjs","webpack://_N_E/./node_modules/react-icons/lib/iconsManifest.mjs","webpack://_N_E/./node_modules/react-icons/lib/iconContext.mjs","webpack://_N_E/./node_modules/react-icons/lib/iconBase.mjs","webpack://_N_E/./node_modules/react-icons/lib/index.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/async-event-emitter.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/config.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/config.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/util.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/app.mjs","webpack://_N_E/./node_modules/@algorandfoundation/algokit-utils/types/algorand-client-transaction-sender.mjs"],"sourcesContent":["// src/mutationObserver.ts\nimport { getDefaultState } from \"./mutation.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { hashKey, shallowEqualObjects } from \"./utils.js\";\nvar MutationObserver = class extends Subscribable {\n #client;\n #currentResult = void 0;\n #currentMutation;\n #mutateOptions;\n constructor(client, options) {\n super();\n this.#client = client;\n this.setOptions(options);\n this.bindMethods();\n this.#updateResult();\n }\n bindMethods() {\n this.mutate = this.mutate.bind(this);\n this.reset = this.reset.bind(this);\n }\n setOptions(options) {\n const prevOptions = this.options;\n this.options = this.#client.defaultMutationOptions(options);\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: \"observerOptionsUpdated\",\n mutation: this.#currentMutation,\n observer: this\n });\n }\n if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {\n this.reset();\n } else if (this.#currentMutation?.state.status === \"pending\") {\n this.#currentMutation.setOptions(this.options);\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this);\n }\n }\n onMutationUpdate(action) {\n this.#updateResult();\n this.#notify(action);\n }\n getCurrentResult() {\n return this.#currentResult;\n }\n reset() {\n this.#currentMutation?.removeObserver(this);\n this.#currentMutation = void 0;\n this.#updateResult();\n this.#notify();\n }\n mutate(variables, options) {\n this.#mutateOptions = options;\n this.#currentMutation?.removeObserver(this);\n this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);\n this.#currentMutation.addObserver(this);\n return this.#currentMutation.execute(variables);\n }\n #updateResult() {\n const state = this.#currentMutation?.state ?? getDefaultState();\n this.#currentResult = {\n ...state,\n isPending: state.status === \"pending\",\n isSuccess: state.status === \"success\",\n isError: state.status === \"error\",\n isIdle: state.status === \"idle\",\n mutate: this.mutate,\n reset: this.reset\n };\n }\n #notify(action) {\n notifyManager.batch(() => {\n if (this.#mutateOptions && this.hasListeners()) {\n const variables = this.#currentResult.variables;\n const context = this.#currentResult.context;\n if (action?.type === \"success\") {\n this.#mutateOptions.onSuccess?.(action.data, variables, context);\n this.#mutateOptions.onSettled?.(action.data, null, variables, context);\n } else if (action?.type === \"error\") {\n this.#mutateOptions.onError?.(action.error, variables, context);\n this.#mutateOptions.onSettled?.(\n void 0,\n action.error,\n variables,\n context\n );\n }\n }\n this.listeners.forEach((listener) => {\n listener(this.#currentResult);\n });\n });\n }\n};\nexport {\n MutationObserver\n};\n//# sourceMappingURL=mutationObserver.js.map","'use client'\nimport * as React from 'react'\nimport { MutationObserver, notifyManager } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport { noop, shouldThrowError } from './utils'\nimport type {\n UseMutateFunction,\n UseMutationOptions,\n UseMutationResult,\n} from './types'\nimport type { DefaultError, QueryClient } from '@tanstack/query-core'\n\n// HOOK\n\nexport function useMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TContext = unknown,\n>(\n options: UseMutationOptions,\n queryClient?: QueryClient,\n): UseMutationResult {\n const client = useQueryClient(queryClient)\n\n const [observer] = React.useState(\n () =>\n new MutationObserver(\n client,\n options,\n ),\n )\n\n React.useEffect(() => {\n observer.setOptions(options)\n }, [observer, options])\n\n const result = React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer],\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult(),\n )\n\n const mutate = React.useCallback<\n UseMutateFunction\n >(\n (variables, mutateOptions) => {\n observer.mutate(variables, mutateOptions).catch(noop)\n },\n [observer],\n )\n\n if (\n result.error &&\n shouldThrowError(observer.options.throwOnError, [result.error])\n ) {\n throw result.error\n }\n\n return { ...result, mutate, mutateAsync: result.mutate }\n}\n","var EventType;\n(function (EventType) {\n EventType[\"TxnGroupSimulated\"] = \"TxnGroupSimulated\";\n EventType[\"AppCompiled\"] = \"AppCompiled\";\n})(EventType || (EventType = {}));\n\nexport { EventType };\n//# sourceMappingURL=lifecycle-events.mjs.map\n","import algosdk from 'algosdk';\nimport { Config } from '../config.mjs';\nimport { encodeLease, sendAtomicTransactionComposer, getABIReturnValue } from '../transaction/transaction.mjs';\nimport { asJson } from '../util.mjs';\nimport { APP_PAGE_MAX_SIZE } from './app.mjs';\nimport { AppManager } from './app-manager.mjs';\nimport { EventType } from './lifecycle-events.mjs';\nimport { genesisIdIsLocalNet } from './network-client.mjs';\n\nvar AtomicTransactionComposer = algosdk.AtomicTransactionComposer;\nvar isTransactionWithSigner = algosdk.isTransactionWithSigner;\nvar encodeAddress = algosdk.encodeAddress;\nvar modelsv2 = algosdk.modelsv2;\nconst MAX_TRANSACTION_GROUP_SIZE = 16;\n/** TransactionComposer helps you compose and execute transactions as a transaction group. */\nclass TransactionComposer {\n /**\n * Create a `TransactionComposer`.\n * @param params The configuration for this composer\n */\n constructor(params) {\n /** The ATC used to compose the group */\n this.atc = new algosdk.AtomicTransactionComposer();\n /** Map of txid to ABI method */\n this.txnMethodMap = new Map();\n /** Transactions that have not yet been composed */\n this.txns = [];\n /** The default transaction validity window */\n this.defaultValidityWindow = 10;\n /** Whether the validity window was explicitly set on construction */\n this.defaultValidityWindowIsExplicit = false;\n this.algod = params.algod;\n const defaultGetSuggestedParams = () => params.algod.getTransactionParams().do();\n this.getSuggestedParams = params.getSuggestedParams ?? defaultGetSuggestedParams;\n this.getSigner = params.getSigner;\n this.defaultValidityWindow = params.defaultValidityWindow ?? this.defaultValidityWindow;\n this.defaultValidityWindowIsExplicit = params.defaultValidityWindow !== undefined;\n this.appManager = params.appManager ?? new AppManager(params.algod);\n }\n /**\n * Add a pre-built transaction to the transaction group.\n * @param transaction The pre-built transaction\n * @param signer Optional signer override for the transaction\n * @returns The composer so you can chain method calls\n */\n addTransaction(transaction, signer) {\n this.txns.push({\n txn: transaction,\n signer: signer ?? this.getSigner(algosdk.encodeAddress(transaction.from.publicKey)),\n type: 'txnWithSigner',\n });\n return this;\n }\n /**\n * Add a payment transaction to the transaction group.\n * @param params The payment transaction parameters\n * @returns The composer so you can chain method calls\n */\n addPayment(params) {\n this.txns.push({ ...params, type: 'pay' });\n return this;\n }\n /**\n * Add an asset create transaction to the transaction group.\n * @param params The asset create transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetCreate(params) {\n this.txns.push({ ...params, type: 'assetCreate' });\n return this;\n }\n /**\n * Add an asset config transaction to the transaction group.\n * @param params The asset config transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetConfig(params) {\n this.txns.push({ ...params, type: 'assetConfig' });\n return this;\n }\n /**\n * Add an asset freeze transaction to the transaction group.\n * @param params The asset freeze transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetFreeze(params) {\n this.txns.push({ ...params, type: 'assetFreeze' });\n return this;\n }\n /**\n * Add an asset destroy transaction to the transaction group.\n * @param params The asset destroy transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetDestroy(params) {\n this.txns.push({ ...params, type: 'assetDestroy' });\n return this;\n }\n /**\n * Add an asset transfer transaction to the transaction group.\n * @param params The asset transfer transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetTransfer(params) {\n this.txns.push({ ...params, type: 'assetTransfer' });\n return this;\n }\n /**\n * Add an asset opt-in transaction to the transaction group.\n * @param params The asset opt-in transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetOptIn(params) {\n this.txns.push({ ...params, type: 'assetOptIn' });\n return this;\n }\n /**\n * Add an asset opt-out transaction to the transaction group.\n * @param params The asset opt-out transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAssetOptOut(params) {\n this.txns.push({ ...params, type: 'assetOptOut' });\n return this;\n }\n /**\n * Add an application create transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The application create transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppCreate(params) {\n this.txns.push({ ...params, type: 'appCall' });\n return this;\n }\n /**\n * Add an application update transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The application update transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppUpdate(params) {\n this.txns.push({ ...params, type: 'appCall', onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC });\n return this;\n }\n /**\n * Add an application delete transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The application delete transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppDelete(params) {\n this.txns.push({ ...params, type: 'appCall', onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC });\n return this;\n }\n /**\n * Add an application call transaction to the transaction group.\n *\n * If you want to create or update an app use `addAppCreate` or `addAppUpdate`.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The application call transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppCall(params) {\n this.txns.push({ ...params, type: 'appCall' });\n return this;\n }\n /**\n * Add an ABI method create application call transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The ABI create method application call transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppCreateMethodCall(params) {\n this.txns.push({ ...params, type: 'methodCall' });\n return this;\n }\n /**\n * Add an ABI method update application call transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The ABI update method application call transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppUpdateMethodCall(params) {\n this.txns.push({ ...params, type: 'methodCall', onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC });\n return this;\n }\n /**\n * Add an ABI method delete application call transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The ABI delete method application call transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppDeleteMethodCall(params) {\n this.txns.push({ ...params, type: 'methodCall', onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC });\n return this;\n }\n /**\n * Add a non-create/non-update ABI method application call transaction to the transaction group.\n *\n * Note: we recommend using app clients to make it easier to make app calls.\n * @param params The ABI method application call transaction parameters\n * @returns The composer so you can chain method calls\n */\n addAppCallMethodCall(params) {\n this.txns.push({ ...params, type: 'methodCall' });\n return this;\n }\n /**\n * Add an online key registration transaction to the transaction group.\n * @param params The online key registration transaction parameters\n * @returns The composer so you can chain method calls\n */\n addOnlineKeyRegistration(params) {\n this.txns.push({ ...params, type: 'keyReg' });\n return this;\n }\n /**\n * Add an offline key registration transaction to the transaction group.\n * @param params The offline key registration transaction parameters\n * @returns The composer so you can chain method calls\n */\n addOfflineKeyRegistration(params) {\n this.txns.push({ ...params, type: 'keyReg' });\n return this;\n }\n /**\n * Add the transactions within an `AtomicTransactionComposer` to the transaction group.\n * @param atc The `AtomicTransactionComposer` to build transactions from and add to the group\n * @returns The composer so you can chain method calls\n */\n addAtc(atc) {\n this.txns.push({ atc, type: 'atc' });\n return this;\n }\n /** Build an ATC and return transactions ready to be incorporated into a broader set of transactions this composer is composing */\n buildAtc(atc, processTransaction) {\n const group = atc.buildGroup();\n const txnWithSigners = group.map((ts, idx) => {\n // Remove underlying group ID from the transaction since it will be re-grouped when this TransactionComposer is built\n ts.txn.group = undefined;\n // Process transaction if a function is provided\n ts.txn = processTransaction?.(ts.txn, idx) ?? ts.txn;\n // If this was a method call stash the ABIMethod for later\n if (atc['methodCalls'].get(idx)) {\n this.txnMethodMap.set(ts.txn.txID(), atc['methodCalls'].get(idx));\n }\n return ts;\n });\n return txnWithSigners;\n }\n commonTxnBuildStep(params, txn, suggestedParams) {\n if (params.lease)\n txn.addLease(encodeLease(params.lease));\n if (params.rekeyTo)\n txn.addRekey(params.rekeyTo);\n const encoder = new TextEncoder();\n if (params.note)\n txn.note = typeof params.note === 'string' ? encoder.encode(params.note) : params.note;\n if (params.firstValidRound) {\n txn.firstRound = Number(params.firstValidRound);\n }\n if (params.lastValidRound) {\n txn.lastRound = Number(params.lastValidRound);\n }\n else {\n // If the validity window isn't set in this transaction or by default and we are pointing at\n // LocalNet set a bigger window to avoid dead transactions\n const window = params.validityWindow ??\n (!this.defaultValidityWindowIsExplicit && genesisIdIsLocalNet(suggestedParams.genesisID) ? 1000 : this.defaultValidityWindow);\n txn.lastRound = txn.firstRound + window;\n }\n if (params.staticFee !== undefined && params.extraFee !== undefined) {\n throw Error('Cannot set both staticFee and extraFee');\n }\n if (params.staticFee !== undefined) {\n txn.fee = Number(params.staticFee.microAlgo);\n }\n else {\n txn.fee = txn.estimateSize() * suggestedParams.fee || algosdk.ALGORAND_MIN_TX_FEE;\n if (params.extraFee)\n txn.fee += Number(params.extraFee.microAlgo);\n }\n txn.flatFee = true;\n if (params.maxFee !== undefined && txn.fee > params.maxFee.microAlgo) {\n throw Error(`Transaction fee ${txn.fee} µALGO is greater than maxFee ${params.maxFee}`);\n }\n return txn;\n }\n /**\n * Builds an ABI method call transaction and any other associated transactions represented in the ABI args.\n * @param includeSigner Whether to include the actual signer for the transactions.\n * If you are just building transactions without signers yet then set this to `false`.\n */\n async buildMethodCall(params, suggestedParams, includeSigner) {\n const methodArgs = [];\n const transactionsForGroup = [];\n const isAbiValue = (x) => {\n if (Array.isArray(x))\n return x.length == 0 || x.every(isAbiValue);\n return typeof x === 'bigint' || typeof x === 'boolean' || typeof x === 'number' || typeof x === 'string' || x instanceof Uint8Array;\n };\n for (let i = (params.args ?? []).length - 1; i >= 0; i--) {\n const arg = params.args[i];\n if (arg === undefined) {\n // An undefined transaction argument signals that the value will be supplied by a method call argument\n if (algosdk.abiTypeIsTransaction(params.method.args[i].type) && transactionsForGroup.length > 0) {\n // Move the last transaction from the group to the method call arguments to appease algosdk\n const placeholderTransaction = transactionsForGroup.splice(-1, 1)[0];\n methodArgs.push(placeholderTransaction);\n continue;\n }\n throw Error(`No value provided for argument ${i + 1} within call to ${params.method.name}`);\n }\n if (isAbiValue(arg)) {\n methodArgs.push(arg);\n continue;\n }\n if (isTransactionWithSigner(arg)) {\n methodArgs.push(arg);\n continue;\n }\n if ('method' in arg) {\n const tempTxnWithSigners = await this.buildMethodCall(arg, suggestedParams, includeSigner);\n // If there is any transaction args, add to the atc\n // Everything else should be added as method args\n methodArgs.push(...tempTxnWithSigners.slice(-1)); // Add the method call itself as a method arg\n transactionsForGroup.push(...tempTxnWithSigners.slice(0, -1).reverse()); // Add any transaction arguments to the atc\n continue;\n }\n const txn = await arg;\n methodArgs.push({\n txn,\n signer: includeSigner\n ? params.signer\n ? 'signer' in params.signer\n ? params.signer.signer\n : params.signer\n : this.getSigner(encodeAddress(txn.from.publicKey))\n : TransactionComposer.NULL_SIGNER,\n });\n }\n const methodAtc = new algosdk.AtomicTransactionComposer();\n transactionsForGroup.reverse().forEach((txn) => methodAtc.addTransaction(txn));\n const appId = Number('appId' in params ? params.appId : 0n);\n const approvalProgram = 'approvalProgram' in params\n ? typeof params.approvalProgram === 'string'\n ? (await this.appManager.compileTeal(params.approvalProgram)).compiledBase64ToBytes\n : params.approvalProgram\n : undefined;\n const clearStateProgram = 'clearStateProgram' in params\n ? typeof params.clearStateProgram === 'string'\n ? (await this.appManager.compileTeal(params.clearStateProgram)).compiledBase64ToBytes\n : params.clearStateProgram\n : undefined;\n methodAtc.addMethodCall({\n appID: appId,\n sender: params.sender,\n suggestedParams,\n onComplete: params.onComplete ?? algosdk.OnApplicationComplete.NoOpOC,\n appAccounts: params.accountReferences,\n appForeignApps: params.appReferences?.map((x) => Number(x)),\n appForeignAssets: params.assetReferences?.map((x) => Number(x)),\n boxes: params.boxReferences?.map(AppManager.getBoxReference),\n approvalProgram,\n clearProgram: clearStateProgram,\n extraPages: appId === 0\n ? 'extraProgramPages' in params && params.extraProgramPages !== undefined\n ? params.extraProgramPages\n : approvalProgram\n ? Math.floor((approvalProgram.length + (clearStateProgram?.length ?? 0)) / APP_PAGE_MAX_SIZE)\n : 0\n : undefined,\n numLocalInts: appId === 0 ? ('schema' in params ? (params.schema?.localInts ?? 0) : 0) : undefined,\n numLocalByteSlices: appId === 0 ? ('schema' in params ? (params.schema?.localByteSlices ?? 0) : 0) : undefined,\n numGlobalInts: appId === 0 ? ('schema' in params ? (params.schema?.globalInts ?? 0) : 0) : undefined,\n numGlobalByteSlices: appId === 0 ? ('schema' in params ? (params.schema?.globalByteSlices ?? 0) : 0) : undefined,\n method: params.method,\n signer: includeSigner\n ? params.signer\n ? 'signer' in params.signer\n ? params.signer.signer\n : params.signer\n : this.getSigner(params.sender)\n : TransactionComposer.NULL_SIGNER,\n methodArgs: methodArgs.reverse(),\n // note, lease, and rekeyTo are set in the common build step\n note: undefined,\n lease: undefined,\n rekeyTo: undefined,\n });\n // Process the ATC to get a set of transactions ready for broader grouping\n // and with the common build step to set fees and validity rounds\n return this.buildAtc(methodAtc, (txn, idx) => idx === methodAtc.count() - 1 ? this.commonTxnBuildStep(params, txn, suggestedParams) : txn);\n }\n buildPayment(params, suggestedParams) {\n const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({\n from: params.sender,\n to: params.receiver,\n amount: params.amount.microAlgo,\n closeRemainderTo: params.closeRemainderTo,\n suggestedParams,\n });\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n buildAssetCreate(params, suggestedParams) {\n const txn = algosdk.makeAssetCreateTxnWithSuggestedParamsFromObject({\n from: params.sender,\n total: params.total,\n decimals: params.decimals ?? 0,\n assetName: params.assetName,\n unitName: params.unitName,\n assetURL: params.url,\n defaultFrozen: params.defaultFrozen ?? false,\n assetMetadataHash: params.metadataHash,\n manager: params.manager,\n reserve: params.reserve,\n freeze: params.freeze,\n clawback: params.clawback,\n suggestedParams,\n });\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n buildAssetConfig(params, suggestedParams) {\n const txn = algosdk.makeAssetConfigTxnWithSuggestedParamsFromObject({\n from: params.sender,\n assetIndex: Number(params.assetId),\n suggestedParams,\n manager: params.manager,\n reserve: params.reserve,\n freeze: params.freeze,\n clawback: params.clawback,\n strictEmptyAddressChecking: false,\n });\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n buildAssetDestroy(params, suggestedParams) {\n const txn = algosdk.makeAssetDestroyTxnWithSuggestedParamsFromObject({\n from: params.sender,\n assetIndex: Number(params.assetId),\n suggestedParams,\n });\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n buildAssetFreeze(params, suggestedParams) {\n const txn = algosdk.makeAssetFreezeTxnWithSuggestedParamsFromObject({\n from: params.sender,\n assetIndex: Number(params.assetId),\n freezeTarget: params.account,\n freezeState: params.frozen,\n suggestedParams,\n });\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n buildAssetTransfer(params, suggestedParams) {\n const txn = algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({\n from: params.sender,\n to: params.receiver,\n assetIndex: Number(params.assetId),\n amount: params.amount,\n suggestedParams,\n closeRemainderTo: params.closeAssetTo,\n revocationTarget: params.clawbackTarget,\n });\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n async buildAppCall(params, suggestedParams) {\n const appId = Number('appId' in params ? params.appId : 0n);\n const approvalProgram = 'approvalProgram' in params\n ? typeof params.approvalProgram === 'string'\n ? (await this.appManager.compileTeal(params.approvalProgram)).compiledBase64ToBytes\n : params.approvalProgram\n : undefined;\n const clearStateProgram = 'clearStateProgram' in params\n ? typeof params.clearStateProgram === 'string'\n ? (await this.appManager.compileTeal(params.clearStateProgram)).compiledBase64ToBytes\n : params.clearStateProgram\n : undefined;\n const sdkParams = {\n from: params.sender,\n suggestedParams,\n appArgs: params.args,\n onComplete: params.onComplete ?? algosdk.OnApplicationComplete.NoOpOC,\n accounts: params.accountReferences,\n foreignApps: params.appReferences?.map((x) => Number(x)),\n foreignAssets: params.assetReferences?.map((x) => Number(x)),\n boxes: params.boxReferences?.map(AppManager.getBoxReference),\n approvalProgram,\n clearProgram: clearStateProgram,\n };\n let txn;\n if (appId === 0) {\n if (sdkParams.approvalProgram === undefined || sdkParams.clearProgram === undefined) {\n throw new Error('approvalProgram and clearStateProgram are required for application creation');\n }\n txn = algosdk.makeApplicationCreateTxnFromObject({\n ...sdkParams,\n extraPages: 'extraProgramPages' in params\n ? (params.extraProgramPages ?? Math.floor((approvalProgram.length + clearStateProgram.length) / APP_PAGE_MAX_SIZE))\n : 0,\n numLocalInts: 'schema' in params ? (params.schema?.localInts ?? 0) : 0,\n numLocalByteSlices: 'schema' in params ? (params.schema?.localByteSlices ?? 0) : 0,\n numGlobalInts: 'schema' in params ? (params.schema?.globalInts ?? 0) : 0,\n numGlobalByteSlices: 'schema' in params ? (params.schema?.globalByteSlices ?? 0) : 0,\n approvalProgram: approvalProgram,\n clearProgram: clearStateProgram,\n });\n }\n else {\n txn = algosdk.makeApplicationCallTxnFromObject({ ...sdkParams, appIndex: appId });\n }\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n buildKeyReg(params, suggestedParams) {\n let txn;\n if ('voteKey' in params) {\n // algosdk throws when voteFirst is 0, so we need to set it to 1, then switch back to 0 after creating the transaction\n const voteFirst = params.voteFirst === 0n ? 1n : params.voteFirst;\n txn = algosdk.makeKeyRegistrationTxnWithSuggestedParamsFromObject({\n from: params.sender,\n voteKey: params.voteKey,\n selectionKey: params.selectionKey,\n voteFirst: Number(voteFirst),\n voteLast: Number(params.voteLast),\n voteKeyDilution: Number(params.voteKeyDilution),\n suggestedParams,\n nonParticipation: false,\n stateProofKey: params.stateProofKey,\n });\n if (params.voteFirst === 0n) {\n txn.voteFirst = 0;\n }\n }\n else {\n txn = algosdk.makeKeyRegistrationTxnWithSuggestedParamsFromObject({\n from: params.sender,\n suggestedParams,\n nonParticipation: params.preventAccountFromEverParticipatingAgain,\n });\n }\n return this.commonTxnBuildStep(params, txn, suggestedParams);\n }\n /** Builds all transaction types apart from `txnWithSigner`, `atc` and `methodCall` since those ones can have custom signers that need to be retrieved. */\n async buildTxn(txn, suggestedParams) {\n switch (txn.type) {\n case 'pay':\n return [this.buildPayment(txn, suggestedParams)];\n case 'assetCreate':\n return [this.buildAssetCreate(txn, suggestedParams)];\n case 'appCall':\n return [await this.buildAppCall(txn, suggestedParams)];\n case 'assetConfig':\n return [this.buildAssetConfig(txn, suggestedParams)];\n case 'assetDestroy':\n return [this.buildAssetDestroy(txn, suggestedParams)];\n case 'assetFreeze':\n return [this.buildAssetFreeze(txn, suggestedParams)];\n case 'assetTransfer':\n return [this.buildAssetTransfer(txn, suggestedParams)];\n case 'assetOptIn':\n return [this.buildAssetTransfer({ ...txn, receiver: txn.sender, amount: 0n }, suggestedParams)];\n case 'assetOptOut':\n return [this.buildAssetTransfer({ ...txn, receiver: txn.sender, amount: 0n, closeAssetTo: txn.creator }, suggestedParams)];\n case 'keyReg':\n return [this.buildKeyReg(txn, suggestedParams)];\n default:\n throw Error(`Unsupported txn type`);\n }\n }\n async buildTxnWithSigner(txn, suggestedParams) {\n if (txn.type === 'txnWithSigner') {\n return [txn];\n }\n if (txn.type === 'atc') {\n return this.buildAtc(txn.atc);\n }\n if (txn.type === 'methodCall') {\n return await this.buildMethodCall(txn, suggestedParams, true);\n }\n const signer = txn.signer ? ('signer' in txn.signer ? txn.signer.signer : txn.signer) : this.getSigner(txn.sender);\n return (await this.buildTxn(txn, suggestedParams)).map((txn) => ({ txn, signer }));\n }\n /**\n * Compose all of the transactions without signers and return the transaction objects directly along with any ABI method calls.\n *\n * @returns The array of built transactions and any corresponding method calls\n */\n async buildTransactions() {\n const suggestedParams = await this.getSuggestedParams();\n const transactions = [];\n const methodCalls = new Map();\n const signers = new Map();\n for (const txn of this.txns) {\n if (!['txnWithSigner', 'atc', 'methodCall'].includes(txn.type)) {\n transactions.push(...(await this.buildTxn(txn, suggestedParams)));\n }\n else {\n const transactionsWithSigner = txn.type === 'txnWithSigner'\n ? [txn]\n : txn.type === 'atc'\n ? this.buildAtc(txn.atc)\n : txn.type === 'methodCall'\n ? await this.buildMethodCall(txn, suggestedParams, false)\n : [];\n transactions.push(...transactionsWithSigner.map((ts) => ts.txn));\n transactionsWithSigner.forEach((ts, idx) => {\n if (ts.signer && ts.signer !== TransactionComposer.NULL_SIGNER) {\n signers.set(idx, ts.signer);\n }\n });\n }\n }\n for (let i = 0; i < transactions.length; i++) {\n const method = this.txnMethodMap.get(transactions[i].txID());\n if (method)\n methodCalls.set(i, method);\n }\n return { transactions, methodCalls, signers };\n }\n /**\n * Get the number of transactions currently added to this composer.\n */\n async count() {\n return (await this.buildTransactions()).transactions.length;\n }\n /**\n * Compose all of the transactions in a single atomic transaction group and an atomic transaction composer.\n *\n * You can then use the transactions standalone, or use the composer to execute or simulate the transactions.\n *\n * Once this method is called, no further transactions will be able to be added.\n * You can safely call this method multiple times to get the same result.\n * @returns The built atomic transaction composer and the transactions\n */\n async build() {\n if (this.atc.getStatus() === algosdk.AtomicTransactionComposerStatus.BUILDING) {\n const suggestedParams = await this.getSuggestedParams();\n // Build all of the transactions\n const txnWithSigners = [];\n for (const txn of this.txns) {\n txnWithSigners.push(...(await this.buildTxnWithSigner(txn, suggestedParams)));\n }\n // Add all of the transactions to the underlying ATC\n const methodCalls = new Map();\n txnWithSigners.forEach((ts, idx) => {\n this.atc.addTransaction(ts);\n // Populate consolidated set of all ABI method calls\n const method = this.txnMethodMap.get(ts.txn.txID());\n if (method)\n methodCalls.set(idx, method);\n });\n this.atc['methodCalls'] = methodCalls;\n }\n return { atc: this.atc, transactions: this.atc.buildGroup(), methodCalls: this.atc['methodCalls'] };\n }\n /**\n * Rebuild the group, discarding any previously built transactions.\n * This will potentially cause new signers and suggested params to be used if the callbacks return a new value compared to the first build.\n * @returns The newly built atomic transaction composer and the transactions\n */\n async rebuild() {\n this.atc = new algosdk.AtomicTransactionComposer();\n return await this.build();\n }\n /**\n * Compose the atomic transaction group and send it to the network.\n * @param params The parameters to control execution with\n * @returns The execution result\n */\n async send(params) {\n const group = (await this.build()).transactions;\n let waitRounds = params?.maxRoundsToWaitForConfirmation;\n if (waitRounds === undefined) {\n const lastRound = group.reduce((max, txn) => Math.max(txn.txn.lastRound, max), 0);\n const { firstRound } = await this.getSuggestedParams();\n waitRounds = lastRound - firstRound + 1;\n }\n return await sendAtomicTransactionComposer({\n atc: this.atc,\n suppressLog: params?.suppressLog,\n maxRoundsToWaitForConfirmation: waitRounds,\n populateAppCallResources: params?.populateAppCallResources,\n }, this.algod);\n }\n /**\n * @deprecated Use `send` instead.\n *\n * Compose the atomic transaction group and send it to the network\n *\n * An alias for `composer.send(params)`.\n * @param params The parameters to control execution with\n * @returns The execution result\n */\n async execute(params) {\n return this.send(params);\n }\n async simulate(options) {\n const { skipSignatures = false, ...rawOptions } = options ?? {};\n const atc = skipSignatures ? new AtomicTransactionComposer() : this.atc;\n // Build the transactions\n if (skipSignatures) {\n rawOptions.allowEmptySignatures = true;\n rawOptions.fixSigners = true;\n // Build transactions uses empty signers\n const transactions = await this.buildTransactions();\n for (const txn of transactions.transactions) {\n atc.addTransaction({ txn, signer: TransactionComposer.NULL_SIGNER });\n }\n atc['methodCalls'] = transactions.methodCalls;\n }\n else {\n // Build creates real signatures\n await this.build();\n }\n const { methodResults, simulateResponse } = await atc.simulate(this.algod, new modelsv2.SimulateRequest({\n txnGroups: [],\n ...rawOptions,\n ...(Config.debug\n ? {\n allowEmptySignatures: true,\n fixSigners: true,\n allowMoreLogging: true,\n execTraceConfig: new modelsv2.SimulateTraceConfig({\n enable: true,\n scratchChange: true,\n stackChange: true,\n stateChange: true,\n }),\n }\n : undefined),\n }));\n const failedGroup = simulateResponse?.txnGroups[0];\n if (failedGroup?.failureMessage) {\n const errorMessage = `Transaction failed at transaction(s) ${failedGroup.failedAt?.join(', ') || 'unknown'} in the group. ${failedGroup.failureMessage}`;\n const error = new Error(errorMessage);\n if (Config.debug) {\n await Config.events.emitAsync(EventType.TxnGroupSimulated, { simulateResponse });\n }\n error.simulateResponse = simulateResponse;\n throw error;\n }\n if (Config.debug && Config.traceAll) {\n await Config.events.emitAsync(EventType.TxnGroupSimulated, { simulateResponse });\n }\n const transactions = atc.buildGroup().map((t) => t.txn);\n return {\n confirmations: simulateResponse.txnGroups[0].txnResults.map((t) => t.txnResult),\n transactions: transactions,\n txIds: transactions.map((t) => t.txID()),\n groupId: Buffer.from(transactions[0].group ?? new Uint8Array()).toString('base64'),\n simulateResponse,\n returns: methodResults.map(getABIReturnValue),\n };\n }\n /**\n * Create an encoded transaction note that follows the ARC-2 spec.\n *\n * https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md\n * @param note The ARC-2 transaction note data\n * @returns The binary encoded transaction note\n */\n static arc2Note(note) {\n const arc2Payload = `${note.dAppName}:${note.format}${typeof note.data === 'string' ? note.data : asJson(note.data)}`;\n const encoder = new TextEncoder();\n return encoder.encode(arc2Payload);\n }\n}\n/** Signer used to represent a lack of signer */\nTransactionComposer.NULL_SIGNER = algosdk.makeEmptyTransactionSigner();\n\nexport { MAX_TRANSACTION_GROUP_SIZE, TransactionComposer };\n//# sourceMappingURL=composer.mjs.map\n","import algosdk from 'algosdk';\nimport { UPDATABLE_TEMPLATE_NAME, DELETABLE_TEMPLATE_NAME } from './app.mjs';\nimport { getArc56Method, getArc56ReturnValue, getABITupleFromABIStruct, getABIDecodedValue } from './app-arc56.mjs';\nimport { AppClient } from './app-client.mjs';\n\nvar SourceMap = algosdk.SourceMap;\nvar OnApplicationComplete = algosdk.OnApplicationComplete;\n/**\n * ARC-56/ARC-32 app factory that, for a given app spec, allows you to create\n * and deploy one or more app instances and to create one or more app clients\n * to interact with those (or other) app instances.\n */\nclass AppFactory {\n constructor(params) {\n /** Create transactions for the current app */\n this.createTransaction = {\n /** Create bare (raw) transactions for the current app */\n bare: {\n /** Create a create call transaction, including deploy-time TEAL template replacements and compilation if provided */\n create: async (params) => {\n return this._algorand.createTransaction.appCreate(await this.params.bare.create(params));\n },\n },\n /** Create a create ABI call transaction, including deploy-time TEAL template replacements and compilation if provided */\n create: async (params) => {\n return this._algorand.createTransaction.appCreateMethodCall(await this.params.create(params));\n },\n };\n /** Send transactions to the current app */\n this.send = {\n /** Send bare (raw) transactions for the current app */\n bare: {\n create: async (params) => {\n const updatable = params?.updatable ?? this._updatable;\n const deletable = params?.deletable ?? this._deletable;\n const deployTimeParams = params?.deployTimeParams ?? this._deployTimeParams;\n const compiled = await this.compile({ deployTimeParams, updatable, deletable });\n const result = await this.handleCallErrors(async () => ({\n ...(await this._algorand.send.appCreate(await this.params.bare.create({ ...params, updatable, deletable, deployTimeParams }))),\n return: undefined,\n }));\n return {\n appClient: this.getAppClientById({\n appId: result.appId,\n }),\n result: {\n ...result,\n ...compiled,\n },\n };\n },\n },\n /**\n * Creates an instance of the app and returns the result of the creation\n * transaction and an app client to interact with that app instance.\n *\n * Performs deploy-time TEAL template placeholder substitutions (if specified).\n * @param params The parameters to create the app\n * @returns The app client and the result of the creation transaction\n */\n create: async (params) => {\n const updatable = params?.updatable ?? this._updatable;\n const deletable = params?.deletable ?? this._deletable;\n const deployTimeParams = params?.deployTimeParams ?? this._deployTimeParams;\n const compiled = await this.compile({ deployTimeParams, updatable, deletable });\n const result = await this.handleCallErrors(async () => this.parseMethodCallReturn(this._algorand.send.appCreateMethodCall(await this.params.create({ ...params, updatable, deletable, deployTimeParams })), getArc56Method(params.method, this._appSpec)));\n return {\n appClient: this.getAppClientById({\n appId: result.appId,\n }),\n result: {\n ...result,\n ...compiled,\n },\n };\n },\n };\n this._appSpec = AppClient.normaliseAppSpec(params.appSpec);\n this._appName = params.appName ?? this._appSpec.name;\n this._algorand = params.algorand;\n this._version = params.version ?? '1.0';\n this._defaultSender = params.defaultSender;\n this._defaultSigner = params.defaultSigner;\n this._deployTimeParams = params.deployTimeParams;\n this._updatable = params.updatable;\n this._deletable = params.deletable;\n this._paramsMethods = this.getParamsMethods();\n }\n /** The name of the app (from the ARC-32 / ARC-56 app spec or override). */\n get appName() {\n return this._appName;\n }\n /** The ARC-56 app spec being used */\n get appSpec() {\n return this._appSpec;\n }\n /** Return the algorand client this factory is using. */\n get algorand() {\n return this._algorand;\n }\n /** Get parameters to create transactions (create and deploy related calls) for the current app.\n *\n * A good mental model for this is that these parameters represent a deferred transaction creation.\n * @example Create a transaction in the future using Algorand Client\n * ```typescript\n * const createAppParams = appFactory.params.create({method: 'create_method', args: [123, 'hello']})\n * // ...\n * await algorand.send.AppCreateMethodCall(createAppParams)\n * ```\n * @example Define a nested transaction as an ABI argument\n * ```typescript\n * const createAppParams = appFactory.params.create({method: 'create_method', args: [123, 'hello']})\n * await appClient.send.call({method: 'my_method', args: [createAppParams]})\n * ```\n */\n get params() {\n return this._paramsMethods;\n }\n /**\n * Idempotently deploy (create if not exists, update if changed) an app against the given name for the given creator account, including deploy-time TEAL template placeholder substitutions (if specified).\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param params The arguments to control the app deployment\n * @returns The app client and the result of the deployment\n */\n async deploy(params) {\n const updatable = params.updatable ?? this._updatable ?? this.getDeployTimeControl('updatable');\n const deletable = params.deletable ?? this._deletable ?? this.getDeployTimeControl('deletable');\n const deployTimeParams = params.deployTimeParams ?? this._deployTimeParams;\n const compiled = await this.compile({ deployTimeParams, updatable, deletable });\n const deployResult = await this._algorand.appDeployer.deploy({\n ...params,\n createParams: await (params.createParams && 'method' in params.createParams\n ? this.params.create({ ...params.createParams, updatable, deletable, deployTimeParams })\n : this.params.bare.create({ ...params.createParams, updatable, deletable, deployTimeParams })),\n updateParams: params.updateParams && 'method' in params.updateParams\n ? this.params.deployUpdate(params.updateParams)\n : this.params.bare.deployUpdate(params.updateParams),\n deleteParams: params.deleteParams && 'method' in params.deleteParams\n ? this.params.deployDelete(params.deleteParams)\n : this.params.bare.deployDelete(params.deleteParams),\n metadata: {\n name: params.appName ?? this._appName,\n version: this._version,\n updatable,\n deletable,\n },\n });\n const appClient = this.getAppClientById({\n appId: deployResult.appId,\n appName: params.appName,\n });\n const result = {\n ...deployResult,\n ...compiled,\n };\n return {\n appClient,\n result: {\n ...result,\n return: 'return' in result\n ? result.operationPerformed === 'update'\n ? params.updateParams && 'method' in params.updateParams\n ? getArc56ReturnValue(result.return, getArc56Method(params.updateParams.method, this._appSpec), this._appSpec.structs)\n : undefined\n : params.createParams && 'method' in params.createParams\n ? getArc56ReturnValue(result.return, getArc56Method(params.createParams.method, this._appSpec), this._appSpec.structs)\n : undefined\n : undefined,\n deleteReturn: 'deleteReturn' in result && params.deleteParams && 'method' in params.deleteParams\n ? getArc56ReturnValue(result.deleteReturn, getArc56Method(params.deleteParams.method, this._appSpec), this._appSpec.structs)\n : undefined,\n },\n };\n }\n /**\n * Returns a new `AppClient` client for an app instance of the given ID.\n *\n * Automatically populates appName, defaultSender and source maps from the factory\n * if not specified in the params.\n * @param params The parameters to create the app client\n * @returns The `AppClient`\n */\n getAppClientById(params) {\n return new AppClient({\n ...params,\n algorand: this._algorand,\n appSpec: this._appSpec,\n appName: params.appName ?? this._appName,\n defaultSender: params.defaultSender ?? this._defaultSender,\n defaultSigner: params.defaultSigner ?? this._defaultSigner,\n approvalSourceMap: params.approvalSourceMap ?? this._approvalSourceMap,\n clearSourceMap: params.clearSourceMap ?? this._clearSourceMap,\n });\n }\n /**\n * Returns a new `AppClient` client, resolving the app by creator address and name\n * using AlgoKit app deployment semantics (i.e. looking for the app creation transaction note).\n *\n * Automatically populates appName, defaultSender and source maps from the factory\n * if not specified in the params.\n * @param params The parameters to create the app client\n * @returns The `AppClient`\n */\n getAppClientByCreatorAndName(params) {\n return AppClient.fromCreatorAndName({\n ...params,\n algorand: this._algorand,\n appSpec: this._appSpec,\n appName: params.appName ?? this._appName,\n defaultSender: params.defaultSender ?? this._defaultSender,\n approvalSourceMap: params.approvalSourceMap ?? this._approvalSourceMap,\n clearSourceMap: params.clearSourceMap ?? this._clearSourceMap,\n });\n }\n /**\n * Takes an error that may include a logic error from a call to the current app and re-exposes the\n * error to include source code information via the source map and ARC-56 spec.\n * @param e The error to parse\n * @param isClearStateProgram Whether or not the code was running the clear state program (defaults to approval program)\n * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n */\n exposeLogicError(e, isClearStateProgram) {\n return AppClient.exposeLogicError(e, this._appSpec, {\n isClearStateProgram,\n approvalSourceMap: this._approvalSourceMap,\n clearSourceMap: this._clearSourceMap,\n });\n }\n /**\n * Export the current source maps for the app.\n * @returns The source maps\n */\n exportSourceMaps() {\n if (!this._approvalSourceMap || !this._clearSourceMap) {\n throw new Error(\"Unable to export source maps; they haven't been loaded into this client - you need to call create, update, or deploy first\");\n }\n return {\n approvalSourceMap: this._approvalSourceMap,\n clearSourceMap: this._clearSourceMap,\n };\n }\n /**\n * Import source maps for the app.\n * @param sourceMaps The source maps to import\n */\n importSourceMaps(sourceMaps) {\n this._approvalSourceMap = new SourceMap(sourceMaps.approvalSourceMap);\n this._clearSourceMap = new SourceMap(sourceMaps.clearSourceMap);\n }\n getDeployTimeControl(control) {\n const approval = this._appSpec.source?.approval ? Buffer.from(this._appSpec.source.approval, 'base64').toString('utf-8') : undefined;\n // variable not present, so unknown control value\n if (!approval || !approval.includes(control === 'updatable' ? UPDATABLE_TEMPLATE_NAME : DELETABLE_TEMPLATE_NAME))\n return undefined;\n // A call is present and configured\n return (this._appSpec.bareActions.call.includes(control === 'updatable' ? 'UpdateApplication' : 'DeleteApplication') ||\n Object.values(this._appSpec.methods).some((c) => c.actions.call.includes(control === 'updatable' ? 'UpdateApplication' : 'DeleteApplication')));\n }\n getParamsMethods() {\n return {\n /** Return params for a create ABI call, including deploy-time TEAL template replacements and compilation if provided */\n create: async (params) => {\n const compiled = await this.compile({ ...params, deployTimeParams: params.deployTimeParams ?? this._deployTimeParams });\n return this.getABIParams({\n ...params,\n deployTimeParams: params.deployTimeParams ?? this._deployTimeParams,\n schema: params.schema ?? {\n globalByteSlices: this._appSpec.state.schema.global.bytes,\n globalInts: this._appSpec.state.schema.global.ints,\n localByteSlices: this._appSpec.state.schema.local.bytes,\n localInts: this._appSpec.state.schema.local.ints,\n },\n approvalProgram: compiled.approvalProgram,\n clearStateProgram: compiled.clearStateProgram,\n }, params.onComplete ?? OnApplicationComplete.NoOpOC);\n },\n /** Return params for a deployment update ABI call */\n deployUpdate: (params) => {\n return this.getABIParams(params, OnApplicationComplete.UpdateApplicationOC);\n },\n /** Return params for a deployment delete ABI call */\n deployDelete: (params) => {\n return this.getABIParams(params, OnApplicationComplete.DeleteApplicationOC);\n },\n bare: {\n /** Return params for a create bare call, including deploy-time TEAL template replacements and compilation if provided */\n create: async (params) => {\n return this.getBareParams({\n ...params,\n deployTimeParams: params?.deployTimeParams ?? this._deployTimeParams,\n schema: params?.schema ?? {\n globalByteSlices: this._appSpec.state.schema.global.bytes,\n globalInts: this._appSpec.state.schema.global.ints,\n localByteSlices: this._appSpec.state.schema.local.bytes,\n localInts: this._appSpec.state.schema.local.ints,\n },\n ...(await this.compile({ ...params, deployTimeParams: params?.deployTimeParams ?? this._deployTimeParams })),\n }, params?.onComplete ?? OnApplicationComplete.NoOpOC);\n },\n /** Return params for a deployment update bare call */\n deployUpdate: (params) => {\n return this.getBareParams(params, OnApplicationComplete.UpdateApplicationOC);\n },\n /** Return params for a deployment delete bare call */\n deployDelete: (params) => {\n return this.getBareParams(params, OnApplicationComplete.DeleteApplicationOC);\n },\n },\n };\n }\n /** Make the given call and catch any errors, augmenting with debugging information before re-throwing. */\n async handleCallErrors(call) {\n try {\n return await call();\n }\n catch (e) {\n throw this.exposeLogicError(e);\n }\n }\n /**\n * Compiles the approval and clear state programs (if TEAL templates provided),\n * performing any provided deploy-time parameter replacement and stores\n * the source maps.\n *\n * If no TEAL templates provided it will use any byte code provided in the app spec.\n *\n * Will store any generated source maps for later use in debugging.\n */\n async compile(compilation) {\n const result = await AppClient.compile(this._appSpec, this._algorand.app, compilation);\n if (result.compiledApproval) {\n this._approvalSourceMap = result.compiledApproval.sourceMap;\n }\n if (result.compiledClear) {\n this._clearSourceMap = result.compiledClear.sourceMap;\n }\n return result;\n }\n getBareParams(params, onComplete) {\n return {\n ...params,\n sender: this.getSender(params?.sender),\n signer: this.getSigner(params?.sender, params?.signer),\n onComplete,\n };\n }\n getABIParams(params, onComplete) {\n return {\n ...params,\n sender: this.getSender(params.sender),\n signer: this.getSigner(params.sender, params.signer),\n method: getArc56Method(params.method, this._appSpec),\n args: this.getCreateABIArgsWithDefaultValues(params.method, params.args),\n onComplete,\n };\n }\n getCreateABIArgsWithDefaultValues(methodNameOrSignature, args) {\n const m = getArc56Method(methodNameOrSignature, this._appSpec);\n return args?.map((a, i) => {\n const arg = m.args[i];\n if (a !== undefined) {\n // If a struct then convert to tuple for the underlying call\n return arg.struct && typeof a === 'object' && !Array.isArray(a)\n ? getABITupleFromABIStruct(a, this._appSpec.structs[arg.struct], this._appSpec.structs)\n : a;\n }\n const defaultValue = arg.defaultValue;\n if (defaultValue) {\n switch (defaultValue.source) {\n case 'literal':\n return getABIDecodedValue(Buffer.from(defaultValue.data, 'base64'), m.method.args[i].type, this._appSpec.structs);\n default:\n throw new Error(`Can't provide default value for ${defaultValue.source} for a contract creation call`);\n }\n }\n throw new Error(`No value provided for required argument ${arg.name ?? `arg${i + 1}`} in call to method ${m.name}`);\n });\n }\n /** Returns the sender for a call, using the `defaultSender`\n * if none provided and throws an error if neither provided */\n getSender(sender) {\n if (!sender && !this._defaultSender) {\n throw new Error(`No sender provided and no default sender present in app client for call to app ${this._appName}`);\n }\n return sender ?? this._defaultSender;\n }\n /** Returns the signer for a call, using the provided signer or the `defaultSigner`\n * if no signer was provided and the sender resolves to the default sender, the call will use default signer\n * or `undefined` otherwise (so the signer is resolved from `AlgorandClient`) */\n getSigner(sender, signer) {\n return signer ?? (!sender || sender === this._defaultSender ? this._defaultSigner : undefined);\n }\n /**\n * Checks for decode errors on the SendAppTransactionResult and maps the return value to the specified type\n * on the ARC-56 method.\n *\n * If the return type is a struct then the struct will be returned.\n *\n * @param result The SendAppTransactionResult to be mapped\n * @param method The method that was called\n * @returns The smart contract response with an updated return value\n */\n async parseMethodCallReturn(result, method) {\n const resultValue = await result;\n return { ...resultValue, return: getArc56ReturnValue(resultValue.return, method, this._appSpec.structs) };\n }\n}\n\nexport { AppFactory };\n//# sourceMappingURL=app-factory.mjs.map\n","import algosdk from 'algosdk';\nimport { AlgorandClientTransactionCreator } from '../types/algorand-client-transaction-creator.mjs';\nimport { AlgorandClientTransactionSender } from '../types/algorand-client-transaction-sender.mjs';\nimport { AppManager } from '../types/app-manager.mjs';\nimport { AssetManager } from '../types/asset-manager.mjs';\nimport { TransactionComposer } from '../types/composer.mjs';\nimport { getSenderTransactionSigner, getSenderAddress, encodeTransactionNote, encodeLease } from './transaction.mjs';\n\nvar ABIMethod = algosdk.ABIMethod;\n/** @deprecated Bridges between legacy `sendTransaction` behaviour and new `AlgorandClient` behaviour. */\nasync function legacySendTransactionBridge(algod, from, sendParams, params, txn, send, suggestedParams) {\n const appManager = new AppManager(algod);\n const newGroup = () => new TransactionComposer({\n algod,\n getSigner: () => getSenderTransactionSigner(from),\n getSuggestedParams: async () => (suggestedParams ? { ...suggestedParams } : await algod.getTransactionParams().do()),\n appManager,\n });\n const transactionSender = new AlgorandClientTransactionSender(newGroup, new AssetManager(algod, newGroup), appManager);\n const transactionCreator = new AlgorandClientTransactionCreator(newGroup);\n if (sendParams.fee) {\n params.staticFee = sendParams.fee;\n }\n if (sendParams.maxFee) {\n params.maxFee = sendParams.maxFee;\n }\n if (sendParams.atc || sendParams.skipSending) {\n const transaction = await txn(transactionCreator)(params);\n const txns = 'transactions' in transaction ? transaction.transactions : [transaction];\n if (sendParams.atc) {\n const baseIndex = sendParams.atc.count();\n txns\n .map((txn, i) => ({\n txn,\n signer: 'signers' in transaction ? (transaction.signers.get(i) ?? getSenderTransactionSigner(from)) : getSenderTransactionSigner(from),\n }))\n .forEach((t) => sendParams.atc.addTransaction(t));\n // Populate ATC with method calls\n if ('transactions' in transaction) {\n transaction.methodCalls.forEach((m, i) => sendParams.atc['methodCalls'].set(i + baseIndex, m));\n }\n }\n return { transaction: txns.at(-1), transactions: txns };\n }\n return { ...(await send(transactionSender)({ ...sendParams, ...params })) };\n}\n/** @deprecated Bridges between legacy `sendTransaction` behaviour for app transactions and new `AlgorandClient` behaviour. */\nasync function legacySendAppTransactionBridge(algod, from, appArgs, sendParams, params, txn, send, suggestedParams) {\n const encoder = new TextEncoder();\n const paramsWithAppArgs = {\n ...params,\n accountReferences: appArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: appArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: appArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: appArgs?.boxes?.map(_getBoxReference)?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name })),\n lease: appArgs?.lease,\n rekeyTo: appArgs?.rekeyTo ? getSenderAddress(appArgs?.rekeyTo) : undefined,\n args: appArgs\n ? 'methodArgs' in appArgs\n ? (await _getAppArgsForABICall(appArgs, from)).methodArgs\n : appArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n note: encodeTransactionNote(sendParams?.note),\n };\n return await legacySendTransactionBridge(algod, from, sendParams, paramsWithAppArgs, txn, send, suggestedParams);\n}\n/**\n * @deprecated\n */\nasync function _getAppArgsForABICall(args, from) {\n const signer = getSenderTransactionSigner(from);\n const methodArgs = await Promise.all(('methodArgs' in args ? args.methodArgs : args)?.map(async (a, index) => {\n if (a === undefined) {\n throw new Error(`Argument at position ${index} does not have a value`);\n }\n if (typeof a !== 'object') {\n return a;\n }\n // Handle the various forms of transactions to wrangle them for ATC\n return 'txn' in a\n ? a\n : a instanceof Promise\n ? { txn: (await a).transaction, signer }\n : 'transaction' in a\n ? { txn: a.transaction, signer: 'signer' in a ? getSenderTransactionSigner(a.signer) : signer }\n : 'txID' in a\n ? { txn: a, signer }\n : a;\n }));\n return {\n method: 'txnCount' in args.method ? args.method : new ABIMethod(args.method),\n sender: getSenderAddress(from),\n signer: signer,\n boxes: args.boxes?.map(_getBoxReference),\n lease: encodeLease(args.lease),\n appForeignApps: args.apps,\n appForeignAssets: args.assets,\n appAccounts: args.accounts?.map(_getAccountAddress),\n methodArgs: methodArgs,\n rekeyTo: args?.rekeyTo ? (typeof args.rekeyTo === 'string' ? args.rekeyTo : getSenderAddress(args.rekeyTo)) : undefined,\n };\n}\nfunction _getAccountAddress(account) {\n return typeof account === 'string' ? account : algosdk.encodeAddress(account.publicKey);\n}\n/** @deprecated */\nfunction _getBoxReference(box) {\n const encoder = new TextEncoder();\n if (typeof box === 'object' && 'appIndex' in box) {\n return box;\n }\n const ref = typeof box === 'object' && 'appId' in box ? box : { appId: 0, name: box };\n return {\n appIndex: ref.appId,\n name: typeof ref.name === 'string'\n ? encoder.encode(ref.name)\n : 'length' in ref.name\n ? ref.name\n : algosdk.decodeAddress(getSenderAddress(ref.name)).publicKey,\n };\n}\n\nexport { _getAppArgsForABICall, _getBoxReference, legacySendAppTransactionBridge, legacySendTransactionBridge };\n//# sourceMappingURL=legacy-bridge.mjs.map\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-console */\n/** A logger implementation that writes to console */\nconst consoleLogger = {\n error: console.error,\n warn: console.warn,\n info: console.info,\n verbose: () => { },\n debug: console.debug,\n};\nconst infoConsoleLogger = {\n error: console.error,\n warn: console.warn,\n info: console.info,\n verbose: () => { },\n debug: () => { },\n};\nconst verboseConsoleLogger = {\n error: console.error,\n warn: console.warn,\n info: console.info,\n verbose: console.trace,\n debug: console.debug,\n};\nconst warningConsoleLogger = {\n error: console.error,\n warn: console.warn,\n info: () => { },\n verbose: () => { },\n debug: () => { },\n};\n/** A logger implementation that does nothing */\nconst nullLogger = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n error: function (message, ...optionalParams) { },\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n warn: function (message, ...optionalParams) { },\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n info: function (message, ...optionalParams) { },\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n verbose: function (message, ...optionalParams) { },\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n debug: function (message, ...optionalParams) { },\n};\n\nexport { consoleLogger, infoConsoleLogger, nullLogger, verboseConsoleLogger, warningConsoleLogger };\n//# sourceMappingURL=logging.mjs.map\n","import algosdk from 'algosdk';\n\n/**\n * Wrapper around `algosdk.ABIMethod` that represents an ARC-56 ABI method.\n */\nclass Arc56Method extends algosdk.ABIMethod {\n constructor(method) {\n super(method);\n this.method = method;\n this.args = method.args.map((arg) => ({\n ...arg,\n type: algosdk.abiTypeIsTransaction(arg.type) || algosdk.abiTypeIsReference(arg.type) ? arg.type : algosdk.ABIType.from(arg.type),\n }));\n this.returns = {\n ...this.method.returns,\n type: this.method.returns.type === 'void' ? 'void' : algosdk.ABIType.from(this.method.returns.type),\n };\n }\n toJSON() {\n return this.method;\n }\n}\n/**\n * Returns the `ABITupleType` for the given ARC-56 struct definition\n * @param struct The ARC-56 struct definition\n * @returns The `ABITupleType`\n */\nfunction getABITupleTypeFromABIStructDefinition(struct, structs) {\n return new algosdk.ABITupleType(struct.map((v) => typeof v.type === 'string'\n ? structs[v.type]\n ? getABITupleTypeFromABIStructDefinition(structs[v.type], structs)\n : algosdk.ABIType.from(v.type)\n : getABITupleTypeFromABIStructDefinition(v.type, structs)));\n}\n/**\n * Converts a decoded ABI tuple as a struct.\n * @param decodedABITuple The decoded ABI tuple value\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a Record\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getABIStructFromABITuple(decodedABITuple, structFields, structs) {\n return Object.fromEntries(structFields.map(({ name: key, type }, i) => {\n const abiValue = decodedABITuple[i];\n return [\n key,\n (typeof type === 'string' && !structs[type]) || !Array.isArray(abiValue)\n ? decodedABITuple[i]\n : getABIStructFromABITuple(abiValue, typeof type === 'string' ? structs[type] : type, structs),\n ];\n }));\n}\n/**\n * Converts an ARC-56 struct as an ABI tuple.\n * @param struct The struct to convert\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a decoded ABI tuple\n */\nfunction getABITupleFromABIStruct(struct, structFields, structs) {\n return structFields.map(({ name: key, type }) => {\n const value = struct[key];\n return typeof type === 'string' && !structs[type]\n ? value\n : getABITupleFromABIStruct(value, typeof type === 'string' ? structs[type] : type, structs);\n });\n}\n/**\n * Returns the decoded ABI value (or struct for a struct type)\n * for the given raw Algorand value given an ARC-56 type and defined ARC-56 structs.\n * @param value The raw Algorand value (bytes or uint64)\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The decoded ABI value or struct\n */\nfunction getABIDecodedValue(value, type, structs) {\n if (type === 'AVMBytes' || typeof value !== 'object')\n return value;\n if (type === 'AVMString')\n return Buffer.from(value).toString('utf-8');\n if (type === 'AVMUint64')\n return algosdk.ABIType.from('uint64').decode(value);\n if (structs[type]) {\n const tupleValue = getABITupleTypeFromABIStructDefinition(structs[type], structs).decode(value);\n return getABIStructFromABITuple(tupleValue, structs[type], structs);\n }\n return algosdk.ABIType.from(type).decode(value);\n}\n/**\n * Returns the ABI-encoded value for the given value.\n * @param value The value to encode either already in encoded binary form (`Uint8Array`), a decoded ABI value or an ARC-56 struct\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The binary ABI-encoded value\n */\nfunction getABIEncodedValue(value, type, structs) {\n if (typeof value === 'object' && value instanceof Uint8Array)\n return value;\n if (type === 'AVMUint64')\n return algosdk.ABIType.from('uint64').encode(value);\n if (type === 'AVMBytes' || type === 'AVMString') {\n if (typeof value === 'string')\n return Buffer.from(value, 'utf-8');\n if (typeof value !== 'object' || !(value instanceof Uint8Array))\n throw new Error(`Expected bytes value for ${type}, but got ${value}`);\n return value;\n }\n if (structs[type]) {\n const tupleType = getABITupleTypeFromABIStructDefinition(structs[type], structs);\n if (Array.isArray(value)) {\n tupleType.encode(value);\n }\n else {\n return tupleType.encode(getABITupleFromABIStruct(value, structs[type], structs));\n }\n }\n return algosdk.ABIType.from(type).encode(value);\n}\n/**\n * Returns the ARC-56 ABI method object for a given method name or signature and ARC-56 app spec.\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @param appSpec The app spec for the app\n * @returns The `Arc56Method`\n */\nfunction getArc56Method(methodNameOrSignature, appSpec) {\n let method;\n if (!methodNameOrSignature.includes('(')) {\n const methods = appSpec.methods.filter((m) => m.name === methodNameOrSignature);\n if (methods.length === 0)\n throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`);\n if (methods.length > 1) {\n throw new Error(`Received a call to method ${methodNameOrSignature} in contract ${appSpec.name}, but this resolved to multiple methods; please pass in an ABI signature instead: ${appSpec.methods\n .map((m) => new algosdk.ABIMethod(m).getSignature())\n .join(', ')}`);\n }\n method = methods[0];\n }\n else {\n const m = appSpec.methods.find((m) => new algosdk.ABIMethod(m).getSignature() === methodNameOrSignature);\n if (!m)\n throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`);\n method = m;\n }\n return new Arc56Method(method);\n}\n/**\n * Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type\n *\n * @param returnValue The smart contract response\n * @param method The method that was called\n * @param structs The struct fields from the app spec\n * @returns The smart contract response with an updated return value\n */\nfunction getArc56ReturnValue(returnValue, method, structs) {\n const m = 'method' in method ? method.method : method;\n const type = m.returns.struct ?? m.returns.type;\n if (returnValue?.decodeError) {\n throw returnValue.decodeError;\n }\n if (type === undefined || type === 'void' || returnValue?.returnValue === undefined)\n return undefined;\n if (type === 'AVMBytes')\n return returnValue.rawReturnValue;\n if (type === 'AVMString')\n return Buffer.from(returnValue.rawReturnValue).toString('utf-8');\n if (type === 'AVMUint64')\n return algosdk.ABIType.from('uint64').decode(returnValue.rawReturnValue);\n if (structs[type]) {\n return getABIStructFromABITuple(returnValue.returnValue, structs[type], structs);\n }\n return returnValue.returnValue;\n}\n\nexport { Arc56Method, getABIDecodedValue, getABIEncodedValue, getABIStructFromABITuple, getABITupleFromABIStruct, getABITupleTypeFromABIStructDefinition, getArc56Method, getArc56ReturnValue };\n//# sourceMappingURL=app-arc56.mjs.map\n","import algosdk from 'algosdk';\nimport { getAppOnCompleteAction, compileTeal } from './app.mjs';\nimport { _getBoxReference, _getAppArgsForABICall } from './transaction/legacy-bridge.mjs';\nimport { getSenderAddress, getSenderTransactionSigner } from './transaction/transaction.mjs';\nimport { AlgorandClientTransactionSender } from './types/algorand-client-transaction-sender.mjs';\nimport { APP_DEPLOY_NOTE_DAPP } from './types/app.mjs';\nimport { AppDeployer } from './types/app-deployer.mjs';\nimport { AppManager } from './types/app-manager.mjs';\nimport { AssetManager } from './types/asset-manager.mjs';\nimport { TransactionComposer } from './types/composer.mjs';\n\n/**\n * @deprecated Use `algorand.appDeployer.deploy` instead.\n *\n * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deployment The arguments to control the app deployment\n * @param algod An algod client\n * @param indexer An indexer client, needed if `existingDeployments` not passed in\n * @returns The app reference of the new/existing app\n */\nasync function deployApp(deployment, algod, indexer) {\n const appManager = new AppManager(algod);\n const newGroup = () => new TransactionComposer({\n algod,\n getSigner: () => getSenderTransactionSigner(deployment.from),\n getSuggestedParams: async () => deployment.transactionParams ? { ...deployment.transactionParams } : await algod.getTransactionParams().do(),\n appManager,\n });\n const deployer = new AppDeployer(appManager, new AlgorandClientTransactionSender(newGroup, new AssetManager(algod, newGroup), appManager), indexer);\n const createParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.createArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.createArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.createArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.createArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name })),\n lease: deployment.createArgs?.lease,\n rekeyTo: deployment.createArgs?.rekeyTo ? getSenderAddress(deployment.createArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n extraProgramPages: deployment.schema.extraPages,\n onComplete: getAppOnCompleteAction(deployment.createOnCompleteAction),\n schema: deployment.schema,\n };\n const updateParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.updateArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.updateArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.updateArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.updateArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name })),\n lease: deployment.updateArgs?.lease,\n rekeyTo: deployment.updateArgs?.rekeyTo ? getSenderAddress(deployment.updateArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n };\n const deleteParams = {\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.deleteArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.deleteArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.deleteArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.deleteArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name })),\n lease: deployment.deleteArgs?.lease,\n rekeyTo: deployment.deleteArgs?.rekeyTo ? getSenderAddress(deployment.deleteArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n };\n const encoder = new TextEncoder();\n const result = await deployer.deploy({\n createParams: deployment.createArgs?.method\n ? ({\n ...createParams,\n method: 'txnCount' in deployment.createArgs.method ? deployment.createArgs.method : new algosdk.ABIMethod(deployment.createArgs.method),\n args: (await _getAppArgsForABICall(deployment.createArgs, deployment.from)).methodArgs,\n })\n : ({\n ...createParams,\n args: 'appArgs' in (deployment?.createArgs ?? {})\n ? deployment.createArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n }),\n updateParams: deployment.updateArgs?.method\n ? ({\n ...updateParams,\n method: 'txnCount' in deployment.updateArgs.method ? deployment.updateArgs.method : new algosdk.ABIMethod(deployment.updateArgs.method),\n args: (await _getAppArgsForABICall(deployment.updateArgs, deployment.from)).methodArgs,\n })\n : ({\n ...updateParams,\n args: 'appArgs' in (deployment?.updateArgs ?? {})\n ? deployment.updateArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n }),\n deleteParams: deployment.deleteArgs?.method\n ? ({\n ...deleteParams,\n method: 'txnCount' in deployment.deleteArgs.method ? deployment.deleteArgs.method : new algosdk.ABIMethod(deployment.deleteArgs.method),\n args: (await _getAppArgsForABICall(deployment.deleteArgs, deployment.from)).methodArgs,\n })\n : ({\n ...deleteParams,\n args: 'appArgs' in (deployment?.deleteArgs ?? {})\n ? deployment.deleteArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n }),\n metadata: deployment.metadata,\n deployTimeParams: deployment.deployTimeParams,\n onSchemaBreak: deployment.onSchemaBreak,\n onUpdate: deployment.onUpdate,\n existingDeployments: deployment.existingDeployments\n ? {\n creator: deployment.existingDeployments.creator,\n apps: Object.fromEntries(Object.entries(deployment.existingDeployments.apps).map(([name, app]) => [\n name,\n { ...app, appId: BigInt(app.appId), createdRound: BigInt(app.createdRound), updatedRound: BigInt(app.updatedRound) },\n ])),\n }\n : undefined,\n maxRoundsToWaitForConfirmation: deployment.maxRoundsToWaitForConfirmation,\n populateAppCallResources: deployment.populateAppCallResources,\n suppressLog: deployment.suppressLog,\n });\n return { ...result, appId: Number(result.appId), createdRound: Number(result.createdRound), updatedRound: Number(result.updatedRound) };\n}\n/**\n * @deprecated Use `before.numByteSlice < after.numByteSlice || before.numUint < after.numUint` instead.\n *\n * Returns true is there is a breaking change in the application state schema from before to after.\n * i.e. if the schema becomes larger, since applications can't ask for more schema after creation.\n * Otherwise, there is no error, the app just doesn't store data in the extra schema :(\n *\n * @param before The existing schema\n * @param after The new schema\n * @returns Whether or not there is a breaking change\n */\nfunction isSchemaIsBroken(before, after) {\n return before.numByteSlice < after.numByteSlice || before.numUint < after.numUint;\n}\n/**\n * @deprecated Use `algorand.appDeployer.getCreatorAppsByName` instead.\n *\n * Returns a lookup of name => app metadata (id, address, ...metadata) for all apps created by the given account that have an `AppDeployNote` in the transaction note of the creation transaction.\n *\n * **Note:** It's recommended this is only called once and then stored since it's a somewhat expensive operation (multiple indexer calls).\n *\n * @param creatorAccount The account (with private key loaded) or string address of an account that is the creator of the apps you want to search for\n * @param indexer An indexer client\n * @returns A name-based lookup of the app information (id, address)\n */\nasync function getCreatorAppsByName(creatorAccount, indexer) {\n const lookup = await new AppDeployer(undefined, undefined, indexer).getCreatorAppsByName(getSenderAddress(creatorAccount));\n return {\n creator: lookup.creator,\n apps: Object.fromEntries(Object.entries(lookup.apps).map(([name, app]) => [\n name,\n { ...app, appId: Number(app.appId), createdRound: Number(app.createdRound), updatedRound: Number(app.updatedRound) },\n ])),\n };\n}\n/**\n * @deprecated Use `{ dAppName: APP_DEPLOY_NOTE_DAPP, data: metadata, format: 'j' }` instead.\n *\n * Return the transaction note for an app deployment.\n * @param metadata The metadata of the deployment\n * @returns The transaction note as a utf-8 string\n */\nfunction getAppDeploymentTransactionNote(metadata) {\n return {\n dAppName: APP_DEPLOY_NOTE_DAPP,\n data: metadata,\n format: 'j',\n };\n}\n/**\n * @deprecated Use `AppManager.replaceTealTemplateDeployTimeControlParams` instead\n *\n * Replaces deploy-time deployment control parameters within the given teal code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are not undefined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealCode The TEAL code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n */\nfunction replaceDeployTimeControlParams(tealCode, params) {\n return AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, params);\n}\n/**\n * @deprecated Use `AppManager.replaceTealTemplateParams` instead\n *\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @returns The TEAL code with replacements\n */\nfunction performTemplateSubstitution(tealCode, templateParams) {\n return AppManager.replaceTealTemplateParams(tealCode, templateParams);\n}\n/**\n * @deprecated Use `algorand.appManager.compileTealTemplate` instead.\n *\n * Performs template substitution of a teal file and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param algod An algod client\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @param deploymentMetadata The deployment metadata the app will be deployed with\n * @returns The information about the compiled code\n */\nasync function performTemplateSubstitutionAndCompile(tealCode, algod, templateParams, deploymentMetadata) {\n tealCode = stripTealComments(tealCode);\n tealCode = performTemplateSubstitution(tealCode, templateParams);\n if (deploymentMetadata) {\n tealCode = replaceDeployTimeControlParams(tealCode, deploymentMetadata);\n }\n return await compileTeal(tealCode, algod);\n}\n/**\n * @deprecated Use `AppManager.stripTealComments` instead.\n *\n * Remove comments from TEAL Code\n *\n * @param tealCode The TEAL logic to compile\n * @returns The TEAL without comments\n */\nfunction stripTealComments(tealCode) {\n return AppManager.stripTealComments(tealCode);\n}\n\nexport { deployApp, getAppDeploymentTransactionNote, getCreatorAppsByName, isSchemaIsBroken, performTemplateSubstitution, performTemplateSubstitutionAndCompile, replaceDeployTimeControlParams, stripTealComments };\n//# sourceMappingURL=app-deploy.mjs.map\n","import algosdk from 'algosdk';\nimport { getABIReturnValue } from '../transaction/transaction.mjs';\nimport { UPDATABLE_TEMPLATE_NAME, DELETABLE_TEMPLATE_NAME } from './app.mjs';\n\nvar modelsv2 = algosdk.modelsv2;\n/** Allows management of application information. */\nclass AppManager {\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod) {\n this._compilationResults = {};\n this._algod = algod;\n }\n /**\n * Compiles the given TEAL using algod and returns the result, including source map.\n *\n * The result of this compilation is also cached keyed by the TEAL\n * code so it can be retrieved via `getCompilationResult`.\n *\n * This function is re-entrant; it will only compile the same code once.\n *\n * @param tealCode The TEAL code\n * @returns The information about the compiled file\n */\n async compileTeal(tealCode) {\n if (this._compilationResults[tealCode]) {\n return this._compilationResults[tealCode];\n }\n const compiled = await this._algod.compile(tealCode).sourcemap(true).do();\n const result = {\n teal: tealCode,\n compiled: compiled.result,\n compiledHash: compiled.hash,\n compiledBase64ToBytes: new Uint8Array(Buffer.from(compiled.result, 'base64')),\n sourceMap: new algosdk.SourceMap(compiled['sourcemap']),\n };\n this._compilationResults[tealCode] = result;\n return result;\n }\n /**\n * Performs template substitution of a teal template and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements and replaces AlgoKit deploy-time control parameters\n * if deployment metadata is specified.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * @param tealTemplateCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @param deploymentMetadata The deployment metadata the app will be deployed with\n * @returns The information about the compiled code\n */\n async compileTealTemplate(tealTemplateCode, templateParams, deploymentMetadata) {\n let tealCode = AppManager.stripTealComments(tealTemplateCode);\n tealCode = AppManager.replaceTealTemplateParams(tealCode, templateParams);\n if (deploymentMetadata) {\n tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, deploymentMetadata);\n }\n return await this.compileTeal(tealCode);\n }\n /**\n * Returns a previous compilation result.\n * @param tealCode The TEAL code\n * @returns The information about the previously compiled file\n * or `undefined` if that TEAL code wasn't previously compiled\n */\n getCompilationResult(tealCode) {\n return this._compilationResults[tealCode];\n }\n /**\n * Returns the current app information for the app with the given ID.\n *\n * @example\n * ```typescript\n * const appInfo = await appManager.getById(12353n);\n * ```\n *\n * @param appId The ID of the app\n * @returns The app information\n */\n async getById(appId) {\n const app = modelsv2.Application.from_obj_for_encoding(await this._algod.getApplicationByID(Number(appId)).do());\n return {\n appId: BigInt(app.id),\n appAddress: algosdk.getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: Number(app.params.localStateSchema?.numUint ?? 0),\n localByteSlices: Number(app.params.localStateSchema?.numByteSlice ?? 0),\n globalInts: Number(app.params.globalStateSchema?.numUint ?? 0),\n globalByteSlices: Number(app.params.globalStateSchema?.numByteSlice ?? 0),\n extraProgramPages: Number(app.params.extraProgramPages ?? 0),\n globalState: AppManager.decodeAppState(app.params.globalState ?? []),\n };\n }\n /**\n * Returns the current global state values for the given app ID and account address\n *\n * @param appId The ID of the app to return global state for\n * @returns The current global state for the given app\n */\n async getGlobalState(appId) {\n return (await this.getById(appId)).globalState;\n }\n /**\n * Returns the current local state values for the given app ID and account address\n *\n * @param appId The ID of the app to return local state for\n * @param address The string address of the account to get local state for the given app\n * @returns The current local state for the given (app, account) combination\n */\n async getLocalState(appId, address) {\n const appInfo = modelsv2.AccountApplicationResponse.from_obj_for_encoding(await this._algod.accountApplicationInformation(address, Number(appId)).do());\n if (!appInfo.appLocalState?.keyValue) {\n throw new Error(\"Couldn't find local state\");\n }\n return AppManager.decodeAppState(appInfo.appLocalState.keyValue);\n }\n /**\n * Returns the names of the current boxes for the given app.\n * @param appId The ID of the app return box names for\n * @returns The current box names\n */\n async getBoxNames(appId) {\n const boxResult = await this._algod.getApplicationBoxes(Number(appId)).do();\n return boxResult.boxes.map((b) => {\n return {\n nameRaw: b.name,\n nameBase64: Buffer.from(b.name).toString('base64'),\n name: Buffer.from(b.name).toString('utf-8'),\n };\n });\n }\n /**\n * Returns the value of the given box name for the given app.\n * @param appId The ID of the app return box names for\n * @param boxName The name of the box to return either as a string, binary array or `BoxName`\n * @returns The current box value as a byte array\n */\n async getBoxValue(appId, boxName) {\n const boxId = typeof boxName === 'object' && 'nameRaw' in boxName ? boxName.nameRaw : boxName;\n const name = AppManager.getBoxReference(boxId).name;\n const boxResult = await this._algod.getApplicationBoxByName(Number(appId), name).do();\n return boxResult.value;\n }\n /**\n * Returns the value of the given box names for the given app.\n * @param appId The ID of the app return box names for\n * @param boxNames The names of the boxes to return either as a string, binary array or `BoxName`\n * @returns The current box values as a byte array in the same order as the passed in box names\n */\n async getBoxValues(appId, boxNames) {\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValue(appId, boxName)));\n }\n /**\n * Returns the value of the given box name for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box value as an ABI value\n */\n async getBoxValueFromABIType(request) {\n const { appId, boxName, type } = request;\n const value = await this.getBoxValue(appId, boxName);\n return type.decode(value);\n }\n /**\n * Returns the value of the given box names for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box values as an ABI value in the same order as the passed in box names\n */\n async getBoxValuesFromABIType(request) {\n const { appId, boxNames, type } = request;\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValueFromABIType({ appId, boxName, type })));\n }\n /**\n * Returns a `algosdk.BoxReference` given a `BoxIdentifier` or `BoxReference`.\n * @param boxId The box to return a reference for\n * @returns The box reference ready to pass into a `algosdk.Transaction`\n */\n static getBoxReference(boxId) {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId };\n return {\n appIndex: Number(ref.appId),\n name: typeof ref.name === 'string'\n ? new TextEncoder().encode(ref.name)\n : 'length' in ref.name\n ? ref.name\n : algosdk.decodeAddress(ref.name.addr).publicKey,\n };\n }\n /**\n * Converts an array of global/local state values from the algod api to a more friendly\n * generic object keyed by the UTF-8 value of the key.\n * @param state A `global-state`, `local-state`, `global-state-deltas` or `local-state-deltas`\n * @returns An object keyeed by the UTF-8 representation of the key with various parsings of the values\n */\n static decodeAppState(state) {\n const stateValues = {};\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = stateVal.key;\n const keyRaw = Buffer.from(keyBase64, 'base64');\n const key = keyRaw.toString('utf-8');\n const tealValue = stateVal.value;\n const dataTypeFlag = 'action' in tealValue ? tealValue.action : tealValue.type;\n let valueBase64;\n let valueRaw;\n switch (dataTypeFlag) {\n case 1:\n valueBase64 = tealValue.bytes ?? '';\n valueRaw = Buffer.from(valueBase64, 'base64');\n stateValues[key] = {\n keyRaw,\n keyBase64,\n valueRaw: new Uint8Array(valueRaw),\n valueBase64: valueBase64,\n value: valueRaw.toString('utf-8'),\n };\n break;\n case 2: {\n const value = tealValue.uint ?? 0;\n stateValues[key] = {\n keyRaw,\n keyBase64,\n value: BigInt(value),\n };\n break;\n }\n default:\n throw new Error(`Received unknown state data type of ${dataTypeFlag}`);\n }\n }\n return stateValues;\n }\n /**\n * Returns any ABI return values for the given app call arguments and transaction confirmation.\n * @param confirmation The transaction confirmation from algod\n * @param method The ABI method\n * @returns The return value for the method call\n */\n static getABIReturn(confirmation, method) {\n if (!method || !confirmation || method.returns.type === 'void') {\n return undefined;\n }\n // The parseMethodResponse method mutates the second parameter :(\n const resultDummy = {\n txID: '',\n method,\n rawReturnValue: new Uint8Array(),\n };\n return getABIReturnValue(algosdk.AtomicTransactionComposer.parseMethodResponse(method, resultDummy, confirmation));\n }\n /**\n * Replaces AlgoKit deploy-time deployment control parameters within the given TEAL template code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are defined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealTemplateCode The TEAL template code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n */\n static replaceTealTemplateDeployTimeControlParams(tealTemplateCode, params) {\n if (params.updatable !== undefined) {\n if (!tealTemplateCode.includes(UPDATABLE_TEMPLATE_NAME)) {\n throw new Error(`Deploy-time updatability control requested for app deployment, but ${UPDATABLE_TEMPLATE_NAME} not present in TEAL code`);\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString());\n }\n if (params.deletable !== undefined) {\n if (!tealTemplateCode.includes(DELETABLE_TEMPLATE_NAME)) {\n throw new Error(`Deploy-time deletability control requested for app deployment, but ${DELETABLE_TEMPLATE_NAME} not present in TEAL code`);\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString());\n }\n return tealTemplateCode;\n }\n /**\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealTemplateCode The TEAL template code to make parameter replacements in\n * @param templateParams Any parameters to replace in the teal code\n * @returns The TEAL code with replacements\n */\n static replaceTealTemplateParams(tealTemplateCode, templateParams) {\n if (templateParams !== undefined) {\n for (const key in templateParams) {\n const value = templateParams[key];\n const token = `TMPL_${key.replace(/^TMPL_/, '')}`;\n // If this is a number, first replace any byte representations of the number\n // These may appear in the TEAL in order to circumvent int compression and preserve PC values\n if (typeof value === 'number' || typeof value === 'bigint') {\n tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`);\n // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, token, typeof value === 'string'\n ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`\n : ArrayBuffer.isView(value)\n ? `0x${Buffer.from(value).toString('hex')}`\n : value.toString());\n }\n }\n return tealTemplateCode;\n }\n /**\n * Remove comments from TEAL code (useful to reduce code size before compilation).\n *\n * @param tealCode The TEAL logic to strip\n * @returns The TEAL without comments\n */\n static stripTealComments(tealCode) {\n const stripCommentFromLine = (line) => {\n const commentIndex = findUnquotedString(line, '//');\n if (commentIndex === undefined) {\n return line;\n }\n return line.slice(0, commentIndex).trimEnd();\n };\n return tealCode\n .split('\\n')\n .map((line) => stripCommentFromLine(line))\n .join('\\n');\n }\n}\n/**\n * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.\n * Returns undefined if not found\n */\nconst findUnquotedString = (line, token, startIndex = 0, _endIndex) => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex;\n let index = startIndex;\n let inQuotes = false;\n let inBase64 = false;\n while (index < endIndex) {\n const currentChar = line[index];\n if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {\n // enter base64\n inBase64 = true;\n }\n else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {\n // exit base64\n inBase64 = false;\n }\n else if (currentChar === '\\\\' && inQuotes) {\n // escaped char, skip next character\n index += 1;\n }\n else if (currentChar === '\"') {\n // quote boundary\n inQuotes = !inQuotes;\n }\n else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {\n // can test for match\n return index;\n }\n index += 1;\n }\n return undefined;\n};\nconst lastTokenBase64 = (line, index) => {\n try {\n const tokens = line.slice(0, index).split(/\\s+/);\n const last = tokens[tokens.length - 1];\n return ['base64', 'b64'].includes(last);\n }\n catch {\n return false;\n }\n};\nfunction replaceTemplateVariable(program, token, replacement) {\n const result = [];\n const tokenIndexOffset = replacement.length - token.length;\n const programLines = program.split('\\n');\n for (const line of programLines) {\n const _commentIndex = findUnquotedString(line, '//');\n const commentIndex = _commentIndex === undefined ? line.length : _commentIndex;\n let code = line.substring(0, commentIndex);\n const comment = line.substring(commentIndex);\n let trailingIndex = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const tokenIndex = findTemplateToken(code, token, trailingIndex);\n if (tokenIndex === undefined) {\n break;\n }\n trailingIndex = tokenIndex + token.length;\n const prefix = code.substring(0, tokenIndex);\n const suffix = code.substring(trailingIndex);\n code = `${prefix}${replacement}${suffix}`;\n trailingIndex += tokenIndexOffset;\n }\n result.push(code + comment);\n }\n return result.join('\\n');\n}\nconst findTemplateToken = (line, token, startIndex = 0, _endIndex) => {\n const endIndex = line.length ;\n let index = startIndex;\n while (index < endIndex) {\n const tokenIndex = findUnquotedString(line, token, index, endIndex);\n if (tokenIndex === undefined) {\n break;\n }\n const trailingIndex = tokenIndex + token.length;\n if ((tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&\n (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))) {\n return tokenIndex;\n }\n index = trailingIndex;\n }\n return undefined;\n};\nfunction isValidTokenCharacter(char) {\n return char.length === 1 && (/\\w/.test(char) || char === '_');\n}\n\nexport { AppManager };\n//# sourceMappingURL=app-manager.mjs.map\n","const DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT = 1000; //MaxAPIResourcesPerAccount: This is the default maximum, though may be provider specific\n/**\n * Looks up a transaction by ID using Indexer.\n * @param transactionId The ID of the transaction to look up\n * @param indexer An indexer client\n * @returns The result of the look-up\n */\nasync function lookupTransactionById(transactionId, indexer) {\n return (await indexer.lookupTransactionByID(transactionId).do());\n}\n/**\n * Looks up an account by address using Indexer.\n * @param accountAddress The address of the account to look up\n * @param indexer An indexer client\n * @returns The result of the look-up\n */\nasync function lookupAccountByAddress(accountAddress, indexer) {\n return (await indexer.lookupAccountByID(accountAddress).do());\n}\n/**\n * Looks up applications that were created by the given address; will automatically paginate through all data.\n * @param indexer An indexer instance\n * @param address The address of the creator to look up\n * @param getAll Whether or not to include deleted applications\n * @param paginationLimit The number of records to return per paginated request, default 1000\n * @returns The list of application results\n */\nasync function lookupAccountCreatedApplicationByAddress(indexer, address, getAll = undefined, paginationLimit) {\n return await executePaginatedRequest((response) => {\n if ('message' in response) {\n throw { status: 404, ...response };\n }\n return response.applications;\n }, (nextToken) => {\n let s = indexer\n .lookupAccountCreatedApplications(address)\n .includeAll(getAll)\n .limit(paginationLimit ?? DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT);\n if (nextToken) {\n s = s.nextToken(nextToken);\n }\n return s;\n });\n}\n/**\n * Looks up asset holdings for the given asset; will automatically paginate through all data.\n * @param indexer An indexer instance\n * @param assetId The ID of the asset to look up holdings for\n * @param options Optional options to control the lookup\n * @param paginationLimit The number of records to return per paginated request, default 1000\n * @returns The list of application results\n */\nasync function lookupAssetHoldings(indexer, assetId, options, paginationLimit) {\n return await executePaginatedRequest((response) => {\n if ('message' in response) {\n throw { status: 404, ...response };\n }\n return response.balances;\n }, (nextToken) => {\n let s = indexer.lookupAssetBalances(Number(assetId)).limit(paginationLimit ?? DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT);\n if (options?.currencyGreaterThan !== undefined) {\n s = s.currencyGreaterThan(options.currencyGreaterThan);\n }\n if (options?.currencyLessThan !== undefined) {\n s = s.currencyLessThan(options.currencyLessThan);\n }\n if (options?.includeAll !== undefined) {\n s = s.includeAll(options.includeAll);\n }\n if (nextToken) {\n s = s.nextToken(nextToken);\n }\n return s;\n });\n}\n/**\n * Allows transactions to be searched for the given criteria.\n * @param indexer An indexer client\n * @param searchCriteria The criteria to search for\n * @param paginationLimit The number of records to return per paginated request, default 1000\n * @returns The search results\n */\nasync function searchTransactions(indexer, searchCriteria, paginationLimit) {\n let currentRound = 0;\n const transactions = await executePaginatedRequest((response) => {\n if ('message' in response) {\n throw { status: 404, ...response };\n }\n if (response['current-round'] > currentRound) {\n currentRound = response['current-round'];\n }\n return response.transactions;\n }, (nextToken) => {\n let s = searchCriteria(indexer.searchForTransactions()).limit(paginationLimit ?? DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT);\n if (nextToken) {\n s = s.nextToken(nextToken);\n }\n return s;\n });\n return {\n 'current-round': currentRound,\n 'next-token': '',\n transactions: transactions,\n };\n}\n// https://developer.algorand.org/docs/get-details/indexer/#paginated-results\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function executePaginatedRequest(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nextractItems, buildRequest) {\n const results = [];\n let nextToken = undefined;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const request = buildRequest(nextToken);\n const response = await request.do();\n const items = extractItems(response);\n if (items == null || items.length === 0) {\n break;\n }\n results.push(...items);\n nextToken = response['next-token'];\n if (!nextToken) {\n break;\n }\n }\n return results;\n}\n\nexport { executePaginatedRequest, lookupAccountByAddress, lookupAccountCreatedApplicationByAddress, lookupAssetHoldings, lookupTransactionById, searchTransactions };\n//# sourceMappingURL=indexer-lookup.mjs.map\n","import algosdk from 'algosdk';\nimport { Config } from '../config.mjs';\nimport { lookupAccountCreatedApplicationByAddress, searchTransactions } from '../indexer-lookup.mjs';\nimport { APP_DEPLOY_NOTE_DAPP, OnSchemaBreak, OnUpdate } from './app.mjs';\nimport { TransactionComposer } from './composer.mjs';\n\n/** Allows management of deployment and deployment metadata of applications. */\nclass AppDeployer {\n /**\n * Creates an `AppManager`\n * @param appManager An `AppManager` instance\n * @param transactionSender An `AlgorandClientTransactionSender` instance\n * @param indexer An optional indexer instance; supply if you want to indexer to look up app metadata\n */\n constructor(appManager, transactionSender, indexer) {\n this._appLookups = new Map();\n this._appManager = appManager;\n this._transactionSender = transactionSender;\n this._indexer = indexer;\n }\n /**\n * Idempotently deploy (create if not exists, update if changed) an app against the given name for the given creator account, including deploy-time TEAL template placeholder substitutions (if specified).\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deployment The arguments to control the app deployment\n * @returns The app reference of the new/existing app\n */\n async deploy(deployment) {\n const { metadata, deployTimeParams, onSchemaBreak, onUpdate, createParams, updateParams, deleteParams, existingDeployments, ignoreCache, ...sendParams } = deployment;\n // Set creation note\n createParams.note = updateParams.note = TransactionComposer.arc2Note({\n dAppName: APP_DEPLOY_NOTE_DAPP,\n data: metadata,\n format: 'j',\n });\n // Check for required fields\n if (existingDeployments && existingDeployments.creator !== createParams.sender) {\n throw new Error(`Received invalid existingDeployments value for creator ${existingDeployments.creator} when attempting to deploy for creator ${createParams.sender}`);\n }\n if (!existingDeployments && !this._indexer) {\n throw new Error(`Didn't receive an indexer client when this AppManager was created, but also didn't receive an existingDeployments cache - one of them must be provided`);\n }\n Config.getLogger(sendParams?.suppressLog).info(`Idempotently deploying app \"${metadata.name}\" from creator ${createParams.sender} using ${createParams.approvalProgram.length} bytes of ${typeof createParams.approvalProgram === 'string' ? 'teal code' : 'AVM bytecode'} and ${createParams.clearStateProgram.length} bytes of ${typeof createParams.approvalProgram === 'string' ? 'teal code' : 'AVM bytecode'}`);\n // Compile code if required\n const compiledApproval = typeof createParams.approvalProgram === 'string'\n ? await this._appManager.compileTealTemplate(createParams.approvalProgram, deployTimeParams, metadata)\n : undefined;\n const approvalProgram = compiledApproval ? compiledApproval.compiledBase64ToBytes : createParams.approvalProgram;\n const compiledClear = typeof createParams.clearStateProgram === 'string'\n ? await this._appManager.compileTealTemplate(createParams.clearStateProgram, deployTimeParams)\n : undefined;\n const clearStateProgram = compiledClear ? compiledClear.compiledBase64ToBytes : createParams.clearStateProgram;\n // Define routines for create, update, and replace\n const createApp = async () => {\n const result = await ('method' in createParams\n ? this._transactionSender.appCreateMethodCall({ ...createParams, approvalProgram, clearStateProgram, ...sendParams })\n : this._transactionSender.appCreate({ ...createParams, approvalProgram, clearStateProgram, ...sendParams }));\n const appMetadata = {\n appId: result.appId,\n appAddress: result.appAddress,\n ...metadata,\n createdMetadata: metadata,\n createdRound: BigInt(result.confirmation.confirmedRound),\n updatedRound: BigInt(result.confirmation.confirmedRound),\n deleted: false,\n };\n this.updateAppLookup(createParams.sender, appMetadata);\n return {\n operationPerformed: 'create',\n compiledApproval,\n compiledClear,\n ...result,\n ...appMetadata,\n };\n };\n const updateApp = async (existingApp) => {\n Config.getLogger(sendParams?.suppressLog).info(`Updating existing ${metadata.name} app for ${createParams.sender} to version ${metadata.version}.`);\n const result = await ('method' in updateParams\n ? this._transactionSender.appUpdateMethodCall({\n appId: existingApp.appId,\n approvalProgram,\n clearStateProgram,\n ...updateParams,\n ...sendParams,\n })\n : this._transactionSender.appUpdate({\n appId: existingApp.appId,\n approvalProgram,\n clearStateProgram,\n ...updateParams,\n ...sendParams,\n }));\n const appMetadata = {\n appId: existingApp.appId,\n appAddress: existingApp.appAddress,\n createdMetadata: existingApp.createdMetadata,\n createdRound: existingApp.createdRound,\n updatedRound: BigInt(result.confirmation.confirmedRound),\n ...metadata,\n deleted: false,\n };\n this.updateAppLookup(createParams.sender, appMetadata);\n return {\n operationPerformed: 'update',\n compiledApproval,\n compiledClear,\n ...result,\n ...appMetadata,\n };\n };\n const replaceApp = async (existingApp) => {\n Config.getLogger(sendParams?.suppressLog).info(`Deploying a new ${metadata.name} app for ${createParams.sender}; deploying app with version ${metadata.version}.`);\n Config.getLogger(sendParams?.suppressLog).warn(`Deleting existing ${metadata.name} app with id ${existingApp.appId} from ${deleteParams.sender} account.`);\n const composer = this._transactionSender.newGroup();\n if ('method' in createParams) {\n composer.addAppCreateMethodCall({ ...createParams, approvalProgram, clearStateProgram });\n }\n else {\n composer.addAppCreate({ ...createParams, approvalProgram, clearStateProgram });\n }\n const createIndex = await composer.count();\n if ('method' in deleteParams) {\n composer.addAppDeleteMethodCall({ appId: existingApp.appId, ...deleteParams });\n }\n else {\n composer.addAppDelete({ appId: existingApp.appId, ...deleteParams });\n }\n const result = await composer.send({ ...sendParams, suppressLog: true });\n const confirmation = result.confirmations.at(createIndex - 1);\n const transaction = result.transactions.at(createIndex - 1);\n const deleteTransaction = result.transactions.at(-1);\n Config.getLogger(sendParams?.suppressLog).warn(`Sent transactions ${transaction.txID()} to create app with id ${confirmation.applicationIndex} and ${deleteTransaction.txID()} to delete app with id ${existingApp.appId} from ${createParams.sender} account.`);\n const appMetadata = {\n appId: BigInt(confirmation.applicationIndex),\n appAddress: algosdk.getApplicationAddress(confirmation.applicationIndex),\n ...metadata,\n createdMetadata: metadata,\n createdRound: BigInt(confirmation.confirmedRound),\n updatedRound: BigInt(confirmation.confirmedRound),\n deleted: false,\n };\n this.updateAppLookup(createParams.sender, appMetadata);\n return {\n operationPerformed: 'replace',\n ...result,\n compiledApproval,\n compiledClear,\n transaction,\n confirmation,\n return: 'method' in createParams ? result.returns?.[0] : undefined,\n deleteReturn: 'method' in deleteParams ? result.returns?.at(-1) : undefined,\n ...appMetadata,\n deleteResult: { transaction: deleteTransaction, confirmation: result.confirmations.at(-1) },\n };\n };\n // Lookup existing app metadata\n const apps = existingDeployments ?? (await this.getCreatorAppsByName(createParams.sender, ignoreCache));\n const existingApp = apps.apps[metadata.name];\n if (!existingApp || existingApp.deleted) {\n Config.getLogger(sendParams?.suppressLog).info(`App ${metadata.name} not found in apps created by ${createParams.sender}; deploying app with version ${metadata.version}.`);\n return await createApp();\n }\n Config.getLogger(sendParams?.suppressLog).info(`Existing app ${metadata.name} found by creator ${createParams.sender}, with app id ${existingApp.appId} and version ${existingApp.version}.`);\n const existingAppRecord = await this._appManager.getById(existingApp.appId);\n const existingApproval = Buffer.from(existingAppRecord.approvalProgram).toString('base64');\n const existingClear = Buffer.from(existingAppRecord.clearStateProgram).toString('base64');\n const newApproval = Buffer.from(approvalProgram).toString('base64');\n const newClear = Buffer.from(clearStateProgram).toString('base64');\n // Check for changes\n const isUpdate = newApproval !== existingApproval || newClear !== existingClear;\n const isSchemaBreak = existingAppRecord.localInts < (createParams.schema?.localInts ?? 0) ||\n existingAppRecord.globalInts < (createParams.schema?.globalInts ?? 0) ||\n existingAppRecord.localByteSlices < (createParams.schema?.localByteSlices ?? 0) ||\n existingAppRecord.globalByteSlices < (createParams.schema?.globalByteSlices ?? 0);\n if (isSchemaBreak) {\n Config.getLogger(sendParams?.suppressLog).warn(`Detected a breaking app schema change in app ${existingApp.appId}:`, {\n from: {\n globalInts: existingAppRecord.globalInts,\n globalByteSlices: existingAppRecord.globalByteSlices,\n localInts: existingAppRecord.localInts,\n localByteSlices: existingAppRecord.localByteSlices,\n },\n to: createParams.schema,\n });\n if (onSchemaBreak === undefined || onSchemaBreak === 'fail' || onSchemaBreak === OnSchemaBreak.Fail) {\n throw new Error('Schema break detected and onSchemaBreak=OnSchemaBreak.Fail, stopping deployment. ' +\n 'If you want to try deleting and recreating the app then ' +\n 're-run with onSchemaBreak=OnSchemaBreak.ReplaceApp');\n }\n if (onSchemaBreak === 'append' || onSchemaBreak === OnSchemaBreak.AppendApp) {\n Config.getLogger(sendParams?.suppressLog).info('onSchemaBreak=AppendApp, will attempt to create a new app');\n return await createApp();\n }\n if (existingApp.deletable) {\n Config.getLogger(sendParams?.suppressLog).info('App is deletable and onSchemaBreak=ReplaceApp, will attempt to create new app and delete old app');\n }\n else {\n Config.getLogger(sendParams?.suppressLog).info('App is not deletable but onSchemaBreak=ReplaceApp, will attempt to delete app, delete will most likely fail');\n }\n return await replaceApp(existingApp);\n }\n if (isUpdate) {\n Config.getLogger(sendParams?.suppressLog).info(`Detected a TEAL update in app ${existingApp.appId} for creator ${createParams.sender}`);\n if (onUpdate === undefined || onUpdate === 'fail' || onUpdate === OnUpdate.Fail) {\n throw new Error('Update detected and onUpdate=Fail, stopping deployment. Try a different onUpdate value to not fail.');\n }\n if (onUpdate === 'append' || onUpdate === OnUpdate.AppendApp) {\n Config.getLogger(sendParams?.suppressLog).info('onUpdate=AppendApp, will attempt to create a new app');\n return await createApp();\n }\n if (onUpdate === 'update' || onUpdate === OnUpdate.UpdateApp) {\n if (existingApp.updatable) {\n Config.getLogger(sendParams?.suppressLog).info(`App is updatable and onUpdate=UpdateApp, updating app...`);\n }\n else {\n Config.getLogger(sendParams?.suppressLog).warn(`App is not updatable but onUpdate=UpdateApp, will attempt to update app, update will most likely fail`);\n }\n return await updateApp(existingApp);\n }\n if (onUpdate === 'replace' || onUpdate === OnUpdate.ReplaceApp) {\n if (existingApp.deletable) {\n Config.getLogger(sendParams?.suppressLog).warn('App is deletable and onUpdate=ReplaceApp, creating new app and deleting old app...');\n }\n else {\n Config.getLogger(sendParams?.suppressLog).warn('App is not deletable and onUpdate=ReplaceApp, will attempt to create new app and delete old app, delete will most likely fail');\n }\n return await replaceApp(existingApp);\n }\n }\n Config.getLogger(sendParams?.suppressLog).debug('No detected changes in app, nothing to do.');\n return { ...existingApp, operationPerformed: 'nothing' };\n }\n updateAppLookup(sender, appMetadata) {\n const lookup = this._appLookups.get(sender);\n if (!lookup) {\n this._appLookups.set(sender, { creator: sender, apps: { [appMetadata.name]: appMetadata } });\n }\n else {\n lookup.apps[appMetadata.name] = appMetadata;\n }\n }\n /**\n * Returns a lookup of name => app metadata (id, address, ...metadata) for all apps created by the given account that have\n * an [ARC-2](https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md) `AppDeployNote` as the transaction\n * note of the app creation transaction.\n *\n * This function caches the result for the given creator account so that subsequent calls will not require an indexer lookup.\n *\n * If the `AppManager` instance wasn't created with an indexer client, this function will throw an error.\n *\n * @param creatorAddress The address of the account that is the creator of the apps you want to search for\n * @param ignoreCache Whether or not to ignore the cache and force a lookup, default: use the cache\n * @returns A name-based lookup of the app metadata\n */\n async getCreatorAppsByName(creatorAddress, ignoreCache) {\n const appLookup = {};\n if (!ignoreCache && this._appLookups.has(creatorAddress)) {\n return this._appLookups.get(creatorAddress);\n }\n if (!this._indexer) {\n throw new Error(`Didn't receive an indexer client when this AppManager was created, but received a call to getCreatorApps`);\n }\n // Extract all apps that account created\n const createdApps = (await lookupAccountCreatedApplicationByAddress(this._indexer, creatorAddress))\n .map((a) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return { id: BigInt(a.id), createdAtRound: a['created-at-round'], deleted: a.deleted };\n })\n .sort((a, b) => a.createdAtRound - b.createdAtRound);\n // For each app that account created (in parallel)...\n const apps = await Promise.all(createdApps.map(async (createdApp) => {\n // Find any app transactions for that app in the round it was created (should always just be a single creation transaction)\n const appTransactions = await searchTransactions(this._indexer, (s) => s\n .minRound(createdApp.createdAtRound)\n .txType(algosdk.TransactionType.appl)\n .applicationID(Number(createdApp.id))\n .address(creatorAddress)\n .addressRole('sender')\n .notePrefix(Buffer.from(APP_DEPLOY_NOTE_DAPP).toString('base64')));\n // Triple check the transaction is intact by filtering for the one we want:\n // * application-id is 0 when the app is first created\n // * also verify the sender to prevent a potential security risk\n const appCreationTransaction = appTransactions.transactions.filter(\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (t) => t['application-transaction']['application-id'] === 0 && t.sender === creatorAddress)[0];\n const latestAppUpdateTransaction = appTransactions.transactions\n .filter((t) => t.sender === creatorAddress)\n .sort((a, b) => a['confirmed-round'] === b['confirmed-round']\n ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (b['intra-round-offset'] - a['intra-round-offset']) / 10\n : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n b['confirmed-round'] - a['confirmed-round'])[0];\n if (!appCreationTransaction?.note)\n // No note; ignoring\n return null;\n return { createdApp, appCreationTransaction, latestAppUpdateTransaction };\n }));\n apps\n .filter((a) => a !== null)\n .forEach((a) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { createdApp, appCreationTransaction, latestAppUpdateTransaction } = a;\n const parseNote = (note) => {\n if (!note) {\n // No note; ignoring...\n return;\n }\n const decoder = new TextDecoder();\n const noteAsBase64 = decoder.decode(Buffer.from(note));\n const noteAsString = Buffer.from(noteAsBase64, 'base64').toString('utf-8');\n if (!noteAsString.startsWith(`${APP_DEPLOY_NOTE_DAPP}:j{`))\n // Clearly not APP_DEPLOY JSON; ignoring...\n return;\n return JSON.parse(noteAsString.substring(APP_DEPLOY_NOTE_DAPP.length + 2));\n };\n try {\n const creationNote = parseNote(appCreationTransaction.note);\n const updateNote = parseNote(latestAppUpdateTransaction.note);\n if (creationNote?.name) {\n appLookup[creationNote.name] = {\n appId: createdApp.id,\n appAddress: algosdk.getApplicationAddress(createdApp.id),\n createdMetadata: creationNote,\n createdRound: BigInt(appCreationTransaction['confirmed-round'] ?? 0),\n ...(updateNote ?? creationNote),\n updatedRound: BigInt(latestAppUpdateTransaction?.['confirmed-round'] ?? 0),\n deleted: createdApp.deleted ?? false,\n };\n }\n }\n catch (e) {\n Config.logger.warn(`Received error trying to retrieve app with ${createdApp.id} for creator ${creatorAddress}; failing silently`, e);\n return;\n }\n });\n const lookup = {\n creator: creatorAddress,\n apps: appLookup,\n };\n this._appLookups.set(creatorAddress, lookup);\n return lookup;\n }\n}\n\nexport { AppDeployer };\n//# sourceMappingURL=app-deployer.mjs.map\n","/**\n * Returns true if the given network genesisId is associated with a LocalNet network.\n * @param genesisId The network genesis ID\n * @returns Whether the given genesis ID is associated with a LocalNet network\n */\nfunction genesisIdIsLocalNet(genesisId) {\n return genesisId === 'devnet-v1' || genesisId === 'sandnet-v1' || genesisId === 'dockernet-v1';\n}\n\nexport { genesisIdIsLocalNet };\n//# sourceMappingURL=network-client.mjs.map\n","import { ApplicationClient } from './types/app-client.mjs';\n\n/**\n * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientById` or\n * `algorand.client.getAppClientByCreatorAndName`.\n * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n *\n * Create a new ApplicationClient instance\n * @param appDetails The details of the app\n * @param algod An algod instance\n *\n * @example Resolve by creator and name\n * const client = algokit.getAppClient(\n * {\n * resolveBy: 'creatorAndName',\n * app: {appSpec},\n * sender: {account},\n * creatorAddress: {creator},\n * findExistingUsing: indexerClient,\n * },\n * algodClient,\n * )\n *\n * @example Resolve by id:\n * const client = algokit.getAppClient(\n * {\n * resolveBy: 'id',\n * app: {appSpec},\n * sender: {account},\n * id: {id},\n * },\n * algodClient,\n * )\n *\n * @returns The application client\n */\nfunction getAppClient(appDetails, algod) {\n return new ApplicationClient(appDetails, algod);\n}\n/**\n * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientById`.\n * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n *\n *\n * Create a new ApplicationClient instance by id\n * @param appDetails The details of the app\n * @param algod An algod instance\n *\n * @example\n * const client = algokit.getAppClientById(\n * {\n * app: {appSpec},\n * sender: {account},\n * id: {id},\n * },\n * algodClient,\n * )\n *\n * @returns The application client\n */\nfunction getAppClientById(appDetails, algod) {\n return new ApplicationClient({ ...appDetails, resolveBy: 'id' }, algod);\n}\n/**\n * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientByCreatorAndName`.\n * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n *\n *\n * Create a new ApplicationClient instance by creator and name\n * @param appDetails The details of the app by creator and name\n * @param algod An algod instance\n *\n * @example\n * const client = algokit.getAppClientByCreatorAndName(\n * {\n * app: {appSpec},\n * sender: {account},\n * creatorAddress: {account.addr},\n * findExistingUsing: {indexerClient},\n * },\n * algodClient,\n * )\n *\n * @returns The application client\n */\nfunction getAppClientByCreatorAndName(appDetails, algod) {\n return new ApplicationClient({ ...appDetails, resolveBy: 'creatorAndName' }, algod);\n}\n\nexport { getAppClient, getAppClientByCreatorAndName, getAppClientById };\n//# sourceMappingURL=app-client.mjs.map\n","import algosdk from 'algosdk';\n\n/**\n * The account name identifier used for fund dispensing in test environments\n */\nconst DISPENSER_ACCOUNT = 'DISPENSER';\n/** Account wrapper that supports partial or full multisig signing. */\nclass MultisigAccount {\n /** The parameters for the multisig account */\n get params() {\n return this._params;\n }\n /** The list of accounts that are present to sign */\n get signingAccounts() {\n return this._signingAccounts;\n }\n /** The address of the multisig account */\n get addr() {\n return this._addr;\n }\n get signer() {\n return this._signer;\n }\n constructor(multisigParams, signingAccounts) {\n this._params = multisigParams;\n this._signingAccounts = signingAccounts;\n this._addr = algosdk.multisigAddress(multisigParams);\n this._signer = algosdk.makeMultiSigAccountTransactionSigner(multisigParams, signingAccounts.map((a) => a.sk));\n }\n /**\n * Sign the given transaction\n * @param transaction Either a transaction object or a raw, partially signed transaction\n * @returns The transaction signed by the present signers\n */\n sign(transaction) {\n let signedTxn = 'from' in transaction ? undefined : transaction;\n for (const signer of this._signingAccounts) {\n if (signedTxn) {\n signedTxn = algosdk.appendSignMultisigTransaction(signedTxn, this._params, signer.sk).blob;\n }\n else {\n signedTxn = algosdk.signMultisigTransaction(transaction, this._params, signer.sk).blob;\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return signedTxn;\n }\n}\n/** Account wrapper that supports a rekeyed account */\nclass SigningAccount {\n /**\n * Algorand address of the sender\n */\n get addr() {\n return this._sender;\n }\n /**\n * Secret key belonging to the signer\n */\n get sk() {\n return this._account.sk;\n }\n /**\n * Transaction signer for the underlying signing account\n */\n get signer() {\n return this._signer;\n }\n /**\n * Algorand account of the sender address and signer private key\n */\n get sender() {\n return {\n addr: this._sender,\n sk: this._account.sk,\n };\n }\n constructor(account, sender) {\n this._account = account;\n this._sender = sender ?? account.addr;\n this._signer = algosdk.makeBasicAccountTransactionSigner(account);\n }\n}\n\nexport { DISPENSER_ACCOUNT, MultisigAccount, SigningAccount };\n//# sourceMappingURL=account.mjs.map\n","import { Buffer } from 'buffer';\n\nclass URLTokenBaseHTTPError extends Error {\n constructor(message, response) {\n super(message);\n this.response = response;\n this.name = 'URLTokenBaseHTTPError';\n this.response = response;\n }\n}\n/**\n * Implementation of BaseHTTPClient that uses a URL and a token\n * and make the REST queries using fetch.\n * This is the default implementation of BaseHTTPClient.\n */\nclass URLTokenBaseHTTPClient {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(tokenHeader, baseServer, port, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n defaultHeaders = {}) {\n this.defaultHeaders = defaultHeaders;\n // Append a trailing slash so we can use relative paths. Without the trailing\n // slash, the last path segment will be replaced by the relative path. See\n // usage in `addressWithPath`.\n const fixedBaseServer = baseServer.endsWith('/') ? baseServer : `${baseServer}/`;\n const baseServerURL = new URL(fixedBaseServer);\n if (typeof port !== 'undefined') {\n baseServerURL.port = port.toString();\n }\n if (baseServerURL.protocol.length === 0) {\n throw new Error('Invalid base server URL, protocol must be defined.');\n }\n this.baseURL = baseServerURL;\n this.tokenHeader = tokenHeader;\n }\n /**\n * Compute the URL for a path relative to the instance's address\n * @param relativePath - A path string\n * @param query - An optional key-value object of query parameters to add to the URL. If the\n * relativePath already has query parameters on it, the additional parameters defined here will\n * be added to the URL without modifying those (unless a key collision occurs).\n * @returns A URL string\n */\n getURL(relativePath, query) {\n let fixedRelativePath;\n if (relativePath.startsWith('./')) {\n fixedRelativePath = relativePath;\n }\n else if (relativePath.startsWith('/')) {\n fixedRelativePath = `.${relativePath}`;\n }\n else {\n fixedRelativePath = `./${relativePath}`;\n }\n const address = new URL(fixedRelativePath, this.baseURL);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n address.searchParams.set(key, value);\n }\n }\n return address.toString();\n }\n static formatFetchResponseHeaders(headers) {\n const headersObj = {};\n headers.forEach((key, value) => {\n headersObj[key] = value;\n });\n return headersObj;\n }\n static async checkHttpError(res) {\n if (res.ok) {\n return;\n }\n let body = null;\n let bodyErrorMessage = null;\n try {\n body = new Uint8Array(await res.arrayBuffer());\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const decoded = JSON.parse(Buffer.from(body).toString());\n if (decoded.message) {\n bodyErrorMessage = decoded.message;\n }\n }\n catch {\n // ignore any error that happened while we are parsing the error response\n }\n let message = `Network request error. Received status ${res.status} (${res.statusText})`;\n if (bodyErrorMessage) {\n message += `: ${bodyErrorMessage}`;\n }\n throw new URLTokenBaseHTTPError(message, {\n body: body !== null ? body : new Uint8Array(),\n status: res.status,\n headers: URLTokenBaseHTTPClient.formatFetchResponseHeaders(res.headers),\n });\n }\n static async formatFetchResponse(res) {\n await this.checkHttpError(res);\n return {\n body: new Uint8Array(await res.arrayBuffer()),\n status: res.status,\n headers: URLTokenBaseHTTPClient.formatFetchResponseHeaders(res.headers),\n };\n }\n async get(relativePath, query, requestHeaders = {}) {\n // Expand headers for use in fetch\n const headers = {\n ...this.tokenHeader,\n ...this.defaultHeaders,\n ...requestHeaders,\n };\n const res = await fetch(this.getURL(relativePath, query), {\n mode: 'cors',\n headers,\n });\n return URLTokenBaseHTTPClient.formatFetchResponse(res);\n }\n async post(relativePath, data, query, requestHeaders = {}) {\n // Expand headers for use in fetch\n const headers = {\n ...this.tokenHeader,\n ...this.defaultHeaders,\n ...requestHeaders,\n };\n const res = await fetch(this.getURL(relativePath, query), {\n method: 'POST',\n mode: 'cors',\n body: data,\n headers,\n });\n return URLTokenBaseHTTPClient.formatFetchResponse(res);\n }\n async delete(relativePath, data, query, requestHeaders = {}) {\n // Expand headers for use in fetch\n const headers = {\n ...this.tokenHeader,\n ...this.defaultHeaders,\n ...requestHeaders,\n };\n const res = await fetch(this.getURL(relativePath, query), {\n method: 'DELETE',\n mode: 'cors',\n body: data,\n headers,\n });\n return URLTokenBaseHTTPClient.formatFetchResponse(res);\n }\n}\n\nexport { URLTokenBaseHTTPClient };\n//# sourceMappingURL=urlTokenBaseHTTPClient.mjs.map\n","import { Config } from '../config.mjs';\nimport { URLTokenBaseHTTPClient } from './urlTokenBaseHTTPClient.mjs';\n\n/** A HTTP Client that wraps the Algorand SDK HTTP Client with retries */\nclass AlgoHttpClientWithRetry extends URLTokenBaseHTTPClient {\n async callWithRetry(func) {\n let response;\n let numTries = 1;\n do {\n try {\n response = await func();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n catch (err) {\n if (numTries >= AlgoHttpClientWithRetry.MAX_TRIES) {\n throw err;\n }\n // Only retry for one of the hardcoded conditions\n if (!(AlgoHttpClientWithRetry.RETRY_ERROR_CODES.includes(err.code) ||\n AlgoHttpClientWithRetry.RETRY_STATUS_CODES.includes(Number(err.status)) ||\n ('response' in err && AlgoHttpClientWithRetry.RETRY_STATUS_CODES.includes(Number(err.response.status))))) {\n throw err;\n }\n // Retry immediately the first time, then exponentially backoff.\n const delayTimeMs = numTries == 1 ? 0 : Math.min(1000 * Math.pow(2, numTries - 1), AlgoHttpClientWithRetry.MAX_BACKOFF_MS);\n if (delayTimeMs > 0) {\n await new Promise((r) => setTimeout(r, delayTimeMs));\n }\n Config.logger.warn(`algosdk request failed ${numTries} times. Retrying in ${delayTimeMs}ms: ${err}`);\n }\n } while (!response && ++numTries <= AlgoHttpClientWithRetry.MAX_TRIES);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return response;\n }\n async get(relativePath, query, requestHeaders = {}) {\n return await this.callWithRetry(() => super.get(relativePath, query, requestHeaders));\n }\n async post(relativePath, data, query, requestHeaders = {}) {\n return await this.callWithRetry(() => super.post(relativePath, data, query, requestHeaders));\n }\n async delete(relativePath, data, query, requestHeaders = {}) {\n return await this.callWithRetry(() => super.delete(relativePath, data, query, requestHeaders));\n }\n}\nAlgoHttpClientWithRetry.MAX_TRIES = 5;\nAlgoHttpClientWithRetry.MAX_BACKOFF_MS = 10000;\n// These lists come from https://visionmedia.github.io/superagent/#retrying-requests\n// which is the underlying library used by algosdk - but the CloudFlare specific 52X status codes have been removed\nAlgoHttpClientWithRetry.RETRY_STATUS_CODES = [408, 413, 429, 500, 502, 503, 504];\nAlgoHttpClientWithRetry.RETRY_ERROR_CODES = [\n 'ETIMEDOUT',\n 'ECONNRESET',\n 'EADDRINUSE',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EAI_AGAIN',\n 'EPROTO', // We get this intermittently with AlgoNode API\n];\n\nexport { AlgoHttpClientWithRetry };\n//# sourceMappingURL=algo-http-client-with-retry.mjs.map\n","import { asJson } from '../util.mjs';\n\nconst DISPENSER_BASE_URL = 'https://api.dispenser.algorandfoundation.tools';\nconst DEFAULT_DISPENSER_REQUEST_TIMEOUT = 15;\nconst DISPENSER_ACCESS_TOKEN_KEY = 'ALGOKIT_DISPENSER_ACCESS_TOKEN';\nvar DispenserAssetName;\n(function (DispenserAssetName) {\n DispenserAssetName[DispenserAssetName[\"Algo\"] = 0] = \"Algo\";\n})(DispenserAssetName || (DispenserAssetName = {}));\nconst dispenserAssets = {\n [DispenserAssetName.Algo]: {\n assetId: 0,\n decimals: 6,\n description: 'Algo',\n },\n};\n/**\n * `TestNetDispenserApiClient` is a class that provides methods to interact with the [Algorand TestNet Dispenser API](https://github.com/algorandfoundation/algokit/blob/main/docs/testnet_api.md).\n * It allows you to fund an address with Algo, refund a transaction, and get the funding limit for the Algo asset.\n *\n * The class requires an authentication token and a request timeout to be initialized. The authentication token can be provided\n * either directly as a parameter or through an `ALGOKIT_DISPENSER_ACCESS_TOKEN` environment variable. If neither is provided, an error is thrown.\n *\n * The request timeout can be provided as a parameter. If not provided, a default value is used.\n *\n * @property {string} authToken - The authentication token used for API requests.\n * @property {number} requestTimeout - The timeout for API requests, in seconds.\n *\n * @method fund - Sends a funding request to the dispenser API to fund the specified address with the given amount of Algo.\n * @method refund - Sends a refund request to the dispenser API for the specified refundTxnId.\n * @method limit - Sends a request to the dispenser API to get the funding limit for the Algo asset.\n *\n * @example\n * ```typescript\n * const client = new TestNetDispenserApiClient({ authToken: 'your_auth_token', requestTimeout: 30 });\n * const fundResponse = await client.fund('your_address', 100);\n * const limitResponse = await client.getLimit();\n * await client.refund('your_transaction_id');\n * ```\n *\n * @throws {Error} If neither the environment variable 'ALGOKIT_DISPENSER_ACCESS_TOKEN' nor the authToken parameter were provided.\n */\nclass TestNetDispenserApiClient {\n constructor(params) {\n const authTokenFromEnv = process?.env?.[DISPENSER_ACCESS_TOKEN_KEY];\n if (params?.authToken) {\n this._authToken = params.authToken;\n }\n else if (authTokenFromEnv) {\n this._authToken = authTokenFromEnv;\n }\n else {\n throw new Error(`Can't init AlgoKit TestNet Dispenser API client because neither environment variable ${DISPENSER_ACCESS_TOKEN_KEY} or the authToken were provided.`);\n }\n this._requestTimeout = params?.requestTimeout || DEFAULT_DISPENSER_REQUEST_TIMEOUT;\n }\n get authToken() {\n return this._authToken;\n }\n get requestTimeout() {\n return this._requestTimeout;\n }\n /**\n * Processes a dispenser API request.\n *\n * @param authToken - The authentication token.\n * @param urlSuffix - The URL suffix for the API request.\n * @param body - The request body.\n * @param method - The HTTP method.\n *\n * @returns The API response.\n */\n async processDispenserRequest(authToken, urlSuffix, body = null, method = 'POST') {\n const headers = { Authorization: `Bearer ${authToken}` };\n const requestArgs = {\n method: method,\n headers: headers,\n signal: AbortSignal.timeout(this.requestTimeout * 1000),\n };\n if (body) {\n requestArgs.body = asJson(body);\n }\n const response = await fetch(`${DISPENSER_BASE_URL}/${urlSuffix}`, requestArgs);\n if (!response.ok) {\n let error_message = `Error processing dispenser API request: ${response.status}`;\n let error_response = null;\n try {\n error_response = await response.json();\n }\n catch {\n // suppress exception\n }\n if (error_response && error_response.code) {\n error_message = error_response.code;\n }\n else if (response.status === 400) {\n const errorResponse = (await response.json());\n error_message = errorResponse.message;\n }\n throw new Error(error_message);\n }\n return response;\n }\n /**\n * Sends a funding request to the dispenser API to fund the specified address with the given amount of Algo.\n *\n * @param address - The address to fund.\n * @param amount - The amount of µAlgo to fund.\n *\n * @returns DispenserFundResponse: An object containing the transaction ID and funded amount.\n */\n async fund(address, amount) {\n const response = await this.processDispenserRequest(this.authToken, `fund/${dispenserAssets[DispenserAssetName.Algo].assetId}`, { receiver: address, amount: Number(amount), assetID: dispenserAssets[DispenserAssetName.Algo].assetId }, 'POST');\n const content = (await response.json());\n return { txId: content.txID, amount: content.amount };\n }\n /**\n * Sends a refund request to the dispenser API for the specified refundTxnId.\n *\n * @param refundTxnId - The transaction ID to refund.\n */\n async refund(refundTxnId) {\n await this.processDispenserRequest(this.authToken, 'refund', { refundTransactionID: refundTxnId }, 'POST');\n }\n /**\n * Sends a request to the dispenser API to get the funding limit for the Algo asset.\n *\n * @returns DispenserLimitResponse: An object containing the funding limit amount.\n */\n async getLimit() {\n const response = await this.processDispenserRequest(this.authToken, `fund/${dispenserAssets[DispenserAssetName.Algo].assetId}/limit`, null, 'GET');\n const content = (await response.json());\n return { amount: content.amount };\n }\n}\n\nexport { TestNetDispenserApiClient };\n//# sourceMappingURL=dispenser-client.mjs.map\n","import algosdk from 'algosdk';\nimport { AlgoHttpClientWithRetry } from './algo-http-client-with-retry.mjs';\nimport { AppClient } from './app-client.mjs';\nimport { AppFactory } from './app-factory.mjs';\nimport { TestNetDispenserApiClient } from './dispenser-client.mjs';\nimport { genesisIdIsLocalNet } from './network-client.mjs';\n\nvar Kmd = algosdk.Kmd;\nvar Indexer = algosdk.Indexer;\nvar IntDecoding = algosdk.IntDecoding;\n/** Exposes access to various API clients. */\nclass ClientManager {\n /**\n * algosdk clients or config for interacting with the official Algorand APIs.\n * @param clientsOrConfig The clients or config to use\n * @example Algod client only\n * ```typescript\n * const clientManager = new ClientManager({ algod: algodClient })\n * ```\n * @example All clients\n * ```typescript\n * const clientManager = new ClientManager({ algod: algodClient, indexer: indexerClient, kmd: kmdClient })\n * ```\n * @example Algod config only\n * ```typescript\n * const clientManager = new ClientManager({ algodConfig })\n * ```\n * @example All client configs\n * ```typescript\n * const clientManager = new ClientManager({ algodConfig, indexerConfig, kmdConfig })\n * ```\n */\n constructor(clientsOrConfig, algorandClient) {\n const _clients = 'algod' in clientsOrConfig\n ? clientsOrConfig\n : {\n algod: ClientManager.getAlgodClient(clientsOrConfig.algodConfig),\n indexer: clientsOrConfig.indexerConfig ? ClientManager.getIndexerClient(clientsOrConfig.indexerConfig) : undefined,\n kmd: clientsOrConfig.kmdConfig ? ClientManager.getKmdClient(clientsOrConfig.kmdConfig) : undefined,\n };\n this._algod = _clients.algod;\n this._indexer = _clients.indexer;\n this._kmd = _clients.kmd;\n this._algorand = algorandClient;\n }\n /** Returns an algosdk Algod API client. */\n get algod() {\n return this._algod;\n }\n /** Returns an algosdk Indexer API client or throws an error if it's not been provided. */\n get indexer() {\n if (!this._indexer)\n throw new Error('Attempt to use Indexer client in AlgoKit instance with no Indexer configured');\n return this._indexer;\n }\n /** Returns an algosdk Indexer API client or `undefined` if it's not been provided. */\n get indexerIfPresent() {\n return this._indexer;\n }\n /** Returns an algosdk KMD API client or throws an error if it's not been provided. */\n get kmd() {\n if (!this._kmd)\n throw new Error('Attempt to use Kmd client in AlgoKit instance with no Kmd configured');\n return this._kmd;\n }\n /**\n * Get details about the current network.\n * @example Getting genesis ID\n * ```typescript\n * const network = await networkClient.network()\n * const genesisId = network.genesisId\n * ```\n * @returns The current network details\n */\n async network() {\n if (!this._getNetworkPromise) {\n this._getNetworkPromise = this._algod.getTransactionParams().do();\n }\n const params = await this._getNetworkPromise;\n return {\n isTestNet: ['testnet-v1.0', 'testnet-v1', 'testnet'].includes(params.genesisID),\n isMainNet: ['mainnet-v1.0', 'mainnet-v1', 'mainnet'].includes(params.genesisID),\n isLocalNet: ClientManager.genesisIdIsLocalNet(params.genesisID),\n genesisId: params.genesisID,\n genesisHash: params.genesisHash,\n };\n }\n /**\n * Returns true if the given network genesisId is associated with a LocalNet network.\n * @param genesisId The network genesis ID\n * @returns Whether the given genesis ID is associated with a LocalNet network\n */\n static genesisIdIsLocalNet(genesisId) {\n return genesisIdIsLocalNet(genesisId);\n }\n /**\n * Returns true if the current network is LocalNet.\n * @returns True if the current network is LocalNet.\n */\n async isLocalNet() {\n return (await this.network()).isLocalNet;\n }\n /**\n * Returns true if the current network is TestNet.\n * @returns True if the current network is TestNet.\n */\n async isTestNet() {\n return (await this.network()).isTestNet;\n }\n /**\n * Returns true if the current network is MainNet.\n * @returns True if the current network is MainNet.\n */\n async isMainNet() {\n return (await this.network()).isMainNet;\n }\n /**\n * Returns a TestNet Dispenser API client.\n *\n * Refer to [docs](https://github.com/algorandfoundation/algokit/blob/main/docs/testnet_api.md) on guidance to obtain an access token.\n *\n * @param params An object containing parameters for the TestNetDispenserApiClient class.\n * @example\n * const client = clientManager.getTestNetDispenser(\n * {\n * authToken: 'your_auth_token',\n * requestTimeout: 15,\n * }\n * )\n *\n * @returns An instance of the TestNetDispenserApiClient class.\n */\n getTestNetDispenser(params) {\n return new TestNetDispenserApiClient(params);\n }\n /**\n * Returns a TestNet Dispenser API client, loading the auth token from `process.env.ALGOKIT_DISPENSER_ACCESS_TOKEN`.\n *\n * Refer to [docs](https://github.com/algorandfoundation/algokit/blob/main/docs/testnet_api.md) on guidance to obtain an access token.\n *\n * @param params An object containing parameters for the TestNetDispenserApiClient class.\n * @example\n * const client = clientManager.getTestNetDispenserFromEnvironment(\n * {\n * requestTimeout: 15,\n * }\n * )\n *\n * @returns An instance of the TestNetDispenserApiClient class.\n */\n getTestNetDispenserFromEnvironment(params) {\n return new TestNetDispenserApiClient(params ? { ...params, authToken: '' } : undefined);\n }\n /**\n * Returns a new `AppFactory` client\n * @example Basic example\n * ```typescript\n * const factory = algorand.client.getAppFactory({\n * appSpec: '{/* ARC-56 or ARC-32 compatible JSON *\\/}',\n * })\n * ```\n * @example Advanced example\n * ```typescript\n * const factory = algorand.client.getAppFactory({\n * appSpec: parsedAppSpec_AppSpec_or_Arc56Contract,\n * defaultSender: \"SENDERADDRESS\",\n * appName: \"OverriddenAppName\",\n * version: \"2.0.0\",\n * updatable: true,\n * deletable: false,\n * deployTimeParams: { ONE: 1, TWO: 'value' }\n * })\n * ```\n */\n getAppFactory(params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app factory from a ClientManager without an Algorand client');\n }\n return new AppFactory({ ...params, algorand: this._algorand });\n }\n /**\n * Returns a new `AppClient` client for managing calls and state for an ARC-32/ARC-56 app.\n * This method resolves the app ID by looking up the creator address and name\n * using AlgoKit app deployment semantics (i.e. looking for the app creation transaction note).\n * @param params The parameters to create the app client\n * @example Basic\n * ```typescript\n * const appClient = algorand.client.getAppClientByCreatorAndName({\n * appSpec: '{/* ARC-56 or ARC-32 compatible JSON *\\}',\n * // appId resolved by looking for app ID of named app by this creator\n * creatorAddress: 'CREATORADDRESS',\n * })\n * ```\n * @returns The `AppClient`\n */\n getAppClientByCreatorAndName(params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app client from a ClientManager without an Algorand client');\n }\n return AppClient.fromCreatorAndName({\n ...params,\n algorand: this._algorand,\n });\n }\n /**\n * Returns a new `AppClient` client for managing calls and state for an ARC-32/ARC-56 app.\n * @param params The parameters to create the app client\n * @example Basic\n * ```typescript\n * const appClient = algorand.client.getAppClientById({\n * appSpec: '{/* ARC-56 or ARC-32 compatible JSON *\\}',\n * appId: 12345n,\n * })\n * ```\n * @returns The `AppClient`\n */\n getAppClientById(params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app client from a ClientManager without an Algorand client');\n }\n return new AppClient({ ...params, algorand: this._algorand });\n }\n /**\n * Returns a new `AppClient` client for managing calls and state for an ARC-56 app.\n * This method resolves the app ID for the current network based on\n * pre-determined network-specific app IDs specified in the ARC-56 app spec.\n *\n * If no IDs are in the app spec or the network isn't recognised, an error is thrown.\n * @param params The parameters to create the app client\n * @example Basic\n * ```typescript\n * const appClient = algorand.client.getAppClientByNetwork({\n * appSpec: '{/* ARC-56 or ARC-32 compatible JSON *\\}',\n * // appId resolved by using ARC-56 spec to find app ID for current network\n * })\n * ```\n * @returns The `AppClient`\n */\n async getAppClientByNetwork(params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app client from a ClientManager without an Algorand client');\n }\n return AppClient.fromNetwork({ ...params, algorand: this._algorand });\n }\n /**\n * Returns a new typed client, resolving the app by creator address and name.\n * @param typedClient The typed client type to use\n * @param params The params to resolve the app by creator address and name\n * @example Use name in ARC-32 / ARC-56 app spec\n * ```typescript\n * const appClient = algorand.client.getTypedAppClientByCreatorAndName(MyContractClient, {\n * creatorAddress: \"CREATORADDRESS\",\n * defaultSender: alice,\n * })\n * ```\n * @example Specify name\n * ```typescript\n * const appClient = algorand.client.getTypedAppClientByCreatorAndName(MyContractClient, {\n * creatorAddress: \"CREATORADDRESS\",\n * name: \"contract-name\",\n * defaultSender: alice,\n * })\n * ```\n * @returns The typed client instance\n */\n async getTypedAppClientByCreatorAndName(typedClient, params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app client from a ClientManager without an Algorand client');\n }\n return typedClient.fromCreatorAndName({ ...params, algorand: this._algorand });\n }\n /**\n * Returns a new typed client, resolving the app by app ID.\n * @param typedClient The typed client type to use\n * @param params The params to resolve the app by ID\n * @example\n * ```typescript\n * const appClient = algorand.client.getTypedAppClientById(MyContractClient, {\n * appId: 12345n,\n * defaultSender: alice,\n * })\n * ```\n * @returns The typed client instance\n */\n getTypedAppClientById(typedClient, params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app client from a ClientManager without an Algorand client');\n }\n return new typedClient({ ...params, algorand: this._algorand });\n }\n /**\n * Returns a new typed client, resolves the app ID for the current network based on\n * pre-determined network-specific app IDs specified in the ARC-56 app spec.\n *\n * If no IDs are in the app spec or the network isn't recognised, an error is thrown.\n * @param typedClient The typed client type to use\n * @param params The params to resolve the app by network\n * @example\n * ```typescript\n * const appClient = algorand.client.getTypedAppClientByNetwork(MyContractClient, {\n * defaultSender: alice,\n * })\n * ```\n * @returns The typed client instance\n */\n getTypedAppClientByNetwork(typedClient, params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app client from a ClientManager without an Algorand client');\n }\n return typedClient.fromNetwork({ ...params, algorand: this._algorand });\n }\n /**\n * Returns a new typed app factory.\n * @param typedFactory The typed factory type to use\n * @param params The params to resolve the factory by\n * @example\n * ```typescript\n * const appFactory = algorand.client.getTypedAppFactory(MyContractClient, {\n * sender: alice,\n * })\n * ```\n * @returns The typed client instance\n */\n getTypedAppFactory(typedFactory, params) {\n if (!this._algorand) {\n throw new Error('Attempt to get app factory from a ClientManager without an Algorand client');\n }\n return new typedFactory({ ...params, algorand: this._algorand });\n }\n /**\n * Retrieve client configurations from environment variables when defined or get defaults (expects to be called from a Node.js environment)\n *\n * If both `process.env.INDEXER_SERVER` and `process.env.ALGOD_SERVER` is defined it will use both along with optional `process.env.ALGOD_PORT`, `process.env.ALGOD_TOKEN`, `process.env.INDEXER_PORT` and `process.env.INDEXER_TOKEN`.\n *\n * If only `process.env.ALGOD_SERVER` is defined it will use this along with optional `process.env.ALGOD_PORT` and `process.env.ALGOD_TOKEN` and leave indexer as `undefined`.\n *\n * If only `process.env.INDEXER_SERVER` is defined it will use the default (LocalNet) configuration for both algod and indexer.\n *\n * It will return a KMD configuration that uses `process.env.KMD_PORT` (or port 4002) if `process.env.ALGOD_SERVER` is defined,\n * otherwise it will use the default LocalNet config unless it detects testnet or mainnet.\n * @example\n * ```typescript\n * const config = ClientManager.getConfigFromEnvironmentOrLocalNet()\n * ```\n * @returns The config for algod, indexer and kmd\n */\n static getConfigFromEnvironmentOrLocalNet() {\n if (!process || !process.env) {\n throw new Error('Attempt to get default client configuration from a non Node.js context; supply the config instead');\n }\n const [algodConfig, indexerConfig, kmdConfig] = process.env.ALGOD_SERVER\n ? [\n ClientManager.getAlgodConfigFromEnvironment(),\n process.env.INDEXER_SERVER ? ClientManager.getIndexerConfigFromEnvironment() : undefined,\n !process.env.ALGOD_SERVER.includes('mainnet') && !process.env.ALGOD_SERVER.includes('testnet')\n ? { ...ClientManager.getAlgodConfigFromEnvironment(), port: process?.env?.KMD_PORT ?? '4002' }\n : undefined,\n ]\n : [\n ClientManager.getDefaultLocalNetConfig('algod'),\n ClientManager.getDefaultLocalNetConfig('indexer'),\n ClientManager.getDefaultLocalNetConfig('kmd'),\n ];\n return {\n algodConfig,\n indexerConfig,\n kmdConfig,\n };\n }\n /** Retrieve the algod configuration from environment variables (expects to be called from a Node.js environment)\n *\n * Expects `process.env.ALGOD_SERVER` to be defined, and you can also specify `process.env.ALGOD_PORT` and `process.env.ALGOD_TOKEN`.\n */\n static getAlgodConfigFromEnvironment() {\n if (!process || !process.env) {\n throw new Error('Attempt to get default algod configuration from a non Node.js context; supply the config instead');\n }\n if (!process.env.ALGOD_SERVER) {\n throw new Error('Attempt to get default algod configuration without specifying ALGOD_SERVER in the environment variables');\n }\n return {\n server: process.env.ALGOD_SERVER,\n port: process.env.ALGOD_PORT,\n token: process.env.ALGOD_TOKEN,\n };\n }\n /**\n * Retrieve the indexer configuration from environment variables (expects to be called from a Node.js environment).\n *\n * Expects `process.env.INDEXER_SERVER` to be defined, and you can also specify `process.env.INDEXER_PORT` and `process.env.INDEXER_TOKEN`.\n */\n static getIndexerConfigFromEnvironment() {\n if (!process || !process.env) {\n throw new Error('Attempt to get default indexer configuration from a non Node.js context; supply the config instead');\n }\n if (!process.env.INDEXER_SERVER) {\n throw new Error('Attempt to get default indexer configuration without specifying INDEXER_SERVER in the environment variables');\n }\n return {\n server: process.env.INDEXER_SERVER,\n port: process.env.INDEXER_PORT,\n token: process.env.INDEXER_TOKEN,\n };\n }\n /** Returns the Algorand configuration to point to the free tier of the AlgoNode service.\n *\n * @param network Which network to connect to - TestNet or MainNet\n * @param config Which algod config to return - Algod or Indexer\n */\n static getAlgoNodeConfig(network, config) {\n return {\n server: `https://${network}-${config === 'algod' ? 'api' : 'idx'}.algonode.cloud/`,\n port: 443,\n };\n }\n /** Returns the Algorand configuration to point to the default LocalNet.\n *\n * @param configOrPort Which algod config to return - algod, kmd, or indexer OR a port number\n */\n static getDefaultLocalNetConfig(configOrPort) {\n return {\n server: `http://localhost`,\n port: configOrPort === 'algod' ? 4001 : configOrPort === 'indexer' ? 8980 : configOrPort === 'kmd' ? 4002 : configOrPort,\n token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',\n };\n }\n /**\n * Returns an algod SDK client that automatically retries on idempotent calls.\n *\n * @param config The config of the client\n * @example AlgoNode (testnet)\n * ```typescript\n * const algod = ClientManager.getAlgodClient(ClientManager.getAlgoNodeConfig('testnet', 'algod'))\n * await algod.healthCheck().do()\n * ```\n * @example AlgoNode (mainnet)\n * ```typescript\n * const algod = ClientManager.getAlgodClient(ClientManager.getAlgoNodeConfig('mainnet', 'algod'))\n * await algod.healthCheck().do()\n * ```\n * @example Custom (e.g. default LocalNet)\n * ```typescript\n * const algod = ClientManager.getAlgodClient({server: 'http://localhost', port: '4001', token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'})\n * await algod.healthCheck().do()\n * ```\n */\n static getAlgodClient(config) {\n const { token, server, port } = config;\n const tokenHeader = typeof token === 'string' ? { 'X-Algo-API-Token': token } : (token ?? {});\n const httpClientWithRetry = new AlgoHttpClientWithRetry(tokenHeader, server, port);\n return new algosdk.Algodv2(httpClientWithRetry, server);\n }\n /**\n * Returns an algod SDK client that automatically retries on idempotent calls loaded from environment variables (expects to be called from a Node.js environment).\n *\n * @example\n * ```typescript\n * // Uses process.env.ALGOD_SERVER, process.env.ALGOD_PORT and process.env.ALGOD_TOKEN\n * const algod = ClientManager.getAlgodClientFromEnvironment()\n * await algod.healthCheck().do()\n * ```\n */\n static getAlgodClientFromEnvironment() {\n return ClientManager.getAlgodClient(ClientManager.getAlgodConfigFromEnvironment());\n }\n /**\n * Returns an indexer SDK client that automatically retries on idempotent calls\n *\n * @param config The config of the client\n * @param overrideIntDecoding Override the default int decoding for responses, uses MIXED by default to avoid lost precision for big integers\n * @example AlgoNode (testnet)\n * ```typescript\n * const indexer = ClientManager.getIndexerClient(ClientManager.getAlgoNodeConfig('testnet', 'indexer'))\n * await indexer.makeHealthCheck().do()\n * ```\n * @example AlgoNode (mainnet)\n * ```typescript\n * const indexer = ClientManager.getIndexerClient(ClientManager.getAlgoNodeConfig('mainnet', 'indexer'))\n * await indexer.makeHealthCheck().do()\n * ```\n * @example Custom (e.g. default LocalNet, although we recommend loading this into a .env and using the Default option instead)\n * ```typescript\n * const indexer = ClientManager.getIndexerClient({server: 'http://localhost', port: '8980', token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'})\n * await indexer.makeHealthCheck().do()\n * ```\n * @example Override int decoding for responses\n * ```typescript\n * const indexer = ClientManager.getIndexerClient(config, IntDecoding.BIGINT)\n * ```\n */\n static getIndexerClient(config, overrideIntDecoding) {\n const { token, server, port } = config;\n const tokenHeader = typeof token === 'string' ? { 'X-Indexer-API-Token': token } : (token ?? {});\n const httpClientWithRetry = new AlgoHttpClientWithRetry(tokenHeader, server, port);\n const indexer = new Indexer(httpClientWithRetry);\n // Use mixed int decoding by default so bigints don't have lost precision\n indexer.setIntEncoding(overrideIntDecoding ?? IntDecoding.MIXED);\n return indexer;\n }\n /**\n * Returns an indexer SDK client that automatically retries on idempotent calls loaded from environment variables (expects to be called from a Node.js environment).\n *\n * @param overrideIntDecoding Override the default int decoding for responses, uses MIXED by default to avoid lost precision for big integers\n * @example\n *\n * ```typescript\n * // Uses process.env.INDEXER_SERVER, process.env.INDEXER_PORT and process.env.INDEXER_TOKEN\n * const indexer = ClientManager.getIndexerClientFromEnvironment()\n * await indexer.makeHealthCheck().do()\n * ```\n */\n static getIndexerClientFromEnvironment(overrideIntDecoding) {\n return ClientManager.getIndexerClient(ClientManager.getIndexerConfigFromEnvironment(), overrideIntDecoding);\n }\n /**\n * Returns a KMD SDK client.\n *\n * KMD client allows you to export private keys, which is useful to (for instance) get the default account in a LocalNet network.\n *\n * @param config The config for the client\n * @example Custom (e.g. default LocalNet, although we recommend loading this into a .env and using the Default option instead)\n * ```typescript\n * const kmd = ClientManager.getKmdClient({server: 'http://localhost', port: '4002', token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'})\n * ```\n */\n static getKmdClient(config) {\n const { token, server, port } = config;\n return new Kmd(token, server, port);\n }\n /**\n * Returns a KMD SDK client that automatically retries on idempotent calls loaded from environment variables (expects to be called from a Node.js environment).\n *\n * @example\n * ```typescript\n * // Uses process.env.ALGOD_SERVER, process.env.KMD_PORT (or if not specified: port 4002) and process.env.ALGOD_TOKEN\n * const kmd = ClientManager.getKmdClientFromEnvironment()\n * ```\n */\n static getKmdClientFromEnvironment() {\n // We can only use Kmd on the LocalNet otherwise it's not exposed so this makes some assumptions\n // (e.g. same token and server as algod and port 4002 by default)\n return ClientManager.getKmdClient({ ...ClientManager.getAlgodConfigFromEnvironment(), port: process?.env?.KMD_PORT ?? '4002' });\n }\n}\n\nexport { ClientManager };\n//# sourceMappingURL=client-manager.mjs.map\n","import algosdk from 'algosdk';\nimport { Config } from '../config.mjs';\nimport { SigningAccount } from './account.mjs';\nimport { AlgoAmount } from './amount.mjs';\nimport { ClientManager } from './client-manager.mjs';\nimport { TransactionComposer } from './composer.mjs';\n\n/** Provides abstractions over a [KMD](https://github.com/algorand/go-algorand/blob/master/daemon/kmd/README.md) instance\n * that makes it easier to get and manage accounts using KMD. */\nclass KmdAccountManager {\n /**\n * Create a new KMD manager.\n * @param clientManager A ClientManager client to use for algod and kmd clients\n */\n constructor(clientManager) {\n this._clientManager = clientManager;\n try {\n this._kmd = clientManager.kmd;\n }\n catch {\n this._kmd = undefined;\n }\n }\n async kmd() {\n if (this._kmd === undefined) {\n if (await this._clientManager.isLocalNet()) {\n const { kmdConfig } = ClientManager.getConfigFromEnvironmentOrLocalNet();\n if (kmdConfig) {\n this._kmd = ClientManager.getKmdClient(kmdConfig);\n return this._kmd;\n }\n }\n this._kmd = null;\n }\n if (!this._kmd) {\n throw new Error('Attempt to use Kmd client in AlgoKit instance with no Kmd configured');\n }\n return this._kmd;\n }\n /**\n * Returns an Algorand signing account with private key loaded from the given KMD wallet (identified by name).\n *\n * @param walletName The name of the wallet to retrieve an account from\n * @param predicate An optional filter to use to find the account (otherwise it will return a random account from the wallet)\n * @param sender The optional sender address to use this signer for (aka a rekeyed account)\n * @example Get default funded account in a LocalNet\n *\n * ```typescript\n * const defaultDispenserAccount = await kmdAccountManager.getWalletAccount(\n * 'unencrypted-default-wallet',\n * a => a.status !== 'Offline' && a.amount > 1_000_000_000\n * )\n * ```\n * @returns The signing account (with private key loaded) or undefined if no matching wallet or account was found\n */\n async getWalletAccount(walletName, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n predicate, sender) {\n const kmd = await this.kmd();\n const walletsResponse = await kmd.listWallets();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const wallet = walletsResponse.wallets.filter((w) => w.name === walletName);\n if (wallet.length === 0) {\n return undefined;\n }\n const walletId = wallet[0].id;\n const walletHandle = (await kmd.initWalletHandle(walletId, '')).wallet_handle_token;\n const addresses = (await kmd.listKeys(walletHandle)).addresses;\n let i = 0;\n if (predicate) {\n for (i = 0; i < addresses.length; i++) {\n const address = addresses[i];\n const account = await this._clientManager.algod.accountInformation(address).do();\n if (predicate(account)) {\n break;\n }\n }\n }\n if (i >= addresses.length) {\n return undefined;\n }\n const accountKey = (await kmd.exportKey(walletHandle, '', addresses[i])).private_key;\n const accountMnemonic = algosdk.secretKeyToMnemonic(accountKey);\n const account = algosdk.mnemonicToSecretKey(accountMnemonic);\n const signingAccount = new SigningAccount(account, sender);\n return {\n account: signingAccount,\n addr: signingAccount.addr,\n signer: signingAccount.signer,\n };\n }\n /**\n * Gets an account with private key loaded from a KMD wallet of the given name, or alternatively creates one with funds in it via a KMD wallet of the given name.\n *\n * This is useful to get idempotent accounts from LocalNet without having to specify the private key (which will change when resetting the LocalNet).\n *\n * This significantly speeds up local dev time and improves experience since you can write code that *just works* first go without manual config in a fresh LocalNet.\n *\n * If this is used via `mnemonicAccountFromEnvironment`, then you can even use the same code that runs on production without changes for local development!\n *\n * @param name The name of the wallet to retrieve / create\n * @param fundWith The number of Algo to fund the account with when it gets created, if not specified then 1000 ALGO will be funded from the dispenser account\n *\n * @example\n * ```typescript\n * // Idempotently get (if exists) or crate (if it doesn't exist yet) an account by name using KMD\n * // if creating it then fund it with 2 ALGO from the default dispenser account\n * const newAccount = await kmdAccountManager.getOrCreateWalletAccount('account1', (2).algo())\n * // This will return the same account as above since the name matches\n * const existingAccount = await kmdAccountManager.getOrCreateWalletAccount('account1')\n * ```\n *\n * @returns An Algorand account with private key loaded - either one that already existed in the given KMD wallet, or a new one that is funded for you\n */\n async getOrCreateWalletAccount(name, fundWith) {\n // Get an existing account from the KMD wallet\n const existing = await this.getWalletAccount(name);\n if (existing) {\n return existing;\n }\n const kmd = await this.kmd();\n // None existed: create the KMD wallet instead\n const walletId = (await kmd.createWallet(name, '')).wallet.id;\n const walletHandle = (await kmd.initWalletHandle(walletId, '')).wallet_handle_token;\n await kmd.generateKey(walletHandle);\n // Get the account from the new KMD wallet\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const account = (await this.getWalletAccount(name));\n Config.logger.info(`LocalNet account '${name}' doesn't yet exist; created account ${account.addr} with keys stored in KMD and funding with ${fundWith?.algo ?? 1000} ALGO`);\n // Fund the account from the dispenser\n const dispenser = await this.getLocalNetDispenserAccount();\n await new TransactionComposer({\n algod: this._clientManager.algod,\n getSigner: () => dispenser.signer,\n getSuggestedParams: () => this._clientManager.algod.getTransactionParams().do(),\n })\n .addPayment({\n amount: fundWith ?? AlgoAmount.Algo(1000),\n receiver: account.addr,\n sender: dispenser.addr,\n })\n .send();\n return account;\n }\n /**\n * Returns an Algorand account with private key loaded for the default LocalNet dispenser account (that can be used to fund other accounts).\n * @example\n * ```typescript\n * const dispenser = await kmdAccountManager.getLocalNetDispenserAccount()\n * ```\n * @returns The default LocalNet dispenser account\n */\n async getLocalNetDispenserAccount() {\n if (!(await this._clientManager.isLocalNet())) {\n throw new Error(\"Can't get LocalNet dispenser account from non LocalNet network\");\n }\n const dispenser = await this.getWalletAccount('unencrypted-default-wallet', (a) => a.status !== 'Offline' && a.amount > 1000000000);\n if (!dispenser) {\n throw new Error(\"Error retrieving LocalNet dispenser account; couldn't find the default account in KMD\");\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return dispenser;\n }\n}\n\nexport { KmdAccountManager };\n//# sourceMappingURL=kmd-account-manager.mjs.map\n","import algosdk from 'algosdk';\nimport { Config } from '../config.mjs';\nimport { memoize, calculateFundAmount } from '../util.mjs';\nimport { SigningAccount, MultisigAccount, DISPENSER_ACCOUNT } from './account.mjs';\nimport { AlgoAmount } from './amount.mjs';\nimport { TransactionComposer } from './composer.mjs';\nimport { KmdAccountManager } from './kmd-account-manager.mjs';\n\nvar LogicSigAccount = algosdk.LogicSigAccount;\nvar AccountInformationModel = algosdk.modelsv2.Account;\n/**\n * Returns a `TransactionSigner` for the given account that can sign a transaction.\n * This function has memoization, so will return the same transaction signer for a given account.\n * @param account An account that can sign a transaction\n * @returns A transaction signer\n */\nconst getAccountTransactionSigner = memoize(function (account) {\n return 'signer' in account\n ? account.signer\n : 'lsig' in account\n ? algosdk.makeLogicSigAccountTransactionSigner(account)\n : algosdk.makeBasicAccountTransactionSigner(account);\n});\n/** Creates and keeps track of signing accounts that can sign transactions for a sending address. */\nclass AccountManager {\n /**\n * Create a new account manager.\n * @param clientManager The ClientManager client to use for algod and kmd clients\n * @example Create a new account manager\n * ```typescript\n * const accountManager = new AccountManager(clientManager)\n * ```\n */\n constructor(clientManager) {\n this._accounts = {};\n this._clientManager = clientManager;\n this._kmdAccountManager = new KmdAccountManager(clientManager);\n }\n _getComposer(getSuggestedParams) {\n return new TransactionComposer({\n algod: this._clientManager.algod,\n getSigner: this.getSigner.bind(this),\n getSuggestedParams: getSuggestedParams ?? (() => this._clientManager.algod.getTransactionParams().do()),\n });\n }\n /** KMD account manager that allows you to easily get and create accounts using KMD. */\n get kmd() {\n return this._kmdAccountManager;\n }\n /**\n * Sets the default signer to use if no other signer is specified.\n *\n * If this isn't set an a transaction needs signing for a given sender\n * then an error will be thrown from `getSigner` / `getAccount`.\n * @param signer The signer to use, either a `TransactionSigner` or a `TransactionSignerAccount`\n * @example\n * ```typescript\n * const signer = accountManager.random() // Can be anything that returns a `algosdk.TransactionSigner` or `TransactionSignerAccount`\n * accountManager.setDefaultSigner(signer)\n *\n * // When signing a transaction, if there is no signer registered for the sender then the default signer will be used\n * const signer = accountManager.getSigner(\"{SENDERADDRESS}\")\n * ```\n * @returns The `AccountManager` so method calls can be chained\n */\n setDefaultSigner(signer) {\n this._defaultSigner = 'signer' in signer ? signer.signer : signer;\n return this;\n }\n /**\n * Records the given account (that can sign) against the address of the provided account for later\n * retrieval and returns a `TransactionSignerAccount` along with the original account in an `account` property.\n */\n signerAccount(account) {\n const acc = {\n addr: 'addr' in account ? account.addr : account.address(),\n signer: getAccountTransactionSigner(account),\n };\n this._accounts[acc.addr] = acc;\n return { ...acc, account };\n }\n /**\n * Tracks the given account for later signing.\n *\n * Note: If you are generating accounts via the various methods on `AccountManager`\n * (like `random`, `fromMnemonic`, `logicsig`, etc.) then they automatically get tracked.\n * @param account The account to register, which can be a `TransactionSignerAccount` or\n * a `algosdk.Account`, `algosdk.LogicSigAccount`, `SigningAccount` or `MultisigAccount`\n * @example\n * ```typescript\n * const accountManager = new AccountManager(clientManager)\n * .setSignerFromAccount(algosdk.generateAccount())\n * .setSignerFromAccount(new algosdk.LogicSigAccount(program, args))\n * .setSignerFromAccount(new SigningAccount(mnemonic, sender))\n * .setSignerFromAccount(new MultisigAccount({version: 1, threshold: 1, addrs: [\"ADDRESS1...\", \"ADDRESS2...\"]}, [account1, account2]))\n * .setSignerFromAccount({addr: \"SENDERADDRESS\", signer: transactionSigner})\n * ```\n * @returns The `AccountManager` instance for method chaining\n */\n setSignerFromAccount(account) {\n this.signerAccount(account);\n return this;\n }\n /**\n * Tracks the given `algosdk.TransactionSigner` against the given sender address for later signing.\n * @param sender The sender address to use this signer for\n * @param signer The `algosdk.TransactionSigner` to sign transactions with for the given sender\n * @example\n * ```typescript\n * const accountManager = new AccountManager(clientManager)\n * .setSigner(\"SENDERADDRESS\", transactionSigner)\n * ```\n * @returns The `AccountManager` instance for method chaining\n */\n setSigner(sender, signer) {\n this._accounts[sender] = { addr: sender, signer };\n return this;\n }\n /**\n * Takes all registered signers from the given `AccountManager` and adds them to this `AccountManager`.\n *\n * This is useful for situations where you have multiple contexts you are building accounts in such as unit tests.\n * @param anotherAccountManager Another account manager with signers registered\n * @param overwriteExisting Whether or not to overwrite any signers that have the same sender address with the ones in the other account manager or not (default: true)\n * @returns The `AccountManager` instance for method chaining\n */\n setSigners(anotherAccountManager, overwriteExisting = true) {\n this._accounts = overwriteExisting\n ? { ...this._accounts, ...anotherAccountManager._accounts }\n : { ...anotherAccountManager._accounts, ...this._accounts };\n return;\n }\n /**\n * Returns the `TransactionSigner` for the given sender address, ready to sign a transaction for that sender.\n *\n * If no signer has been registered for that address then the default signer is used if registered and\n * if not then an error is thrown.\n *\n * @param sender The sender address\n * @example\n * ```typescript\n * const signer = accountManager.getSigner(\"SENDERADDRESS\")\n * ```\n * @returns The `TransactionSigner` or throws an error if not found and no default signer is set\n */\n getSigner(sender) {\n const signer = this._accounts[sender]?.signer ?? this._defaultSigner;\n if (!signer)\n throw new Error(`No signer found for address ${sender}`);\n return signer;\n }\n /**\n * Returns the `TransactionSignerAccount` for the given sender address.\n *\n * If no signer has been registered for that address then an error is thrown.\n * @param sender The sender address\n * @example\n * ```typescript\n * const sender = accountManager.random().addr\n * // ...\n * // Returns the `TransactionSignerAccount` for `sender` that has previously been registered\n * const account = accountManager.getAccount(sender)\n * ```\n * @returns The `TransactionSignerAccount` or throws an error if not found\n */\n getAccount(sender) {\n const account = this._accounts[sender];\n if (!account)\n throw new Error(`No signer found for address ${sender}`);\n return account;\n }\n /**\n * Returns the given sender account's current status, balance and spendable amounts.\n *\n * [Response data schema details](https://developer.algorand.org/docs/rest-apis/algod/#get-v2accountsaddress)\n * @example\n * ```typescript\n * const address = \"XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA\";\n * const accountInfo = await accountManager.getInformation(address);\n * ```\n *\n * @param sender The account / address to look up\n * @returns The account information\n */\n async getInformation(sender) {\n const { round, lastHeartbeat = undefined, lastProposed = undefined, ...account } = AccountInformationModel.from_obj_for_encoding(await this._clientManager.algod.accountInformation(typeof sender === 'string' ? sender : sender.addr).do());\n return {\n ...account,\n // None of the Number types can practically overflow 2^53\n balance: AlgoAmount.MicroAlgo(Number(account.amount)),\n amountWithoutPendingRewards: AlgoAmount.MicroAlgo(Number(account.amountWithoutPendingRewards)),\n minBalance: AlgoAmount.MicroAlgo(Number(account.minBalance)),\n pendingRewards: AlgoAmount.MicroAlgo(Number(account.pendingRewards)),\n rewards: AlgoAmount.MicroAlgo(Number(account.rewards)),\n validAsOfRound: BigInt(round),\n totalAppsOptedIn: Number(account.totalAppsOptedIn),\n totalAssetsOptedIn: Number(account.totalAssetsOptedIn),\n totalCreatedApps: Number(account.totalCreatedApps),\n totalCreatedAssets: Number(account.totalCreatedAssets),\n appsTotalExtraPages: account.appsTotalExtraPages !== undefined ? Number(account.appsTotalExtraPages) : undefined,\n rewardBase: account.rewardBase !== undefined ? Number(account.rewardBase) : undefined,\n totalBoxBytes: account.totalBoxBytes !== undefined ? Number(account.totalBoxBytes) : undefined,\n totalBoxes: account.totalBoxes !== undefined ? Number(account.totalBoxes) : undefined,\n lastHeartbeatRound: lastHeartbeat !== undefined ? BigInt(lastHeartbeat) : undefined,\n lastProposedRound: lastProposed !== undefined ? BigInt(lastProposed) : undefined,\n };\n }\n /**\n * Tracks and returns an Algorand account with secret key loaded (i.e. that can sign transactions) by taking the mnemonic secret.\n *\n * @example\n * ```typescript\n * const account = accountManager.fromMnemonic(\"mnemonic secret ...\")\n * const rekeyedAccount = accountManager.fromMnemonic(\"mnemonic secret ...\", \"SENDERADDRESS...\")\n * ```\n * @param mnemonicSecret The mnemonic secret representing the private key of an account; **Note: Be careful how the mnemonic is handled**,\n * never commit it into source control and ideally load it from the environment (ideally via a secret storage service) rather than the file system.\n * @param sender The optional sender address to use this signer for (aka a rekeyed account)\n * @returns The account\n */\n fromMnemonic(mnemonicSecret, sender) {\n const account = algosdk.mnemonicToSecretKey(mnemonicSecret);\n return this.signerAccount(new SigningAccount(account, sender));\n }\n /**\n * Tracks and returns an Algorand account that is a rekeyed version of the given account to a new sender.\n *\n * @example\n * ```typescript\n * const account = account.fromMnemonic(\"mnemonic secret ...\")\n * const rekeyedAccount = accountManager.rekeyed(account, \"SENDERADDRESS...\")\n * ```\n * @param account The account to use as the signer for this new rekeyed account\n * @param sender The sender address to use as the new sender\n * @returns The account\n */\n rekeyed(sender, account) {\n return this.signerAccount({ addr: sender, signer: account.signer });\n }\n /**\n * Tracks and returns an Algorand account with private key loaded by convention from environment variables based on the given name identifier.\n *\n * Note: This function expects to run in a Node.js environment.\n *\n * ## Convention:\n * * **Non-LocalNet:** will load process.env['\\{NAME\\}_MNEMONIC'] as a mnemonic secret; **Note: Be careful how the mnemonic is handled**,\n * never commit it into source control and ideally load it via a secret storage service rather than the file system.\n * If process.env['\\{NAME\\}_SENDER'] is defined then it will use that for the sender address (i.e. to support rekeyed accounts)\n * * **LocalNet:** will load the account from a KMD wallet called \\{NAME\\} and if that wallet doesn't exist it will create it and fund the account for you\n *\n * This allows you to write code that will work seamlessly in production and local development (LocalNet) without manual config locally (including when you reset the LocalNet).\n *\n * @example Default\n *\n * If you have a mnemonic secret loaded into `process.env.MY_ACCOUNT_MNEMONIC` then you can call the following to get that private key loaded into an account object:\n * ```typescript\n * const account = await accountManager.fromEnvironment('MY_ACCOUNT')\n * ```\n *\n * If that code runs against LocalNet then a wallet called `MY_ACCOUNT` will automatically be created with an account that is automatically funded with 1000 (default) ALGO from the default LocalNet dispenser.\n * If not running against LocalNet then it will use proces.env.MY_ACCOUNT_MNEMONIC as the private key and (if present) process.env.MY_ACCOUNT_SENDER as the sender address.\n *\n * @param name The name identifier of the account\n * @param fundWith The optional amount to fund the account with when it gets created (when targeting LocalNet), if not specified then 1000 ALGO will be funded from the dispenser account\n * @returns The account\n */\n async fromEnvironment(name, fundWith) {\n if (!process || !process.env) {\n throw new Error('Attempt to get account with private key from a non Node.js context; this is not supported!');\n }\n const accountMnemonic = process.env[`${name.toUpperCase()}_MNEMONIC`];\n const sender = process.env[`${name.toUpperCase()}_SENDER`];\n if (accountMnemonic) {\n const signer = algosdk.mnemonicToSecretKey(accountMnemonic);\n return this.signerAccount(new SigningAccount(signer, sender));\n }\n if (await this._clientManager.isLocalNet()) {\n const account = await this._kmdAccountManager.getOrCreateWalletAccount(name, fundWith);\n return this.signerAccount(account.account);\n }\n throw new Error(`Missing environment variable ${name.toUpperCase()}_MNEMONIC when looking for account ${name}`);\n }\n /**\n * Tracks and returns an Algorand account with private key loaded from the given KMD wallet (identified by name).\n *\n * @param name The name of the wallet to retrieve an account from\n * @param predicate An optional filter to use to find the account (otherwise it will return a random account from the wallet)\n * @param sender The optional sender address to use this signer for (aka a rekeyed account)\n * @example Get default funded account in a LocalNet\n *\n * ```typescript\n * const defaultDispenserAccount = await account.fromKmd('unencrypted-default-wallet',\n * a => a.status !== 'Offline' && a.amount > 1_000_000_000\n * )\n * ```\n * @returns The account\n */\n async fromKmd(name, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n predicate, sender) {\n const account = await this._kmdAccountManager.getWalletAccount(name, predicate, sender);\n if (!account)\n throw new Error(`Unable to find KMD account ${name}${predicate ? ' with predicate' : ''}`);\n return this.signerAccount(account.account);\n }\n /**\n * Tracks and returns an account that supports partial or full multisig signing.\n *\n * @example\n * ```typescript\n * const account = accountManager.multisig({version: 1, threshold: 1, addrs: [\"ADDRESS1...\", \"ADDRESS2...\"]},\n * [(await accountManager.fromEnvironment('ACCOUNT1')).account])\n * ```\n * @param multisigParams The parameters that define the multisig account\n * @param signingAccounts The signers that are currently present\n * @returns A multisig account wrapper\n */\n multisig(multisigParams, signingAccounts) {\n return this.signerAccount(new MultisigAccount(multisigParams, signingAccounts));\n }\n /**\n * Tracks and returns an account that represents a logic signature.\n *\n * @example\n * ```typescript\n * const account = account.logicsig(program, [new Uint8Array(3, ...)])\n * ```\n * @param program The bytes that make up the compiled logic signature\n * @param args The (binary) arguments to pass into the logic signature\n * @returns A logic signature account wrapper\n */\n logicsig(program, args) {\n return this.signerAccount(new LogicSigAccount(program, args));\n }\n /**\n * Tracks and returns a new, random Algorand account with secret key loaded.\n *\n * @example\n * ```typescript\n * const account = account.random()\n * ```\n * @returns The account\n */\n random() {\n return this.signerAccount(algosdk.generateAccount());\n }\n /**\n * Returns an account (with private key loaded) that can act as a dispenser from\n * environment variables, or against default LocalNet if no environment variables present.\n *\n * Note: requires a Node.js environment to execute.\n *\n * If present, it will load the account mnemonic stored in process.env.DISPENSER_MNEMONIC and optionally\n * process.env.DISPENSER_SENDER if it's a rekeyed account.\n *\n * @example\n * ```typescript\n * const account = await account.dispenserFromEnvironment()\n * ```\n *\n * @returns The account\n */\n async dispenserFromEnvironment() {\n if (!process || !process.env) {\n throw new Error('Attempt to get dispenser from environment from a non Node.js context; this is not supported!');\n }\n return process.env[`${DISPENSER_ACCOUNT.toUpperCase()}_MNEMONIC`]\n ? await this.fromEnvironment(DISPENSER_ACCOUNT)\n : await this.localNetDispenser();\n }\n /**\n * Returns an Algorand account with private key loaded for the default LocalNet dispenser account (that can be used to fund other accounts).\n *\n * @example\n * ```typescript\n * const account = await account.localNetDispenser()\n * ```\n * @returns The account\n */\n async localNetDispenser() {\n const dispenser = await this._kmdAccountManager.getLocalNetDispenserAccount();\n return this.signerAccount(dispenser.account);\n }\n /**\n * Rekey an account to a new address.\n *\n * **Note:** Please be careful with this function and be sure to read the [official rekey guidance](https://developer.algorand.org/docs/get-details/accounts/rekey/).\n *\n * @param account The account to rekey\n * @param rekeyTo The account address or signing account of the account that will be used to authorise transactions for the rekeyed account going forward.\n * If a signing account is provided that will now be tracked as the signer for `account` in this `AccountManager`\n * @param options Any parameters to control the transaction or execution of the transaction\n *\n * @example Basic example (with string addresses)\n * ```typescript\n * await algorand.account.rekeyAccount({account: \"ACCOUNTADDRESS\", rekeyTo: \"NEWADDRESS\"})\n * ```\n * @example Basic example (with signer accounts)\n * ```typescript\n * await algorand.account.rekeyAccount({account: account1, rekeyTo: newSignerAccount})\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.account.rekeyAccount({\n * account: \"ACCOUNTADDRESS\",\n * rekeyTo: \"NEWADDRESS\",\n * lease: 'lease',\n * note: 'note',\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n async rekeyAccount(account, rekeyTo, options) {\n const result = await this._getComposer()\n .addPayment({\n ...options,\n sender: typeof account === 'string' ? account : account.addr,\n receiver: typeof account === 'string' ? account : account.addr,\n amount: AlgoAmount.MicroAlgo(0),\n rekeyTo: typeof rekeyTo === 'string' ? rekeyTo : rekeyTo.addr,\n })\n .send(options);\n // If the rekey is a signing account set it as the signer for this account\n if (typeof rekeyTo !== 'string') {\n this.rekeyed(typeof account === 'string' ? account : account.addr, rekeyTo);\n }\n Config.getLogger(options?.suppressLog).info(`Rekeyed ${account} to ${rekeyTo} via transaction ${result.txIds.at(-1)}`);\n return { ...result, transaction: result.transactions.at(-1), confirmation: result.confirmations.at(-1) };\n }\n async _getEnsureFundedAmount(sender, minSpendingBalance, minFundingIncrement) {\n const accountInfo = await this.getInformation(sender);\n const currentSpendingBalance = accountInfo.balance.microAlgo - accountInfo.minBalance.microAlgo;\n const amountFunded = calculateFundAmount(minSpendingBalance.microAlgo, currentSpendingBalance, minFundingIncrement?.microAlgo ?? 0n);\n return amountFunded === null ? undefined : AlgoAmount.MicroAlgo(amountFunded);\n }\n /**\n * Funds a given account using a dispenser account as a funding source such that\n * the given account has a certain amount of Algo free to spend (accounting for\n * Algo locked in minimum balance requirement).\n *\n * https://developer.algorand.org/docs/get-details/accounts/#minimum-balance\n *\n * @param accountToFund The account to fund\n * @param dispenserAccount The account to use as a dispenser funding source\n * @param minSpendingBalance The minimum balance of Algo that the account should have available to spend (i.e. on top of minimum balance requirement)\n * @param options Optional parameters to control the funding increment, transaction or execution of the transaction\n * @example Example using AlgorandClient\n * ```typescript\n * // Basic example\n * await algorand.account.ensureFunded(\"ACCOUNTADDRESS\", \"DISPENSERADDRESS\", algokit.algo(1))\n * // With configuration\n * await algorand.account.ensureFunded(\"ACCOUNTADDRESS\", \"DISPENSERADDRESS\", algokit.algo(1),\n * { minFundingIncrement: algokit.algo(2), fee: (1000).microAlgo(), suppressLog: true }\n * )\n * ```\n * @returns\n * - The result of executing the dispensing transaction and the `amountFunded` if funds were needed.\n * - `undefined` if no funds were needed.\n */\n async ensureFunded(accountToFund, dispenserAccount, minSpendingBalance, options) {\n const addressToFund = typeof accountToFund === 'string' ? accountToFund : accountToFund.addr;\n const amountFunded = await this._getEnsureFundedAmount(addressToFund, minSpendingBalance, options?.minFundingIncrement);\n if (!amountFunded)\n return undefined;\n const result = await this._getComposer()\n .addPayment({\n ...options,\n sender: typeof dispenserAccount === 'string' ? dispenserAccount : dispenserAccount.addr,\n receiver: addressToFund,\n amount: amountFunded,\n })\n .send(options);\n return {\n ...result,\n transaction: result.transactions[0],\n confirmation: result.confirmations[0],\n transactionId: result.txIds[0],\n amountFunded: amountFunded,\n };\n }\n /**\n * Funds a given account using a dispenser account retrieved from the environment,\n * per the `dispenserFromEnvironment` method, as a funding source such that\n * the given account has a certain amount of Algo free to spend (accounting for\n * Algo locked in minimum balance requirement).\n *\n * **Note:** requires a Node.js environment to execute.\n *\n * The dispenser account is retrieved from the account mnemonic stored in\n * process.env.DISPENSER_MNEMONIC and optionally process.env.DISPENSER_SENDER\n * if it's a rekeyed account, or against default LocalNet if no environment variables present.\n *\n * https://developer.algorand.org/docs/get-details/accounts/#minimum-balance\n *\n * @param accountToFund The account to fund\n * @param minSpendingBalance The minimum balance of Algo that the account should have available to spend (i.e. on top of minimum balance requirement)\n * @param options Optional parameters to control the funding increment, transaction or execution of the transaction\n * @example Example using AlgorandClient\n * ```typescript\n * // Basic example\n * await algorand.account.ensureFundedFromEnvironment(\"ACCOUNTADDRESS\", algokit.algo(1))\n * // With configuration\n * await algorand.account.ensureFundedFromEnvironment(\"ACCOUNTADDRESS\", algokit.algo(1),\n * { minFundingIncrement: algokit.algo(2), fee: (1000).microAlgo(), suppressLog: true }\n * )\n * ```\n * @returns\n * - The result of executing the dispensing transaction and the `amountFunded` if funds were needed.\n * - `undefined` if no funds were needed.\n */\n async ensureFundedFromEnvironment(accountToFund, minSpendingBalance, options) {\n const addressToFund = typeof accountToFund === 'string' ? accountToFund : accountToFund.addr;\n const dispenserAccount = await this.dispenserFromEnvironment();\n const amountFunded = await this._getEnsureFundedAmount(addressToFund, minSpendingBalance, options?.minFundingIncrement);\n if (!amountFunded)\n return undefined;\n const result = await this._getComposer()\n .addPayment({\n ...options,\n sender: dispenserAccount.addr,\n receiver: addressToFund,\n amount: amountFunded,\n })\n .send(options);\n return {\n ...result,\n transaction: result.transactions[0],\n confirmation: result.confirmations[0],\n transactionId: result.txIds[0],\n amountFunded: amountFunded,\n };\n }\n /**\n * Funds a given account using the TestNet Dispenser API as a funding source such that\n * the account has a certain amount of Algo free to spend (accounting for Algo locked\n * in minimum balance requirement).\n *\n * https://developer.algorand.org/docs/get-details/accounts/#minimum-balance\n *\n * @param accountToFund The account to fund\n * @param dispenserClient The TestNet dispenser funding client\n * @param minSpendingBalance The minimum balance of Algo that the account should have available to spend (i.e. on top of minimum balance requirement)\n * @param options Optional parameters to control the funding increment, transaction or execution of the transaction\n * @example Example using AlgorandClient\n * ```typescript\n * // Basic example\n * await algorand.account.ensureFundedUsingDispenserAPI(\"ACCOUNTADDRESS\", algorand.client.getTestNetDispenserFromEnvironment(), algokit.algo(1))\n * // With configuration\n * await algorand.account.ensureFundedUsingDispenserAPI(\"ACCOUNTADDRESS\", algorand.client.getTestNetDispenserFromEnvironment(), algokit.algo(1),\n * { minFundingIncrement: algokit.algo(2) }\n * )\n * ```\n * @returns\n * - The result of executing the dispensing transaction and the `amountFunded` if funds were needed.\n * - `undefined` if no funds were needed.\n */\n async ensureFundedFromTestNetDispenserApi(accountToFund, dispenserClient, minSpendingBalance, options) {\n if (!(await this._clientManager.isTestNet())) {\n throw new Error('Attempt to fund using TestNet dispenser API on non TestNet network.');\n }\n const addressToFund = typeof accountToFund === 'string' ? accountToFund : accountToFund.addr;\n const amountFunded = await this._getEnsureFundedAmount(addressToFund, minSpendingBalance, options?.minFundingIncrement);\n if (!amountFunded)\n return undefined;\n const result = await dispenserClient.fund(addressToFund, amountFunded.microAlgo);\n return {\n amountFunded: AlgoAmount.MicroAlgo(result.amount),\n transactionId: result.txId,\n };\n }\n}\n\nexport { AccountManager, getAccountTransactionSigner };\n//# sourceMappingURL=account-manager.mjs.map\n","/** Orchestrates creating transactions for `AlgorandClient`. */\nclass AlgorandClientTransactionCreator {\n /**\n * Creates a new `AlgorandClientTransactionCreator`\n * @param newGroup A lambda that starts a new `TransactionComposer` transaction group\n */\n constructor(newGroup) {\n /**\n * Create a payment transaction to transfer Algo between accounts.\n * @param params The parameters for the payment transaction\n * @example Basic example\n * ```typescript\n * const result = await algorand.send.payment({\n * sender: 'SENDERADDRESS',\n * receiver: 'RECEIVERADDRESS',\n * amount: (4).algo(),\n * })\n * ```\n * @example Advanced example\n * ```typescript\n * const result = await algorand.send.payment({\n * amount: (4).algo(),\n * receiver: 'RECEIVERADDRESS',\n * sender: 'SENDERADDRESS',\n * closeRemainderTo: 'CLOSEREMAINDERTOADDRESS',\n * lease: 'lease',\n * note: 'note',\n * // Use this with caution, it's generally better to use algorand.account.rekeyAccount\n * rekeyTo: 'REKEYTOADDRESS',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n *\n * @returns The payment transaction\n */\n this.payment = this._transaction((c) => c.addPayment);\n /** Create a create Algorand Standard Asset transaction.\n *\n * The account that sends this transaction will automatically be\n * opted in to the asset and will hold all units after creation.\n *\n * @param params The parameters for the asset creation transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetCreate({sender: \"CREATORADDRESS\", total: 100n})\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.assetCreate({\n * sender: 'CREATORADDRESS',\n * total: 100n,\n * decimals: 2,\n * assetName: 'asset',\n * unitName: 'unit',\n * url: 'url',\n * metadataHash: 'metadataHash',\n * defaultFrozen: false,\n * manager: 'MANAGERADDRESS',\n * reserve: 'RESERVEADDRESS',\n * freeze: 'FREEZEADDRESS',\n * clawback: 'CLAWBACKADDRESS',\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The asset create transaction\n */\n this.assetCreate = this._transaction((c) => c.addAssetCreate);\n /** Create an asset config transaction to reconfigure an existing Algorand Standard Asset.\n *\n * **Note:** The manager, reserve, freeze, and clawback addresses\n * are immutably empty if they are not set. If manager is not set then\n * all fields are immutable from that point forward.\n *\n * @param params The parameters for the asset config transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetConfig({sender: \"MANAGERADDRESS\", assetId: 123456n, manager: \"MANAGERADDRESS\" })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.assetConfig({\n * sender: 'MANAGERADDRESS',\n * assetId: 123456n,\n * manager: 'MANAGERADDRESS',\n * reserve: 'RESERVEADDRESS',\n * freeze: 'FREEZEADDRESS',\n * clawback: 'CLAWBACKADDRESS',\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The asset config transaction\n */\n this.assetConfig = this._transaction((c) => c.addAssetConfig);\n /** Create an Algorand Standard Asset freeze transaction.\n *\n * @param params The parameters for the asset freeze transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetFreeze({sender: \"MANAGERADDRESS\", assetId: 123456n, account: \"ACCOUNTADDRESS\", frozen: true })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.assetFreeze({\n * sender: 'MANAGERADDRESS',\n * assetId: 123456n,\n * account: 'ACCOUNTADDRESS',\n * frozen: true,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The asset freeze transaction\n */\n this.assetFreeze = this._transaction((c) => c.addAssetFreeze);\n /** Create an Algorand Standard Asset destroy transaction.\n *\n * Created assets can be destroyed only by the asset manager account.\n * All of the assets must be owned by the creator of the asset before\n * the asset can be deleted.\n *\n * @param params The parameters for the asset destroy transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetDestroy({sender: \"MANAGERADDRESS\", assetId: 123456n })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.assetDestroy({\n * sender: 'MANAGERADDRESS',\n * assetId: 123456n,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The asset destroy transaction\n */\n this.assetDestroy = this._transaction((c) => c.addAssetDestroy);\n /** Create an Algorand Standard Asset transfer transaction.\n *\n * @param params The parameters for the asset transfer transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetTransfer({sender: \"HOLDERADDRESS\", assetId: 123456n, amount: 1n, receiver: \"RECEIVERADDRESS\" })\n * ```\n * @example Advanced example (with clawback)\n * ```typescript\n * await algorand.createTransaction.assetTransfer({\n * sender: 'CLAWBACKADDRESS',\n * assetId: 123456n,\n * amount: 1n,\n * receiver: 'RECEIVERADDRESS',\n * clawbackTarget: 'HOLDERADDRESS',\n * // This field needs to be used with caution\n * closeAssetTo: 'ADDRESSTOCLOSETO'\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The result of the asset transfer transaction\n */\n this.assetTransfer = this._transaction((c) => c.addAssetTransfer);\n /** Create an Algorand Standard Asset opt-in transaction.\n *\n * @param params The parameters for the asset opt-in transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetOptIn({sender: \"SENDERADDRESS\", assetId: 123456n })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.assetOptIn({\n * sender: 'SENDERADDRESS',\n * assetId: 123456n,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The asset opt-in transaction\n */\n this.assetOptIn = this._transaction((c) => c.addAssetOptIn);\n /** Create an asset opt-out transaction.\n *\n * *Note:* If the account has a balance of the asset,\n * it will lose those assets\n *\n * @param params The parameters for the asset opt-out transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.assetOptOut({sender: \"SENDERADDRESS\", creator: \"CREATORADDRESS\", assetId: 123456n })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.assetOptIn({\n * sender: 'SENDERADDRESS',\n * assetId: 123456n,\n * creator: 'CREATORADDRESS',\n * ensureZeroBalance: true,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * })\n * ```\n * @returns The asset opt-out transaction\n */\n this.assetOptOut = this._transaction((c) => c.addAssetOptOut);\n /** Create an application create transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app creation transaction\n * @example Basic example\n * ```typescript\n * const result = await algorand.createTransaction.appCreate({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE' })\n * const createdAppId = result.appId\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.appCreate({\n * sender: 'CREATORADDRESS',\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * schema: {\n * globalInts: 1,\n * globalByteSlices: 2,\n * localInts: 3,\n * localByteSlices: 4\n * },\n * extraProgramPages: 1,\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCreate = this._transaction((c) => c.addAppCreate);\n /** Create an application update transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app update transaction\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.appUpdate({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE' })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.appUpdate({\n * sender: 'CREATORADDRESS',\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appUpdate = this._transaction((c) => c.addAppUpdate);\n /** Create an application delete transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app deletion transaction\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.appDelete({ sender: 'CREATORADDRESS' })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.appDelete({\n * sender: 'CREATORADDRESS',\n * onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appDelete = this._transaction((c) => c.addAppDelete);\n /** Create an application call transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app call transaction\n * @example Basic example\n * ```typescript\n * await algorand.createTransaction.appCall({ sender: 'CREATORADDRESS' })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.createTransaction.appCall({\n * sender: 'CREATORADDRESS',\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCall = this._transaction((c) => c.addAppCall);\n /** Create an application create call with ABI method call transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app creation transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * const result = await algorand.createTransaction.appCreateMethodCall({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE', method: method, args: [\"arg1_value\"] })\n * const createdAppId = result.appId\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appCreate({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * schema: {\n * globalInts: 1,\n * globalByteSlices: 2,\n * localInts: 3,\n * localByteSlices: 4\n * },\n * extraProgramPages: 1,\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCreateMethodCall = this._transactions((c) => c.addAppCreateMethodCall);\n /** Create an application update call with ABI method call transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app update transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appUpdateMethodCall({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE', method: method, args: [\"arg1_value\"] })\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appUpdateMethodCall({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appUpdateMethodCall = this._transactions((c) => c.addAppUpdateMethodCall);\n /** Create an application delete call with ABI method call transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app deletion transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appDeleteMethodCall({ sender: 'CREATORADDRESS', method: method, args: [\"arg1_value\"] })\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appDeleteMethodCall({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appDeleteMethodCall = this._transactions((c) => c.addAppDeleteMethodCall);\n /** Create an application call with ABI method call transaction.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app call transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appCallMethodCall({ sender: 'CREATORADDRESS', method: method, args: [\"arg1_value\"] })\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.createTransaction.appCallMethodCall({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCallMethodCall = this._transactions((c) => c.addAppCallMethodCall);\n /** Create an online key registration transaction. */\n this.onlineKeyRegistration = this._transaction((c) => c.addOnlineKeyRegistration);\n /** Create an offline key registration transaction. */\n this.offlineKeyRegistration = this._transaction((c) => c.addOfflineKeyRegistration);\n this._newGroup = newGroup;\n }\n _transaction(c) {\n return async (params) => {\n const composer = this._newGroup();\n const result = await c(composer).apply(composer, [params]).buildTransactions();\n return result.transactions.at(-1);\n };\n }\n _transactions(c) {\n return async (params) => {\n const composer = this._newGroup();\n return await c(composer).apply(composer, [params]).buildTransactions();\n };\n }\n}\n\nexport { AlgorandClientTransactionCreator };\n//# sourceMappingURL=algorand-client-transaction-creator.mjs.map\n","import { AccountManager } from './account-manager.mjs';\nimport { AlgorandClientTransactionCreator } from './algorand-client-transaction-creator.mjs';\nimport { AlgorandClientTransactionSender } from './algorand-client-transaction-sender.mjs';\nimport { AppDeployer } from './app-deployer.mjs';\nimport { AppManager } from './app-manager.mjs';\nimport { AssetManager } from './asset-manager.mjs';\nimport { ClientManager } from './client-manager.mjs';\nimport { TransactionComposer } from './composer.mjs';\n\n/**\n * A client that brokers easy access to Algorand functionality.\n */\nclass AlgorandClient {\n constructor(config) {\n this._cachedSuggestedParamsTimeout = 3000; // three seconds\n this._defaultValidityWindow = undefined;\n this._clientManager = new ClientManager(config, this);\n this._accountManager = new AccountManager(this._clientManager);\n this._appManager = new AppManager(this._clientManager.algod);\n this._assetManager = new AssetManager(this._clientManager.algod, () => this.newGroup());\n this._transactionSender = new AlgorandClientTransactionSender(() => this.newGroup(), this._assetManager, this._appManager);\n this._transactionCreator = new AlgorandClientTransactionCreator(() => this.newGroup());\n this._appDeployer = new AppDeployer(this._appManager, this._transactionSender, this._clientManager.indexerIfPresent);\n }\n /**\n * Sets the default validity window for transactions.\n * @param validityWindow The number of rounds between the first and last valid rounds\n * @returns The `AlgorandClient` so method calls can be chained\n */\n setDefaultValidityWindow(validityWindow) {\n this._defaultValidityWindow = validityWindow;\n return this;\n }\n /**\n * Sets the default signer to use if no other signer is specified.\n * @param signer The signer to use, either a `TransactionSigner` or a `TransactionSignerAccount`\n * @returns The `AlgorandClient` so method calls can be chained\n */\n setDefaultSigner(signer) {\n this._accountManager.setDefaultSigner(signer);\n return this;\n }\n /**\n * Tracks the given account (object that encapsulates an address and a signer) for later signing.\n * @param account The account to register, which can be a `TransactionSignerAccount` or\n * a `algosdk.Account`, `algosdk.LogicSigAccount`, `SigningAccount` or `MultisigAccount`\n * @example\n * ```typescript\n * const accountManager = AlgorandClient.mainnet()\n * .setSignerFromAccount(algosdk.generateAccount())\n * .setSignerFromAccount(new algosdk.LogicSigAccount(program, args))\n * .setSignerFromAccount(new SigningAccount(mnemonic, sender))\n * .setSignerFromAccount(new MultisigAccount({version: 1, threshold: 1, addrs: [\"ADDRESS1...\", \"ADDRESS2...\"]}, [account1, account2]))\n * .setSignerFromAccount({addr: \"SENDERADDRESS\", signer: transactionSigner})\n * ```\n * @returns The `AlgorandClient` so method calls can be chained\n */\n setSignerFromAccount(account) {\n this._accountManager.setSignerFromAccount(account);\n return this;\n }\n /**\n * Tracks the given signer against the given sender for later signing.\n * @param sender The sender address to use this signer for\n * @param signer The signer to sign transactions with for the given sender\n * @returns The `AlgorandClient` so method calls can be chained\n */\n setSigner(sender, signer) {\n this._accountManager.setSigner(sender, signer);\n return this;\n }\n /**\n * Sets a cache value to use for suggested transaction params.\n * @param suggestedParams The suggested params to use\n * @param until A date until which to cache, or if not specified then the timeout is used\n * @returns The `AlgorandClient` so method calls can be chained\n */\n setSuggestedParamsCache(suggestedParams, until) {\n this._cachedSuggestedParams = suggestedParams;\n this._cachedSuggestedParamsExpiry = until ?? new Date(+new Date() + this._cachedSuggestedParamsTimeout);\n return this;\n }\n /**\n * Sets the timeout for caching suggested params.\n * @param timeout The timeout in milliseconds\n * @returns The `AlgorandClient` so method calls can be chained\n */\n setSuggestedParamsCacheTimeout(timeout) {\n this._cachedSuggestedParamsTimeout = timeout;\n return this;\n }\n /** Get suggested params for a transaction (either cached or from algod if the cache is stale or empty) */\n async getSuggestedParams() {\n if (this._cachedSuggestedParams && (!this._cachedSuggestedParamsExpiry || this._cachedSuggestedParamsExpiry > new Date())) {\n return {\n ...this._cachedSuggestedParams,\n };\n }\n this._cachedSuggestedParams = await this._clientManager.algod.getTransactionParams().do();\n this._cachedSuggestedParamsExpiry = new Date(new Date().getTime() + this._cachedSuggestedParamsTimeout);\n return {\n ...this._cachedSuggestedParams,\n };\n }\n /** Get clients, including algosdk clients and app clients. */\n get client() {\n return this._clientManager;\n }\n /** Get or create accounts that can sign transactions. */\n get account() {\n return this._accountManager;\n }\n /** Methods for interacting with assets. */\n get asset() {\n return this._assetManager;\n }\n /** Methods for interacting with apps. */\n get app() {\n return this._appManager;\n }\n /** Methods for deploying apps and managing app deployment metadata. */\n get appDeployer() {\n return this._appDeployer;\n }\n /** Start a new `TransactionComposer` transaction group */\n newGroup() {\n return new TransactionComposer({\n algod: this.client.algod,\n getSigner: (addr) => this.account.getSigner(addr),\n getSuggestedParams: () => this.getSuggestedParams(),\n defaultValidityWindow: this._defaultValidityWindow,\n appManager: this._appManager,\n });\n }\n /**\n * Methods for sending a transaction.\n */\n get send() {\n return this._transactionSender;\n }\n /**\n * Methods for creating a transaction.\n */\n get createTransaction() {\n return this._transactionCreator;\n }\n // Static methods to create an `AlgorandClient`\n /**\n * Returns an `AlgorandClient` pointing at default LocalNet ports and API token.\n * @returns The `AlgorandClient`\n */\n static defaultLocalNet() {\n return new AlgorandClient({\n algodConfig: ClientManager.getDefaultLocalNetConfig('algod'),\n indexerConfig: ClientManager.getDefaultLocalNetConfig('indexer'),\n kmdConfig: ClientManager.getDefaultLocalNetConfig('kmd'),\n });\n }\n /**\n * Returns an `AlgorandClient` pointing at TestNet using AlgoNode.\n * @returns The `AlgorandClient`\n */\n static testNet() {\n return new AlgorandClient({\n algodConfig: ClientManager.getAlgoNodeConfig('testnet', 'algod'),\n indexerConfig: ClientManager.getAlgoNodeConfig('testnet', 'indexer'),\n kmdConfig: undefined,\n });\n }\n /**\n * Returns an `AlgorandClient` pointing at MainNet using AlgoNode.\n * @returns The `AlgorandClient`\n */\n static mainNet() {\n return new AlgorandClient({\n algodConfig: ClientManager.getAlgoNodeConfig('mainnet', 'algod'),\n indexerConfig: ClientManager.getAlgoNodeConfig('mainnet', 'indexer'),\n kmdConfig: undefined,\n });\n }\n /**\n * Returns an `AlgorandClient` pointing to the given client(s).\n * @param clients The clients to use\n * @returns The `AlgorandClient`\n */\n static fromClients(clients) {\n return new AlgorandClient(clients);\n }\n /**\n * Returns an `AlgorandClient` loading the configuration from environment variables.\n *\n * Retrieve configurations from environment variables when defined or get default LocalNet configuration if they aren't defined.\n *\n * Expects to be called from a Node.js environment.\n *\n * If `process.env.ALGOD_SERVER` is defined it will use that along with optional `process.env.ALGOD_PORT` and `process.env.ALGOD_TOKEN`.\n *\n * If `process.env.INDEXER_SERVER` is defined it will use that along with optional `process.env.INDEXER_PORT` and `process.env.INDEXER_TOKEN`.\n *\n * If either aren't defined it will use the default LocalNet config.\n *\n * It will return a KMD configuration that uses `process.env.KMD_PORT` (or port 4002) if `process.env.ALGOD_SERVER` is defined,\n * otherwise it will use the default LocalNet config unless it detects testnet or mainnet.\n * @returns The `AlgorandClient`\n */\n static fromEnvironment() {\n return new AlgorandClient(ClientManager.getConfigFromEnvironmentOrLocalNet());\n }\n /**\n * Returns an `AlgorandClient` from the given config.\n * @param config The config to use\n * @returns The `AlgorandClient`\n */\n static fromConfig(config) {\n return new AlgorandClient(config);\n }\n}\n\nexport { AlgorandClient };\n//# sourceMappingURL=algorand-client.mjs.map\n","import { legacySendTransactionBridge } from './transaction/legacy-bridge.mjs';\nimport { AlgorandClient } from './types/algorand-client.mjs';\nimport { getSenderAddress, encodeTransactionNote } from './transaction/transaction.mjs';\n\n/**\n * @deprecated use `algorand.send.assetCreate()` / `algorand.createTransaction.assetCreate()` instead\n *\n * Create an Algorand Standard Asset (ASA).\n * @param create The asset creation definition\n * @param algod An algod client\n * @returns The transaction object and optionally the confirmation if it was sent to the chain (`skipSending` is `false` or unset)\n *\n * @example Usage example\n * ```typescript\n * await algokit.createAsset({ creator: account, total: 1, decimals: 0, name: 'My asset' }, algod)\n * ```\n */\nasync function createAsset(create, algod) {\n const params = {\n sender: getSenderAddress(create.creator),\n total: BigInt(create.total),\n decimals: create.decimals,\n assetName: create.name,\n unitName: create.unit,\n manager: create.manager ? getSenderAddress(create.manager) : undefined,\n clawback: create.clawbackAccount ? getSenderAddress(create.clawbackAccount) : undefined,\n freeze: create.freezeAccount ? getSenderAddress(create.freezeAccount) : undefined,\n reserve: create.reserveAccount ? getSenderAddress(create.reserveAccount) : undefined,\n defaultFrozen: create.frozenByDefault,\n lease: create.lease,\n metadataHash: create.metadataHash,\n note: encodeTransactionNote(create.note),\n url: create.url,\n };\n return (await legacySendTransactionBridge(algod, create.creator, create, params, (client) => client.assetCreate, (client) => client.assetCreate));\n}\n/**\n * @deprecated use `algorand.send.assetOptIn()` / `algorand.createTransaction.assetOptIn()` instead\n *\n * Opt-in an account to an asset.\n * @param optIn The opt-in definition\n * @param algod An algod client\n * @returns The transaction object and optionally the confirmation if it was sent to the chain (`skipSending` is `false` or unset)\n *\n * @example Usage example\n * ```typescript\n * await algokit.assetOptIn({ account, assetId }, algod)\n * ```\n */\nasync function assetOptIn(optIn, algod) {\n const params = {\n assetId: BigInt(optIn.assetId),\n sender: getSenderAddress(optIn.account),\n note: encodeTransactionNote(optIn.note),\n lease: optIn.lease,\n };\n return legacySendTransactionBridge(algod, optIn.account, optIn, params, (c) => c.assetOptIn, (c) => c.assetOptIn);\n}\n/**\n * @deprecated use `algorand.send.assetOptOut()` / `algorand.createTransaction.assetOptOut()` instead\n *\n * Opt-out an account from an asset.\n * @param optOut The opt-in definition\n * @param algod An algod client\n * @returns The transaction object and optionally the confirmation if it was sent to the chain (`skipSending` is `false` or unset)\n *\n * @example Usage example\n * ```typescript\n * await algokit.assetOptOut({ account, assetId, assetCreatorAddress }, algod)\n * ```\n */\nasync function assetOptOut(optOut, algod) {\n const assetCreatorAddress = optOut.assetCreatorAddress ?? (await algod.getAssetByID(optOut.assetId).do()).params.creator;\n const params = {\n assetId: BigInt(optOut.assetId),\n creator: assetCreatorAddress,\n sender: getSenderAddress(optOut.account),\n note: encodeTransactionNote(optOut.note),\n lease: optOut.lease,\n };\n return legacySendTransactionBridge(algod, optOut.account, optOut, params, (c) => c.assetOptOut, (c) => (params) => c.assetOptOut({ ...params, ensureZeroBalance: optOut.ensureZeroBalance ?? true }));\n}\n/**\n * @deprecated use `algorand.asset.bulkOptIn()` instead\n *\n * Opt in to a list of assets on the Algorand blockchain.\n *\n * @param optIn - The bulk opt-in request.\n * @param algod - An instance of the Algodv2 class from the `algosdk` library.\n * @returns A record object where the keys are the asset IDs and the values are the corresponding transaction IDs for successful opt-ins.\n * @throws If there is an error during the opt-in process.\n * @example algokit.bulkOptIn({ account: account, assetIds: [12345, 67890] }, algod)\n */\nasync function assetBulkOptIn(optIn, algod) {\n const result = await AlgorandClient.fromClients({ algod })\n .setSignerFromAccount(optIn.account)\n .asset.bulkOptIn(getSenderAddress(optIn.account), optIn.assetIds.map(BigInt), {\n note: encodeTransactionNote(optIn.note),\n maxFee: optIn.maxFee,\n suppressLog: optIn.suppressLog,\n });\n const returnResult = {};\n for (const r of result) {\n returnResult[Number(r.assetId)] = r.transactionId;\n }\n return returnResult;\n}\n/**\n * @deprecated use `algorand.asset.bulkOptOut()` instead\n *\n * Opt out of multiple assets in Algorand blockchain.\n *\n * @param optOut The bulk opt-out request.\n * @param algod - An instance of the Algodv2 client used to interact with the Algorand blockchain.\n * @returns A record object containing asset IDs as keys and their corresponding transaction IDs as values.\n * @throws If there is an error during the opt-out process.\n * @example algokit.bulkOptOut({ account: account, assetIds: [12345, 67890] }, algod)\n */\nasync function assetBulkOptOut(optOut, algod) {\n const result = await AlgorandClient.fromClients({ algod })\n .setSignerFromAccount(optOut.account)\n .asset.bulkOptOut(getSenderAddress(optOut.account), optOut.assetIds.map(BigInt), {\n ensureZeroBalance: optOut.validateBalances ?? true,\n note: encodeTransactionNote(optOut.note),\n maxFee: optOut.maxFee,\n suppressLog: optOut.suppressLog,\n });\n const returnResult = {};\n for (const r of result) {\n returnResult[Number(r.assetId)] = r.transactionId;\n }\n return returnResult;\n}\n\nexport { assetBulkOptIn, assetBulkOptOut, assetOptIn, assetOptOut, createAsset };\n//# sourceMappingURL=asset.mjs.map\n","import { TestNetDispenserApiClient } from './types/dispenser-client.mjs';\n\n/**\n * @deprecated Use `clientManager.getTestNetDispenser` or `clientManager.getTestNetDispenserFromEnvironment` instead\n *\n * Create a new TestNetDispenserApiClient instance.\n * Refer to [docs](https://github.com/algorandfoundation/algokit/blob/main/docs/testnet_api.md) on guidance to obtain an access token.\n *\n * @param params An object containing parameters for the TestNetDispenserApiClient class.\n * Or null if you want the client to load the access token from the environment variable `ALGOKIT_DISPENSER_ACCESS_TOKEN`.\n * @example\n * const client = algokit.getTestNetDispenserApiClient(\n * {\n * authToken: 'your_auth_token',\n * requestTimeout: 15,\n * }\n * )\n *\n * @returns An instance of the TestNetDispenserApiClient class.\n */\nfunction getTestNetDispenserApiClient(params = null) {\n return new TestNetDispenserApiClient(params === null ? undefined : params);\n}\n\nexport { getTestNetDispenserApiClient };\n//# sourceMappingURL=dispenser-client.mjs.map\n","import { ClientManager } from './types/client-manager.mjs';\n\n/**\n * @deprecated Use `ClientManager.getConfigFromEnvironmentOrLocalNet()` instead.\n *\n * Retrieve configurations from environment variables when defined or get defaults (expects to be called from a Node.js environment not algod-side)\n */\nfunction getConfigFromEnvOrDefaults() {\n return ClientManager.getConfigFromEnvironmentOrLocalNet();\n}\n/**\n * @deprecated Use `ClientManager.getAlgodConfigFromEnvironment()` instead.\n *\n * Retrieve the algod configuration from environment variables (expects to be called from a Node.js environment not algod-side)\n */\nfunction getAlgodConfigFromEnvironment() {\n return ClientManager.getAlgodConfigFromEnvironment();\n}\n/**\n * @deprecated Use `ClientManager.getIndexerConfigFromEnvironment()` instead.\n *\n * Retrieve the indexer configuration from environment variables (expects to be called from a Node.js environment not algod-side)\n */\nfunction getIndexerConfigFromEnvironment() {\n return ClientManager.getIndexerConfigFromEnvironment();\n}\n/**\n * @deprecated Use `ClientManager.getAlgoNodeConfig(network, config)` instead.\n *\n * Returns the Algorand configuration to point to the AlgoNode service\n *\n * @param network Which network to connect to - TestNet or MainNet\n * @param config Which algod config to return - Algod or Indexer\n */\nfunction getAlgoNodeConfig(network, config) {\n return ClientManager.getAlgoNodeConfig(network, config);\n}\n/**\n * @deprecated Use `ClientManager.getDefaultLocalNetConfig(configOrPort)` instead.\n *\n * Returns the Algorand configuration to point to the default LocalNet\n *\n * @param configOrPort Which algod config to return - algod, kmd, or indexer OR a port number\n */\nfunction getDefaultLocalNetConfig(configOrPort) {\n return ClientManager.getDefaultLocalNetConfig(configOrPort);\n}\n/**\n * @deprecated Use `ClientManager.getAlgodClient(config)` or `ClientManager.getAlgodClientFromEnvironment()` instead.\n *\n * Returns an algod SDK client that automatically retries transient failures on idempotent calls\n *\n * @param config The config if you want to override the default (getting config from process.env)\n * @example Default (load from environment variables)\n *\n * ```typescript\n * // Uses process.env.ALGOD_SERVER, process.env.ALGOD_PORT and process.env.ALGOD_TOKEN\n * // Automatically detects if you are using PureStake to switch in the right header name for ALGOD_TOKEN\n * const algod = getAlgoClient()\n * await algod.healthCheck().do()\n * ```\n * @example AlgoNode (testnet)\n * ```typescript\n * const algod = getAlgoClient(getAlgoNodeConfig('testnet', 'algod'))\n * await algod.healthCheck().do()\n * ```\n * @example AlgoNode (mainnet)\n * ```typescript\n * const algod = getAlgoClient(getAlgoNodeConfig('mainnet', 'algod'))\n * await algod.healthCheck().do()\n * ```\n * @example Custom (e.g. default LocalNet, although we recommend loading this into a .env and using the Default option instead)\n * ```typescript\n * const algod = getAlgoClient({server: 'http://localhost', port: '4001', token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'})\n * await algod.healthCheck().do()\n * ```\n */\nfunction getAlgoClient(config) {\n return config ? ClientManager.getAlgodClient(config) : ClientManager.getAlgodClientFromEnvironment();\n}\n/**\n * @deprecated Use `ClientManager.getIndexerClient(config, overrideIntDecoding)` or `ClientManager.getIndexerClientFromEnvironment(overrideIntDecoding)` instead.\n *\n * Returns an indexer SDK client that automatically retries transient failures on idempotent calls\n *\n * @param config The config if you want to override the default (getting config from process.env)\n * @param overrideIntDecoding Override the default int decoding for responses, uses MIXED by default to avoid lost precision for big integers\n * @example Default (load from environment variables)\n *\n * ```typescript\n * // Uses process.env.INDEXER_SERVER, process.env.INDEXER_PORT and process.env.INDEXER_TOKEN\n * const indexer = getAlgoIndexerClient()\n * await indexer.makeHealthCheck().do()\n * ```\n * @example AlgoNode (testnet)\n * ```typescript\n * const indexer = getAlgoIndexerClient(getAlgoNodeConfig('testnet', 'indexer'))\n * await indexer.makeHealthCheck().do()\n * ```\n * @example AlgoNode (mainnet)\n * ```typescript\n * const indexer = getAlgoIndexerClient(getAlgoNodeConfig('mainnet', 'indexer'))\n * await indexer.makeHealthCheck().do()\n * ```\n * @example Custom (e.g. default LocalNet, although we recommend loading this into a .env and using the Default option instead)\n * ```typescript\n * const indexer = getAlgoIndexerClient({server: 'http://localhost', port: '8980', token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'})\n * await indexer.makeHealthCheck().do()\n * ```\n * @example Override int decoding for responses\n * ```typescript\n * const indexer = getAlgoIndexerClient(config, IntDecoding.BIGINT)\n * ```\n */\nfunction getAlgoIndexerClient(config, overrideIntDecoding) {\n return config\n ? ClientManager.getIndexerClient(config, overrideIntDecoding)\n : ClientManager.getIndexerClientFromEnvironment(overrideIntDecoding);\n}\n/**\n * @deprecated Use `ClientManager.getKmdClient(config)` or `ClientManager.getKmdClientFromEnvironment()` instead.\n *\n * Returns a KMD SDK client that automatically retries transient failures on idempotent calls.\n *\n * KMD client allows you to export private keys, which is useful to get the default account in a LocalNet network.\n *\n * @param config The config if you want to override the default (getting config from process.env)\n * @example Default (load from environment variables)\n *\n * ```typescript\n * // Uses process.env.ALGOD_SERVER, process.env.KMD_PORT (or if not specified: port 4002) and process.env.ALGOD_TOKEN\n * const kmd = getAlgoKmdClient()\n * ```\n * @example Custom (e.g. default LocalNet, although we recommend loading this into a .env and using the Default option instead)\n * ```typescript\n * const kmd = getAlgoKmdClient({server: 'http://localhost', port: '4002', token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'})\n * ```\n */\nfunction getAlgoKmdClient(config) {\n return config ? ClientManager.getKmdClient(config) : ClientManager.getKmdClientFromEnvironment();\n}\n/** @deprecated Use `await algorand.client.isTestNet()` or `await new ClientManager({ algod }).isTestNet()` instead. */\nasync function isTestNet(algod) {\n return await new ClientManager({ algod }).isTestNet();\n}\n/** @deprecated Use `await algorand.client.isMainNet()` or `await new ClientManager({ algod }).isMainNet()` instead. */\nasync function isMainNet(algod) {\n return await new ClientManager({ algod }).isMainNet();\n}\n\nexport { getAlgoClient, getAlgoIndexerClient, getAlgoKmdClient, getAlgoNodeConfig, getAlgodConfigFromEnvironment, getConfigFromEnvOrDefaults, getDefaultLocalNetConfig, getIndexerConfigFromEnvironment, isMainNet, isTestNet };\n//# sourceMappingURL=network-client.mjs.map\n","import algosdk from 'algosdk';\nimport { AlgoAmount } from './types/amount.mjs';\n\nNumber.prototype.microAlgos = function () {\n return AlgoAmount.MicroAlgo(this);\n};\nNumber.prototype.algos = function () {\n return AlgoAmount.Algo(this);\n};\nNumber.prototype.microAlgo = function () {\n return AlgoAmount.MicroAlgo(this);\n};\nNumber.prototype.algo = function () {\n return AlgoAmount.Algo(this);\n};\nBigInt.prototype.microAlgo = function () {\n return AlgoAmount.MicroAlgo(this);\n};\nBigInt.prototype.algo = function () {\n return AlgoAmount.Algo(this);\n};\n/** Returns an amount of Algo using AlgoAmount\n * @param algos The amount of Algo\n */\nconst algos = (algos) => {\n return AlgoAmount.Algo(algos);\n};\n/** Returns an amount of Algo using AlgoAmount\n * @param algos The amount of Algo\n */\nconst algo = (algos) => {\n return AlgoAmount.Algo(algos);\n};\n/** Returns an amount of µAlgo using AlgoAmount\n * @param microAlgos The amount of µAlgo\n */\nconst microAlgos = (microAlgos) => {\n return AlgoAmount.MicroAlgo(microAlgos);\n};\n/** Returns an amount of µAlgo using AlgoAmount\n * @param microAlgos The amount of µAlgo\n */\nconst microAlgo = (microAlgos) => {\n return AlgoAmount.MicroAlgo(microAlgos);\n};\n/** Returns an amount of µAlgo to cover standard fees for the given number of transactions using AlgoAmount\n * @param numberOfTransactions The of standard transaction fees to return the amount of Algo\n */\nconst transactionFees = (numberOfTransactions) => {\n return AlgoAmount.MicroAlgo(numberOfTransactions * algosdk.ALGORAND_MIN_TX_FEE);\n};\n\nexport { algo, algos, microAlgo, microAlgos, transactionFees };\n//# sourceMappingURL=amount.mjs.map\n","import algosdk from 'algosdk';\nimport { getSenderAddress } from '../transaction/transaction.mjs';\nimport { MultisigAccount, SigningAccount } from '../types/account.mjs';\nimport { AccountManager } from '../types/account-manager.mjs';\nimport { AlgorandClient } from '../types/algorand-client.mjs';\nimport { ClientManager } from '../types/client-manager.mjs';\n\nvar AccountInformationModel = algosdk.modelsv2.Account;\n/**\n * @deprecated Use `algorand.account.multisig(multisigParams, signingAccounts)` or `new MultisigAccount(multisigParams, signingAccounts)` instead.\n *\n * Returns an account wrapper that supports partial or full multisig signing.\n * @param multisigParams The parameters that define the multisig account\n * @param signingAccounts The signers that are currently present\n * @returns A multisig account wrapper\n */\nfunction multisigAccount(multisigParams, signingAccounts) {\n return new MultisigAccount(multisigParams, signingAccounts);\n}\n/**\n * @deprecated Use `algorand.account.rekeyed(sender, account)` or `new SigningAccount(account, sender)` instead.\n *\n * Returns an account wrapper that supports a rekeyed account.\n * @param signer The account, with private key loaded, that is signing\n * @param sender The address of the rekeyed account that will act as a sender\n * @returns The SigningAccount wrapper\n */\nfunction rekeyedAccount(signer, sender) {\n return new SigningAccount(signer, sender);\n}\n/**\n * @deprecated Use `algorand.account.getSigner(sender)` (after previously registering the signer with `setSigner`) or `{ addr: sender, signer }` instead.\n *\n * Returns an account wrapper that supports a transaction signer with associated sender address.\n * @param signer The transaction signer\n * @param sender The address of sender account\n * @returns The SigningAccount wrapper\n */\nfunction transactionSignerAccount(signer, sender) {\n return { addr: sender, signer };\n}\n/**\n * @deprecated Use `algorand.account.random()` or `algosdk.generateAccount()` instead.\n *\n * Returns a new, random Algorand account with secret key loaded.\n *\n * This is a wrapper around algosdk.generateAccount to provide a more friendly/obvious name.\n *\n */\nfunction randomAccount() {\n // This method is confusingly named, so this function provides a more dev friendly \"wrapper\" name\n return algosdk.generateAccount();\n}\n/**\n * @deprecated Use `algorand.account.fromEnvironment(name, fundWith)` or `new AccountManager(clientManager).fromEnvironment()` instead.\n *\n * Returns an Algorand account with private key loaded by convention from environment variables based on the given name identifier.\n *\n * Note: This function expects to run in a Node.js environment.\n *\n * ## Convention:\n * * **Non-LocalNet:** will load process.env['\\{NAME\\}_MNEMONIC'] as a mnemonic secret; **Note: Be careful how the mnemonic is handled**,\n * never commit it into source control and ideally load it via a secret storage service rather than the file system.\n * If process.env['\\{NAME\\}_SENDER'] is defined then it will use that for the sender address (i.e. to support rekeyed accounts)\n * * **LocalNet:** will load the account from a KMD wallet called \\{NAME\\} and if that wallet doesn't exist it will create it and fund the account for you\n *\n * This allows you to write code that will work seamlessly in production and local development (LocalNet) without manual config locally (including when you reset the LocalNet).\n *\n * @example Default\n *\n * If you have a mnemonic secret loaded into `process.env.MY_ACCOUNT_MNEMONIC` then you can call the following to get that private key loaded into an account object:\n * ```typescript\n * const account = await mnemonicAccountFromEnvironment('MY_ACCOUNT', algod)\n * ```\n *\n * If that code runs against LocalNet then a wallet called `MY_ACCOUNT` will automatically be created with an account that is automatically funded with 1000 (default) ALGO from the default LocalNet dispenser.\n * If not running against LocalNet then it will use proces.env.MY_ACCOUNT_MNEMONIC as the private key and (if present) process.env.MY_ACCOUNT_SENDER as the sender address.\n *\n * @param account The details of the account to get, either the name identifier (string) or an object with:\n * * `name`: string: The name identifier of the account\n * * `fundWith`: The amount to fund the account with when it gets created (when targeting LocalNet), if not specified then 1000 ALGO will be funded from the dispenser account\n * @param algod An algod client\n * @param kmdClient An optional KMD client to use to create an account (when targeting LocalNet), if not specified then a default KMD client will be loaded from environment variables\n * @returns The requested account with private key loaded from the environment variables or when targeting LocalNet from KMD (idempotently creating and funding the account)\n */\nasync function mnemonicAccountFromEnvironment(account, algod, kmdClient) {\n return (await new AccountManager(new ClientManager({ algod, kmd: kmdClient })).fromEnvironment(typeof account === 'string' ? account : account.name, typeof account === 'string' ? undefined : account.fundWith)).account;\n}\n/**\n * @deprecated Use `algosdk.decodeAddress` instead.\n *\n * Returns an account's address as a byte array\n *\n * @param account Either an account (with private key loaded) or the string address of an account\n */\nfunction getAccountAddressAsUint8Array(account) {\n return algosdk.decodeAddress(typeof account === 'string' ? account : getSenderAddress(account)).publicKey;\n}\n/**\n * @deprecated Use `algosdk.encodeAddress` instead.\n *\n * Returns the string address of an Algorand account from a base64 encoded version of the underlying byte array of the address public key\n *\n * @param addressEncodedInB64 The base64 encoded version of the underlying byte array of the address public key\n */\nfunction getAccountAddressAsString(addressEncodedInB64) {\n return algosdk.encodeAddress(Buffer.from(addressEncodedInB64, 'base64'));\n}\n/**\n * @deprecated Use `algorand.account.getInformation(sender)` or `new AccountManager(clientManager).getInformation(sender)` instead.\n *\n * Returns the given sender account's current status, balance and spendable amounts.\n *\n * @example\n * ```typescript\n * const address = \"XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA\";\n * const accountInfo = await account.getInformation(address, algod);\n * ```\n *\n * [Response data schema details](https://developer.algorand.org/docs/rest-apis/algod/#get-v2accountsaddress)\n * @param sender The address of the sender/account to look up\n * @param algod The algod instance\n * @returns The account information\n */\nasync function getAccountInformation(sender, algod) {\n const account = AccountInformationModel.from_obj_for_encoding(await algod.accountInformation(getSenderAddress(sender)).do());\n return {\n ...account,\n // None of these can practically overflow 2^53\n amount: Number(account.amount),\n amountWithoutPendingRewards: Number(account.amountWithoutPendingRewards),\n minBalance: Number(account.minBalance),\n pendingRewards: Number(account.pendingRewards),\n rewards: Number(account.rewards),\n round: Number(account.round),\n totalAppsOptedIn: Number(account.totalAppsOptedIn),\n totalAssetsOptedIn: Number(account.totalAssetsOptedIn),\n totalCreatedApps: Number(account.totalCreatedApps),\n totalCreatedAssets: Number(account.totalCreatedAssets),\n appsTotalExtraPages: account.appsTotalExtraPages !== undefined ? Number(account.appsTotalExtraPages) : undefined,\n rewardBase: account.rewardBase !== undefined ? Number(account.rewardBase) : undefined,\n totalBoxBytes: account.totalBoxBytes !== undefined ? Number(account.totalBoxBytes) : undefined,\n totalBoxes: account.totalBoxes !== undefined ? Number(account.totalBoxes) : undefined,\n lastHeartbeat: account.lastHeartbeat !== undefined ? Number(account.lastHeartbeat) : undefined,\n lastProposed: account.lastProposed !== undefined ? Number(account.lastProposed) : undefined,\n };\n}\n/**\n * @deprecated Use `algorand.asset.getAccountInformation(sender, assetId)` or `new AssetManager(...).getAccountInformation(sender, assetId)` instead.\n *\n * Returns the given sender account's asset holding for a given asset.\n *\n * @example\n * ```typescript\n * const address = \"XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA\";\n * const assetId = 123345;\n * const accountInfo = await account.getAccountAssetInformation(address, assetId, algod);\n * ```\n *\n * [Response data schema details](https://developer.algorand.org/docs/rest-apis/algod/#get-v2accountsaddressassetsasset-id)\n * @param sender The address of the sender/account to look up\n * @param assetId The ID of the asset to return a holding for\n * @param algod The algod instance\n * @returns The account asset holding information\n */\nasync function getAccountAssetInformation(sender, assetId, algod) {\n return AlgorandClient.fromClients({ algod }).asset.getAccountInformation(getSenderAddress(sender), BigInt(assetId));\n}\n\nexport { getAccountAddressAsString, getAccountAddressAsUint8Array, getAccountAssetInformation, getAccountInformation, mnemonicAccountFromEnvironment, multisigAccount, randomAccount, rekeyedAccount, transactionSignerAccount };\n//# sourceMappingURL=account.mjs.map\n","/** @deprecated Use algokit.mnemonicAccountFromEnvironment, which doesn't need this function\n * Returns the Account configuration from environment variables\n *\n * @param accountName account name\n *\n * @example environment variables\n * {accountName}_MNEMONIC\n * {accountName}_SENDER\n *\n */\nfunction getAccountConfigFromEnvironment(accountName) {\n if (!process || !process.env) {\n throw new Error('Attempt to get account with private key from a non Node.js context; not supported!');\n }\n return {\n accountMnemonic: process.env[`${accountName.toUpperCase()}_MNEMONIC`] || '',\n senderAddress: process.env[`${accountName.toUpperCase()}_SENDER`],\n accountName,\n };\n}\n\nexport { getAccountConfigFromEnvironment };\n//# sourceMappingURL=get-account-config-from-environment.mjs.map\n","import { AccountManager } from '../types/account-manager.mjs';\nimport { ClientManager } from '../types/client-manager.mjs';\nimport { getAccountConfigFromEnvironment } from './get-account-config-from-environment.mjs';\n\n/** @deprecated use `algorand.account.fromEnvironment()` instead\n * Returns an Algorand account with private key loaded by convention based on the given name identifier.\n *\n * Note: This function expects to run in a Node.js environment.\n *\n * ## Convention:\n * * **Non-LocalNet:** will load process.env['\\{NAME\\}_MNEMONIC'] as a mnemonic secret; **Note: Be careful how the mnemonic is handled**,\n * never commit it into source control and ideally load it via a secret storage service rather than the file system.\n * If process.env['\\{NAME\\}_SENDER'] is defined then it will use that for the sender address (i.e. to support rekeyed accounts)\n * * **LocalNet:** will load the account from a KMD wallet called \\{NAME\\} and if that wallet doesn't exist it will create it and fund the account for you\n *\n * This allows you to write code that will work seamlessly in production and local development (LocalNet) without manual config locally (including when you reset the LocalNet).\n *\n * @example Default\n *\n * If you have a mnemonic secret loaded into `process.env.ACCOUNT_MNEMONIC` then you can call the following to get that private key loaded into an account object:\n * ```typescript\n * const account = await getAccount({config: getAccountConfigFromEnvironment('ACCOUNT')}, algod)\n * ```\n *\n * If that code runs against LocalNet then a wallet called `ACCOUNT` will automatically be created with an account that is automatically funded with 1000 (default) ALGO from the default LocalNet dispenser.\n *\n * @param account The details of the account to get, either the name identifier (string) or an object with:\n * * `config`: Account configuration. To get from environment use getAccountConfigFromEnvironment(accountName) OR\n * * `name`: string: The name identifier of the account (deprecated)\n * And optionally\n * * `fundWith`: The amount to fund the account with when it gets created (when targeting LocalNet), if not specified then 1000 ALGO will be funded from the dispenser account\n * @param algod An algod client\n * @param kmdClient An optional KMD client to use to create an account (when targeting LocalNet), if not specified then a default KMD client will be loaded from environment variables\n * @returns The requested account with private key loaded from the environment variables or when targeting LocalNet from KMD (idempotently creating and funding the account)\n */\nasync function getAccount(account, algod, kmdClient) {\n let name;\n let fundWith = undefined;\n let config;\n if (typeof account === 'string') {\n name = account;\n config = getAccountConfigFromEnvironment(name);\n }\n else if ('name' in account) {\n name = account.name;\n config = getAccountConfigFromEnvironment(name);\n fundWith = account.fundWith;\n }\n else if ('config' in account) {\n config = account.config;\n name = config.accountName;\n fundWith = account.fundWith;\n }\n else {\n throw new Error('Missing name or account config');\n }\n return (await new AccountManager(new ClientManager({ algod, kmd: kmdClient })).fromEnvironment(name, fundWith)).account;\n}\n\nexport { getAccount };\n//# sourceMappingURL=get-account.mjs.map\n","import { AccountManager } from '../types/account-manager.mjs';\nimport { ClientManager } from '../types/client-manager.mjs';\n\n/**\n * @deprecated Use `algorand.account.dispenserFromEnvironment()` or `new AccountManager(clientManager).dispenserFromEnvironment()` instead\n *\n * Returns an account (with private key loaded) that can act as a dispenser\n *\n * If running on LocalNet then it will return the default dispenser account automatically,\n * otherwise it will load the account mnemonic stored in process.env.DISPENSER_MNEMONIC\n *\n * @param algod An algod client\n * @param kmd A KMD client, if not specified then a default KMD client will be loaded from environment variables\n */\nasync function getDispenserAccount(algod, kmd) {\n return new AccountManager(new ClientManager({ algod, kmd })).dispenserFromEnvironment();\n}\n\nexport { getDispenserAccount };\n//# sourceMappingURL=get-dispenser-account.mjs.map\n","import algosdk from 'algosdk';\n\n/**\n * @deprecated Use `algorand.account.fromMnemonic(mnemonicSecret)` or `algosdk.mnemonicToSecretKey(mnemonicSecret)` instead.\n *\n * Returns an Algorand account with secret key loaded (i.e. that can sign transactions) by taking the mnemonic secret.\n *\n * This is a wrapper around algosdk.mnemonicToSecretKey to provide a more friendly/obvious name.\n *\n * @param mnemonicSecret The mnemonic secret representing the private key of an account; **Note: Be careful how the mnemonic is handled**,\n * never commit it into source control and ideally load it from the environment (ideally via a secret storage service) rather than the file system.\n */\nfunction mnemonicAccount(mnemonicSecret) {\n // This method is confusingly named, so this function provides a more dev friendly \"wrapper\" name\n return algosdk.mnemonicToSecretKey(mnemonicSecret);\n}\n\nexport { mnemonicAccount };\n//# sourceMappingURL=mnemonic-account.mjs.map\n","import { ClientManager } from '../types/client-manager.mjs';\nimport { KmdAccountManager } from '../types/kmd-account-manager.mjs';\n\n/**\n * @deprecated use `algorand.account.kmd.getWalletAccount(name, predicate)` or `new KMDAccountManager(clientManager).getWalletAccount(name, predicate)` instead.\n *\n * Returns an Algorand account with private key loaded from the given KMD wallet (identified by name).\n *\n * @param walletAccount The details of the wallet, with:\n * * `name`: The name of the wallet to retrieve an account from\n * * `predicate`: An optional filter to use to find the account (otherwise it will return a random account from the wallet)\n * @param algod An algod client\n * @param kmdClient A KMD client, if not specified then a default KMD client will be loaded from environment variables\n * @example Get default funded account in a LocalNet\n *\n * ```typescript\n * const defaultDispenserAccount = await getKmdWalletAccount(algod,\n * 'unencrypted-default-wallet',\n * a => a.status !== 'Offline' && a.amount > 1_000_000_000\n * )\n * ```\n */\nasync function getKmdWalletAccount(walletAccount, algod, kmdClient) {\n return (await new KmdAccountManager(new ClientManager({ algod, kmd: kmdClient })).getWalletAccount(walletAccount.name, walletAccount.predicate))?.account;\n}\n\nexport { getKmdWalletAccount };\n//# sourceMappingURL=get-kmd-wallet-account.mjs.map\n","import { AccountManager } from '../types/account-manager.mjs';\nimport { ClientManager } from '../types/client-manager.mjs';\n\n/**\n * @deprecated Use `algorand.account.kmd.getLocalNetDispenserAccount()` instead.\n *\n * Returns an Algorand account with private key loaded for the default LocalNet dispenser account (that can be used to fund other accounts)\n *\n * @param algod An algod client\n * @param kmd A KMD client, if not specified then a default KMD client will be loaded from environment variables\n */\nasync function getLocalNetDispenserAccount(algod, kmd) {\n return (await new AccountManager(new ClientManager({ algod, kmd })).kmd.getLocalNetDispenserAccount()).account;\n}\n\nexport { getLocalNetDispenserAccount };\n//# sourceMappingURL=get-localnet-dispenser-account.mjs.map\n","import { ClientManager } from '../types/client-manager.mjs';\nimport { KmdAccountManager } from '../types/kmd-account-manager.mjs';\n\n/**\n * @deprecated use `algorand.account.kmd.getOrCreateWalletAccount(name, fundWith)` or `new KMDAccountManager(clientManager).getOrCreateWalletAccount(name, fundWith)` instead.\n *\n * Gets an account with private key loaded from a KMD wallet of the given name, or alternatively creates one with funds in it via a KMD wallet of the given name.\n *\n * This is useful to get idempotent accounts from LocalNet without having to specify the private key (which will change when resetting the LocalNet).\n *\n * This significantly speeds up local dev time and improves experience since you can write code that *just works* first go without manual config in a fresh LocalNet.\n *\n * If this is used via `mnemonicAccountFromEnvironment`, then you can even use the same code that runs on production without changes for local development!\n *\n * @param walletAccount The wallet details with:\n * * `name`: The name of the wallet to retrieve / create\n * * `fundWith`: The number of Algo to fund the account with when it gets created, if not specified then 1000 ALGO will be funded from the dispenser account\n * @param algod An algod client\n * @param kmdClient A KMD client, if not specified then a default KMD client will be loaded from environment variables\n *\n * @returns An Algorand account with private key loaded - either one that already existed in the given KMD wallet, or a new one that is funded for you\n */\nasync function getOrCreateKmdWalletAccount(walletAccount, algod, kmdClient) {\n return (await new KmdAccountManager(new ClientManager({ algod, kmd: kmdClient })).getOrCreateWalletAccount(walletAccount.name, walletAccount.fundWith)).account;\n}\n\nexport { getOrCreateKmdWalletAccount };\n//# sourceMappingURL=get-or-create-kmd-wallet-account.mjs.map\n","import { ClientManager } from '../types/client-manager.mjs';\n\n/** @deprecated Use `await algorand.client.isLocalNet()` or `await new ClientManager({ algod }).isLocalNet()` instead.\n *\n * Returns true if the algod client is pointing to a LocalNet Algorand network\n */\nasync function isLocalNet(algod) {\n return await new ClientManager({ algod }).isLocalNet();\n}\n\nexport { isLocalNet };\n//# sourceMappingURL=is-localnet.mjs.map\n","import { legacySendTransactionBridge } from '../transaction/legacy-bridge.mjs';\nimport { getSenderAddress, encodeTransactionNote } from '../transaction/transaction.mjs';\nimport { AlgorandClient } from '../types/algorand-client.mjs';\nimport { TestNetDispenserApiClient } from '../types/dispenser-client.mjs';\n\n/**\n * @deprecated Use `algorand.account.ensureFunded()` / `algorand.account.ensureFundedFromEnvironment()`\n * / `algorand.account.ensureFundedFromTestNetDispenserApi()` instead\n *\n * Funds a given account using a funding source such that it has a certain amount of Algo free to spend (accounting for Algo locked in minimum balance requirement).\n *\n * https://developer.algorand.org/docs/get-details/accounts/#minimum-balance\n *\n * @param funding The funding configuration of type `EnsureFundedParams`, including the account to fund, minimum spending balance, and optional parameters. If you set `useDispenserApi` to true, you must also set `ALGOKIT_DISPENSER_ACCESS_TOKEN` in your environment variables.\n * @param algod An instance of the Algodv2 client.\n * @param kmd An optional instance of the Kmd client.\n * @returns\n * - `EnsureFundedReturnType` if funds were transferred.\n * - `undefined` if no funds were needed.\n */\nasync function ensureFunded(funding, algod, kmd) {\n const algorand = AlgorandClient.fromClients({ algod, kmd });\n if (funding.fundingSource instanceof TestNetDispenserApiClient) {\n const result = await algorand.account.ensureFundedFromTestNetDispenserApi(getSenderAddress(funding.accountToFund), funding.fundingSource, funding.minSpendingBalance, {\n minFundingIncrement: funding.minFundingIncrement,\n });\n if (!result)\n return undefined;\n return {\n amount: Number(result.amountFunded.microAlgo),\n transactionId: result.transactionId,\n };\n }\n else {\n const sender = funding.fundingSource ?? (await algorand.account.dispenserFromEnvironment());\n algorand.setSignerFromAccount(sender);\n const result = await algorand.account.ensureFunded(getSenderAddress(funding.accountToFund), getSenderAddress(sender), funding.minSpendingBalance, {\n minFundingIncrement: funding.minFundingIncrement,\n note: encodeTransactionNote(funding.note),\n staticFee: funding.fee,\n lease: funding.lease,\n maxFee: funding.maxFee,\n maxRoundsToWaitForConfirmation: funding.maxRoundsToWaitForConfirmation,\n suppressLog: funding.suppressLog,\n });\n return result\n ? {\n amount: Number(result.amountFunded.microAlgo),\n transactionId: result.txIds[0],\n }\n : undefined;\n }\n}\n/**\n * @deprecated Use `algorand.send.assetTransfer()` / `algorand.createTransaction.assetTransfer()` instead\n *\n * Transfer asset between two accounts.\n * @param transfer The transfer definition\n * @param algod An algod client\n * @returns The transaction object and optionally the confirmation if it was sent to the chain (`skipSending` is `false` or unset)\n *\n * @example Usage example\n * ```typescript\n * await algokit.transferAsset({ from, to, assetId, amount }, algod)\n * ```\n */\nasync function transferAsset(transfer, algod) {\n return legacySendTransactionBridge(algod, transfer.from, transfer, {\n assetId: BigInt(transfer.assetId),\n sender: getSenderAddress(transfer.from),\n receiver: getSenderAddress(transfer.to),\n clawbackTarget: transfer.clawbackFrom ? getSenderAddress(transfer.clawbackFrom) : undefined,\n amount: BigInt(transfer.amount),\n note: encodeTransactionNote(transfer.note),\n lease: transfer.lease,\n }, (c) => c.assetTransfer, (c) => c.assetTransfer);\n}\n/**\n * @deprecated Use `algorand.account.rekeyAccount()` instead\n *\n * Rekey an account to a new address.\n *\n * **Note:** Please be careful with this function and be sure to read the [official rekey guidance](https://developer.algorand.org/docs/get-details/accounts/rekey/).\n *\n * @param rekey The rekey definition\n * @param algod An algod client\n * @returns The transaction object and optionally the confirmation if it was sent to the chain (`skipSending` is `false` or unset)\n *\n * @example Usage example\n * ```typescript\n * await algokit.rekeyAccount({ from, rekeyTo }, algod)\n * ```\n */\nasync function rekeyAccount(rekey, algod) {\n return legacySendTransactionBridge(algod, rekey.from, rekey, {\n sender: getSenderAddress(rekey.from),\n receiver: getSenderAddress(rekey.from),\n amount: (0).microAlgo(),\n rekeyTo: typeof rekey.rekeyTo === 'string' ? rekey.rekeyTo : getSenderAddress(rekey.rekeyTo),\n note: encodeTransactionNote(rekey.note),\n lease: rekey.lease,\n }, (c) => c.payment, (c) => c.payment);\n}\n\nexport { ensureFunded, rekeyAccount, transferAsset };\n//# sourceMappingURL=transfer.mjs.map\n","import { legacySendTransactionBridge } from '../transaction/legacy-bridge.mjs';\nimport { getSenderAddress, encodeTransactionNote } from '../transaction/transaction.mjs';\n\n/**\n * @deprecated Use `algorand.send.payment()` / `algorand.createTransaction.payment()` instead\n *\n * Transfer Algo between two accounts.\n * @param transfer The transfer definition\n * @param algod An algod client\n * @returns The transaction object and optionally the confirmation if it was sent to the chain (`skipSending` is `false` or unset)\n *\n * @example Usage example\n * ```typescript\n * await algokit.transferAlgos({ from, to, amount: algokit.algo(1) }, algod)\n * ```\n */\nasync function transferAlgos(transfer, algod) {\n const params = {\n sender: getSenderAddress(transfer.from),\n receiver: getSenderAddress(transfer.to),\n amount: transfer.amount,\n note: encodeTransactionNote(transfer.note),\n lease: transfer.lease,\n };\n return await legacySendTransactionBridge(algod, transfer.from, transfer, params, (c) => c.payment, (c) => c.payment);\n}\n\nexport { transferAlgos };\n//# sourceMappingURL=transfer-algos.mjs.map\n","export { callApp, compileTeal, createApp, decodeAppState, getABIMethodSignature, getABIReturn, getAppArgsForABICall, getAppArgsForTransaction, getAppBoxNames, getAppBoxValue, getAppBoxValueFromABIType, getAppBoxValues, getAppBoxValuesFromABIType, getAppById, getAppGlobalState, getAppLocalState, getAppOnCompleteAction, getBoxReference, updateApp } from './app.mjs';\nexport { getAppClient, getAppClientByCreatorAndName, getAppClientById } from './app-client.mjs';\nexport { deployApp, getAppDeploymentTransactionNote, getCreatorAppsByName, isSchemaIsBroken, performTemplateSubstitution, performTemplateSubstitutionAndCompile, replaceDeployTimeControlParams, stripTealComments } from './app-deploy.mjs';\nexport { assetBulkOptIn, assetBulkOptOut, assetOptIn, assetOptOut, createAsset } from './asset.mjs';\nexport { getTestNetDispenserApiClient } from './dispenser-client.mjs';\nimport * as indexerLookup from './indexer-lookup.mjs';\nexport { indexerLookup as indexer };\nexport { executePaginatedRequest, lookupAccountByAddress, lookupAccountCreatedApplicationByAddress, lookupAssetHoldings, lookupTransactionById, searchTransactions } from './indexer-lookup.mjs';\nexport { getAlgoClient, getAlgoIndexerClient, getAlgoKmdClient, getAlgoNodeConfig, getAlgodConfigFromEnvironment, getConfigFromEnvOrDefaults, getDefaultLocalNetConfig, getIndexerConfigFromEnvironment, isMainNet, isTestNet } from './network-client.mjs';\nexport { algo, algos, microAlgo, microAlgos, transactionFees } from './amount.mjs';\nexport { Config } from './config.mjs';\nexport { AlgorandClient } from './types/algorand-client.mjs';\nexport { ALGOKIT_DIR, DEFAULT_MAX_SEARCH_DEPTH, SOURCES_DIR, TEAL_FILE_EXT, TEAL_SOURCEMAP_EXT } from './types/debugging.mjs';\nexport { EventType } from './types/lifecycle-events.mjs';\nexport { getAccountAddressAsString, getAccountAddressAsUint8Array, getAccountAssetInformation, getAccountInformation, mnemonicAccountFromEnvironment, multisigAccount, randomAccount, rekeyedAccount, transactionSignerAccount } from './account/account.mjs';\nexport { getAccount } from './account/get-account.mjs';\nexport { getAccountConfigFromEnvironment } from './account/get-account-config-from-environment.mjs';\nexport { getDispenserAccount } from './account/get-dispenser-account.mjs';\nexport { mnemonicAccount } from './account/mnemonic-account.mjs';\nexport { getKmdWalletAccount } from './localnet/get-kmd-wallet-account.mjs';\nexport { getLocalNetDispenserAccount } from './localnet/get-localnet-dispenser-account.mjs';\nexport { getOrCreateKmdWalletAccount } from './localnet/get-or-create-kmd-wallet-account.mjs';\nexport { isLocalNet } from './localnet/is-localnet.mjs';\nexport { ensureFunded, rekeyAccount, transferAsset } from './transfer/transfer.mjs';\nexport { transferAlgos } from './transfer/transfer-algos.mjs';\nexport { persistSourceMaps } from './debugging/debugging.mjs';\nexport { performAtomicTransactionComposerSimulate } from './transaction/perform-atomic-transaction-composer-simulate.mjs';\nexport { MAX_APP_CALL_ACCOUNT_REFERENCES, MAX_APP_CALL_FOREIGN_REFERENCES, MAX_TRANSACTION_GROUP_SIZE, capTransactionFee, controlFees, encodeLease, encodeTransactionNote, getABIReturnValue, getAtomicTransactionComposerTransactions, getSenderAddress, getSenderTransactionSigner, getTransactionParams, getTransactionWithSigner, performAtomicTransactionComposerDryrun, populateAppCallResources, sendAtomicTransactionComposer, sendGroupOfTransactions, sendTransaction, signTransaction, waitForConfirmation } from './transaction/transaction.mjs';\n//# sourceMappingURL=index.mjs.map\n","// src/mutation.ts\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Removable } from \"./removable.js\";\nimport { createRetryer } from \"./retryer.js\";\nvar Mutation = class extends Removable {\n #observers;\n #mutationCache;\n #retryer;\n constructor(config) {\n super();\n this.mutationId = config.mutationId;\n this.#mutationCache = config.mutationCache;\n this.#observers = [];\n this.state = config.state || getDefaultState();\n this.setOptions(config.options);\n this.scheduleGc();\n }\n setOptions(options) {\n this.options = options;\n this.updateGcTime(this.options.gcTime);\n }\n get meta() {\n return this.options.meta;\n }\n addObserver(observer) {\n if (!this.#observers.includes(observer)) {\n this.#observers.push(observer);\n this.clearGcTimeout();\n this.#mutationCache.notify({\n type: \"observerAdded\",\n mutation: this,\n observer\n });\n }\n }\n removeObserver(observer) {\n this.#observers = this.#observers.filter((x) => x !== observer);\n this.scheduleGc();\n this.#mutationCache.notify({\n type: \"observerRemoved\",\n mutation: this,\n observer\n });\n }\n optionalRemove() {\n if (!this.#observers.length) {\n if (this.state.status === \"pending\") {\n this.scheduleGc();\n } else {\n this.#mutationCache.remove(this);\n }\n }\n }\n continue() {\n return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before\n this.execute(this.state.variables);\n }\n async execute(variables) {\n this.#retryer = createRetryer({\n fn: () => {\n if (!this.options.mutationFn) {\n return Promise.reject(new Error(\"No mutationFn found\"));\n }\n return this.options.mutationFn(variables);\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: \"failed\", failureCount, error });\n },\n onPause: () => {\n this.#dispatch({ type: \"pause\" });\n },\n onContinue: () => {\n this.#dispatch({ type: \"continue\" });\n },\n retry: this.options.retry ?? 0,\n retryDelay: this.options.retryDelay,\n networkMode: this.options.networkMode,\n canRun: () => this.#mutationCache.canRun(this)\n });\n const restored = this.state.status === \"pending\";\n const isPaused = !this.#retryer.canStart();\n try {\n if (!restored) {\n this.#dispatch({ type: \"pending\", variables, isPaused });\n await this.#mutationCache.config.onMutate?.(\n variables,\n this\n );\n const context = await this.options.onMutate?.(variables);\n if (context !== this.state.context) {\n this.#dispatch({\n type: \"pending\",\n context,\n variables,\n isPaused\n });\n }\n }\n const data = await this.#retryer.start();\n await this.#mutationCache.config.onSuccess?.(\n data,\n variables,\n this.state.context,\n this\n );\n await this.options.onSuccess?.(data, variables, this.state.context);\n await this.#mutationCache.config.onSettled?.(\n data,\n null,\n this.state.variables,\n this.state.context,\n this\n );\n await this.options.onSettled?.(data, null, variables, this.state.context);\n this.#dispatch({ type: \"success\", data });\n return data;\n } catch (error) {\n try {\n await this.#mutationCache.config.onError?.(\n error,\n variables,\n this.state.context,\n this\n );\n await this.options.onError?.(\n error,\n variables,\n this.state.context\n );\n await this.#mutationCache.config.onSettled?.(\n void 0,\n error,\n this.state.variables,\n this.state.context,\n this\n );\n await this.options.onSettled?.(\n void 0,\n error,\n variables,\n this.state.context\n );\n throw error;\n } finally {\n this.#dispatch({ type: \"error\", error });\n }\n } finally {\n this.#mutationCache.runNext(this);\n }\n }\n #dispatch(action) {\n const reducer = (state) => {\n switch (action.type) {\n case \"failed\":\n return {\n ...state,\n failureCount: action.failureCount,\n failureReason: action.error\n };\n case \"pause\":\n return {\n ...state,\n isPaused: true\n };\n case \"continue\":\n return {\n ...state,\n isPaused: false\n };\n case \"pending\":\n return {\n ...state,\n context: action.context,\n data: void 0,\n failureCount: 0,\n failureReason: null,\n error: null,\n isPaused: action.isPaused,\n status: \"pending\",\n variables: action.variables,\n submittedAt: Date.now()\n };\n case \"success\":\n return {\n ...state,\n data: action.data,\n failureCount: 0,\n failureReason: null,\n error: null,\n status: \"success\",\n isPaused: false\n };\n case \"error\":\n return {\n ...state,\n data: void 0,\n error: action.error,\n failureCount: state.failureCount + 1,\n failureReason: action.error,\n isPaused: false,\n status: \"error\"\n };\n }\n };\n this.state = reducer(this.state);\n notifyManager.batch(() => {\n this.#observers.forEach((observer) => {\n observer.onMutationUpdate(action);\n });\n this.#mutationCache.notify({\n mutation: this,\n type: \"updated\",\n action\n });\n });\n }\n};\nfunction getDefaultState() {\n return {\n context: void 0,\n data: void 0,\n error: null,\n failureCount: 0,\n failureReason: null,\n isPaused: false,\n status: \"idle\",\n variables: void 0,\n submittedAt: 0\n };\n}\nexport {\n Mutation,\n getDefaultState\n};\n//# sourceMappingURL=mutation.js.map","import algosdk from 'algosdk';\n\nvar ABIMethod = algosdk.ABIMethod;\nfunction arc32ToArc56(appSpec) {\n const arc32Structs = Object.values(appSpec.hints).flatMap((hint) => Object.entries(hint.structs ?? {}));\n const structs = Object.fromEntries(arc32Structs.map(([_, struct]) => {\n const fields = struct.elements.map((e) => ({ name: e[0], type: e[1] }));\n return [struct.name, fields];\n }));\n const hint = (m) => appSpec.hints[new ABIMethod(m).getSignature()];\n const actions = (m, type) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain\n return hint(m)?.call_config !== undefined ? callConfigToActions(hint(m)?.call_config, type) : [];\n };\n const bareActions = (type) => {\n return callConfigToActions(appSpec.bare_call_config, type);\n };\n const callConfigToActions = (c, type) => {\n const actions = [];\n if (c.close_out && ['ALL', type].includes(c.close_out))\n actions.push('CloseOut');\n if (c.delete_application && ['ALL', type].includes(c.delete_application))\n actions.push('DeleteApplication');\n if (c.no_op && ['ALL', type].includes(c.no_op))\n actions.push('NoOp');\n if (c.opt_in && ['ALL', type].includes(c.opt_in))\n actions.push('OptIn');\n if (c.update_application && ['ALL', type].includes(c.update_application))\n actions.push('UpdateApplication');\n return actions;\n };\n const getDefaultArgValue = (type, defaultArg) => {\n if (!defaultArg)\n return undefined;\n if (defaultArg.source === 'abi-method') {\n return {\n source: 'method',\n data: defaultArg.data.name,\n };\n }\n return {\n source: defaultArg.source === 'constant' ? 'literal' : defaultArg.source === 'global-state' ? 'global' : 'local',\n data: Buffer.from(typeof defaultArg.data === 'number' ? algosdk.ABIType.from('uint64').encode(defaultArg.data) : defaultArg.data).toString('base64'),\n type: type === 'string' ? 'AVMString' : type,\n };\n };\n return {\n arcs: [],\n name: appSpec.contract.name,\n desc: appSpec.contract.desc,\n structs: structs,\n methods: appSpec.contract.methods.map((m) => ({\n name: m.name,\n desc: m.desc,\n args: m.args.map((a) => ({\n name: a.name,\n type: a.type,\n desc: a.desc,\n struct: a.name ? hint(m)?.structs?.[a.name]?.name : undefined,\n defaultValue: getDefaultArgValue(a.type, !a.name ? undefined : hint(m)?.default_arguments?.[a.name]),\n })),\n returns: {\n type: m.returns.type,\n desc: m.returns.desc,\n struct: hint(m)?.structs?.output?.name,\n },\n events: [],\n readonly: hint(m)?.read_only,\n actions: {\n create: actions(m, 'CREATE'),\n call: actions(m, 'CALL'),\n },\n })),\n state: {\n schema: {\n global: {\n ints: appSpec.state.global.num_uints,\n bytes: appSpec.state.global.num_byte_slices,\n },\n local: {\n ints: appSpec.state.local.num_uints,\n bytes: appSpec.state.local.num_byte_slices,\n },\n },\n keys: {\n global: Object.fromEntries(Object.entries(appSpec.schema.global.declared).map((s) => [\n s[0],\n {\n key: Buffer.from(s[1].key, 'utf-8').toString('base64'),\n keyType: 'AVMString',\n valueType: s[1].type === 'uint64' ? 'AVMUint64' : 'AVMBytes',\n desc: s[1].descr,\n },\n ])),\n local: Object.fromEntries(Object.entries(appSpec.schema.local.declared).map((s) => [\n s[0],\n {\n key: Buffer.from(s[1].key, 'utf-8').toString('base64'),\n keyType: 'AVMString',\n valueType: s[1].type === 'uint64' ? 'AVMUint64' : 'AVMBytes',\n desc: s[1].descr,\n },\n ])),\n box: {},\n },\n maps: {\n global: {},\n local: {},\n box: {},\n },\n },\n source: appSpec.source,\n bareActions: {\n create: bareActions('CREATE'),\n call: bareActions('CALL'),\n },\n byteCode: undefined,\n compilerInfo: undefined,\n events: undefined,\n networks: undefined,\n scratchVariables: undefined,\n sourceInfo: undefined,\n templateVariables: undefined,\n };\n}\n\nexport { arc32ToArc56 };\n//# sourceMappingURL=app-spec.mjs.map\n","const LOGIC_ERROR = /transaction ([A-Z0-9]+): logic eval error: (.*). Details: .*pc=([0-9]+).*/;\n/** Wraps key functionality around processing logic errors */\nclass LogicError extends Error {\n /** Takes an error message and parses out the details of any logic errors in there.\n * @param error The error message to parse\n * @returns The logic error details if any, or undefined\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static parseLogicError(error) {\n const errorMessage = error.message;\n const res = LOGIC_ERROR.exec(errorMessage);\n if (res === null || res.length <= 3)\n return undefined;\n return {\n txId: res[1],\n msg: res[2],\n desc: errorMessage,\n pc: parseInt(res[3] ? res[3] : '0'),\n traces: error.traces,\n };\n }\n /**\n * Create a new logic error object.\n * @param errorDetails The details of the logic error\n * @param program The TEAL source code, split by line\n * @param getLineForPc The source map of the TEAL source code\n */\n constructor(errorDetails, program, getLineForPc) {\n super();\n this.lines = 5;\n this.teal_line = 0;\n this.led = errorDetails;\n this.program = program;\n const line = getLineForPc(errorDetails.pc);\n this.teal_line = line === undefined ? 0 : line;\n this.message = `${this.led.msg}. at:${line}. ${this.led.desc}`;\n if (this.teal_line > 0) {\n const start = this.teal_line > this.lines ? this.teal_line - this.lines : 0;\n const stop = program.length > this.teal_line + this.lines ? this.teal_line + this.lines : program.length;\n const stack_lines = program.slice(start, stop);\n stack_lines[stack_lines.length / 2] += ' <--- Error';\n this.stack = stack_lines.join('\\n');\n }\n }\n}\n\nexport { LogicError };\n//# sourceMappingURL=logic-error.mjs.map\n","import algosdk from 'algosdk';\nimport { Buffer } from 'buffer';\nimport { compileTeal, createApp, updateApp, callApp, getAppGlobalState, getAppLocalState, getAppBoxNames, getAppBoxValue, getAppBoxValueFromABIType } from '../app.mjs';\nimport { replaceDeployTimeControlParams, performTemplateSubstitution, deployApp, getCreatorAppsByName } from '../app-deploy.mjs';\nimport { Config } from '../config.mjs';\nimport { legacySendTransactionBridge } from '../transaction/legacy-bridge.mjs';\nimport { getSenderAddress, encodeTransactionNote } from '../transaction/transaction.mjs';\nimport { asJson, binaryStartsWith } from '../util.mjs';\nimport { UPDATABLE_TEMPLATE_NAME, DELETABLE_TEMPLATE_NAME } from './app.mjs';\nimport { getArc56Method, getArc56ReturnValue, getABITupleFromABIStruct, getABIDecodedValue, getABIEncodedValue } from './app-arc56.mjs';\nimport { arc32ToArc56 } from './app-spec.mjs';\nimport { EventType } from './lifecycle-events.mjs';\nimport { LogicError } from './logic-error.mjs';\n\nvar ABIMethod = algosdk.ABIMethod;\nvar AtomicTransactionComposer = algosdk.AtomicTransactionComposer;\nvar getApplicationAddress = algosdk.getApplicationAddress;\nvar Indexer = algosdk.Indexer;\nvar OnApplicationComplete = algosdk.OnApplicationComplete;\nvar SourceMap = algosdk.SourceMap;\n/**\n * Determines deploy time control (UPDATABLE, DELETABLE) value by inspecting application specification\n * @param approval TEAL Approval program, not the base64 version found on the appSpec\n * @param appSpec Application Specification\n * @param templateVariableName Template variable\n * @param callConfigKey Call config type\n * @returns true if applicable call config is found, false if not found or undefined if variable not present\n */\nfunction getDeployTimeControl(approval, appSpec, templateVariableName, callConfigKey) {\n // variable not present, so unknown control value\n if (!approval.includes(templateVariableName))\n return undefined;\n // a bare call for specified CallConfig is present and configured\n const bareCallConfig = appSpec.bare_call_config[callConfigKey];\n if (!!bareCallConfig && bareCallConfig !== 'NEVER')\n return true;\n // an ABI call for specified CallConfig is present and configured\n return Object.values(appSpec.hints).some((h) => {\n const abiCallConfig = h.call_config[callConfigKey];\n return !!abiCallConfig && abiCallConfig !== 'NEVER';\n });\n}\nconst BYTE_CBLOCK = 38;\nconst INT_CBLOCK = 32;\n/**\n * Get the offset of the last constant block at the beginning of the program\n * This value is used to calculate the program counter for an ARC56 program that has a pcOffsetMethod of \"cblocks\"\n *\n * @param program The program to parse\n * @returns The PC value of the opcode after the last constant block\n */\nfunction getConstantBlockOffset(program) {\n const bytes = [...program];\n const programSize = bytes.length;\n bytes.shift(); // remove version\n /** The PC of the opcode after the bytecblock */\n let bytecblockOffset;\n /** The PC of the opcode after the intcblock */\n let intcblockOffset;\n while (bytes.length > 0) {\n /** The current byte from the beginning of the byte array */\n const byte = bytes.shift();\n // If the byte is a constant block...\n if (byte === BYTE_CBLOCK || byte === INT_CBLOCK) {\n const isBytecblock = byte === BYTE_CBLOCK;\n /** The byte following the opcode is the number of values in the constant block */\n const valuesRemaining = bytes.shift();\n // Iterate over all the values in the constant block\n for (let i = 0; i < valuesRemaining; i++) {\n if (isBytecblock) {\n /** The byte following the opcode is the length of the next element */\n const length = bytes.shift();\n bytes.splice(0, length);\n }\n else {\n // intcblock is a uvarint, so we need to keep reading until we find the end (MSB is not set)\n while ((bytes.shift() & 0x80) !== 0) {\n // Do nothing...\n }\n }\n }\n if (isBytecblock)\n bytecblockOffset = programSize - bytes.length - 1;\n else\n intcblockOffset = programSize - bytes.length - 1;\n if (bytes[0] !== BYTE_CBLOCK && bytes[0] !== INT_CBLOCK) {\n // if the next opcode isn't a constant block, we're done\n break;\n }\n }\n }\n return Math.max(bytecblockOffset ?? 0, intcblockOffset ?? 0);\n}\n/** ARC-56/ARC-32 application client that allows you to manage calls and\n * state for a specific deployed instance of an app (with a known app ID). */\nclass AppClient {\n constructor(params) {\n this._appId = params.appId;\n this._appAddress = algosdk.getApplicationAddress(this._appId);\n this._appSpec = AppClient.normaliseAppSpec(params.appSpec);\n this._appName = params.appName ?? this._appSpec.name;\n this._algorand = params.algorand;\n this._defaultSender = params.defaultSender;\n this._defaultSigner = params.defaultSigner;\n this._approvalSourceMap = params.approvalSourceMap;\n this._clearSourceMap = params.clearSourceMap;\n this._localStateMethods = (address) => this.getStateMethods(() => this.getLocalState(address), () => this._appSpec.state.keys.local, () => this._appSpec.state.maps.local);\n this._globalStateMethods = this.getStateMethods(() => this.getGlobalState(), () => this._appSpec.state.keys.global, () => this._appSpec.state.maps.global);\n this._boxStateMethods = this.getBoxMethods();\n this._paramsMethods = {\n ...this.getMethodCallParamsMethods(),\n /** Get parameters to define bare (raw) transactions to the current app */\n bare: this.getBareParamsMethods(),\n };\n this._createTransactionsMethods = {\n ...this.getMethodCallCreateTransactionMethods(),\n /** Get transactions for bare (raw) calls to the current app */\n bare: this.getBareCreateTransactionMethods(),\n };\n this._sendMethods = {\n ...this.getMethodCallSendMethods(),\n /** Send bare (raw) transactions to the current app */\n bare: this.getBareSendMethods(),\n };\n }\n /**\n * Clone this app client with different params\n *\n * @param params The params to use for the the cloned app client. Omit a param to keep the original value. Set a param to override the original value. Setting to undefined will clear the original value.\n * @returns A new app client with the altered params\n */\n clone(params) {\n return new AppClient({\n appId: this._appId,\n appSpec: this._appSpec,\n algorand: this._algorand,\n appName: this._appName,\n defaultSender: this._defaultSender,\n defaultSigner: this._defaultSigner,\n approvalSourceMap: this._approvalSourceMap,\n clearSourceMap: this._clearSourceMap,\n ...params,\n });\n }\n /**\n * Returns a new `AppClient` client, resolving the app by creator address and name\n * using AlgoKit app deployment semantics (i.e. looking for the app creation transaction note).\n * @param params The parameters to create the app client\n */\n static async fromCreatorAndName(params) {\n const appSpec = AppClient.normaliseAppSpec(params.appSpec);\n const appLookup = params.appLookupCache ?? (await params.algorand.appDeployer.getCreatorAppsByName(params.creatorAddress, params.ignoreCache));\n const appMetadata = appLookup.apps[params.appName ?? appSpec.name];\n if (!appMetadata) {\n throw new Error(`App not found for creator ${params.creatorAddress} and name ${params.appName ?? appSpec.name}`);\n }\n return new AppClient({\n ...params,\n algorand: params.algorand,\n appId: appMetadata.appId,\n });\n }\n /**\n * Returns an `AppClient` instance for the current network based on\n * pre-determined network-specific app IDs specified in the ARC-56 app spec.\n *\n * If no IDs are in the app spec or the network isn't recognised, an error is thrown.\n * @param params The parameters to create the app client\n */\n static async fromNetwork(params) {\n const network = await params.algorand.client.network();\n const appSpec = AppClient.normaliseAppSpec(params.appSpec);\n const networkNames = [network.genesisHash];\n if (network.isLocalNet)\n networkNames.push('localnet');\n if (network.isTestNet)\n networkNames.push('testnet');\n if (network.isMainNet)\n networkNames.push('mainnet');\n const availableAppSpecNetworks = Object.keys(appSpec.networks ?? {});\n const networkIndex = availableAppSpecNetworks.findIndex((n) => networkNames.includes(n));\n if (networkIndex === -1) {\n throw new Error(`No app ID found for network ${asJson(networkNames)} in the app spec`);\n }\n const appId = BigInt(appSpec.networks[networkIndex].appID);\n return new AppClient({ ...params, appId, appSpec });\n }\n /**\n * Takes a string or parsed JSON object that could be ARC-32 or ARC-56 format and\n * normalises it into a parsed ARC-56 contract object.\n * @param spec The spec to normalise\n * @returns The normalised ARC-56 contract object\n */\n static normaliseAppSpec(spec) {\n const parsedSpec = typeof spec === 'string' ? JSON.parse(spec) : spec;\n const appSpec = 'hints' in parsedSpec ? arc32ToArc56(parsedSpec) : parsedSpec;\n return appSpec;\n }\n /** The ID of the app instance this client is linked to. */\n get appId() {\n return this._appId;\n }\n /** The app address of the app instance this client is linked to. */\n get appAddress() {\n return this._appAddress;\n }\n /** The name of the app (from the ARC-32 / ARC-56 app spec). */\n get appName() {\n return this._appName;\n }\n /** The ARC-56 app spec being used */\n get appSpec() {\n return this._appSpec;\n }\n /** A reference to the underlying `AlgorandClient` this app client is using. */\n get algorand() {\n return this._algorand;\n }\n /** Get parameters to create transactions for the current app.\n *\n * A good mental model for this is that these parameters represent a deferred transaction creation.\n * @example Create a transaction in the future using Algorand Client\n * ```typescript\n * const myMethodCall = appClient.params.call({method: 'my_method', args: [123, 'hello']})\n * // ...\n * await algorand.send.AppMethodCall(myMethodCall)\n * ```\n * @example Define a nested transaction as an ABI argument\n * ```typescript\n * const myMethodCall = appClient.params.call({method: 'my_method', args: [123, 'hello']})\n * await appClient.send.call({method: 'my_method2', args: [myMethodCall]})\n * ```\n */\n get params() {\n return this._paramsMethods;\n }\n /** Create transactions for the current app */\n get createTransaction() {\n return this._createTransactionsMethods;\n }\n /** Send transactions to the current app */\n get send() {\n return this._sendMethods;\n }\n /** Get state (local, global, box) from the current app */\n get state() {\n return {\n /**\n * Methods to access local state for the current app\n * @param address The address of the account to get the local state for\n */\n local: this._localStateMethods,\n /**\n * Methods to access global state for the current app\n */\n global: this._globalStateMethods,\n /**\n * Methods to access box storage for the current app\n */\n box: this._boxStateMethods,\n };\n }\n /**\n * Funds Algo into the app account for this app.\n *\n * An alias for `appClient.send.fundAppAccount(params)`.\n * @param params The parameters for the funding transaction\n * @returns The result of the funding\n */\n async fundAppAccount(params) {\n return this.send.fundAppAccount(params);\n }\n /**\n * Returns raw global state for the current app.\n * @returns The global state\n */\n async getGlobalState() {\n return await this._algorand.app.getGlobalState(this.appId);\n }\n /**\n * Returns raw local state for the given account address.\n * @param address The address of the account to get the local state for\n * @returns The local state\n */\n async getLocalState(address) {\n return await this._algorand.app.getLocalState(this.appId, address);\n }\n /**\n * Returns the names of all current boxes for the current app.\n * @returns The names of the boxes\n */\n async getBoxNames() {\n return await this._algorand.app.getBoxNames(this.appId);\n }\n /**\n * Returns the value of the given box for the current app.\n * @param name The identifier of the box to return\n * @returns The current box value as a byte array\n */\n async getBoxValue(name) {\n return await this._algorand.app.getBoxValue(this.appId, name);\n }\n /**\n * Returns the value of the given box for the current app.\n * @param name The identifier of the box to return\n * @param type\n * @returns The current box value as a byte array\n */\n async getBoxValueFromABIType(name, type) {\n return await this._algorand.app.getBoxValueFromABIType({\n appId: this.appId,\n boxName: name,\n type,\n });\n }\n /**\n * Returns the values of all current boxes for the current app.\n * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n * @param filter Optional filter to filter which boxes' values are returned\n * @returns The (name, value) pair of the boxes with values as raw byte arrays\n */\n async getBoxValues(filter) {\n const names = (await this.getBoxNames()).filter(filter ?? ((_) => true));\n const values = await this._algorand.app.getBoxValues(this.appId, names.map((name) => name.nameRaw));\n return names.map((name, i) => ({ name, value: values[i] }));\n }\n /**\n * Returns the values of all current boxes for the current app decoded using an ABI Type.\n * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n * @param type The ABI type to decode the values with\n * @param filter Optional filter to filter which boxes' values are returned\n * @returns The (name, value) pair of the boxes with values as the ABI Value\n */\n async getBoxValuesFromABIType(type, filter) {\n const names = (await this.getBoxNames()).filter(filter ?? ((_) => true));\n const values = await this._algorand.app.getBoxValuesFromABIType({\n appId: this.appId,\n boxNames: names.map((name) => name.nameRaw),\n type,\n });\n return names.map((name, i) => ({ name, value: values[i] }));\n }\n /**\n * Takes an error that may include a logic error from a call to the current app and re-exposes the\n * error to include source code information via the source map and ARC-56 spec.\n * @param e The error to parse\n * @param isClearStateProgram Whether or not the code was running the clear state program (defaults to approval program)\n * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n */\n async exposeLogicError(e, isClearStateProgram) {\n const pcOffsetMethod = this._appSpec.sourceInfo?.[isClearStateProgram ? 'clear' : 'approval']?.pcOffsetMethod;\n let program;\n if (pcOffsetMethod === 'cblocks') {\n // TODO: Cache this if we deploy the app and it's not updateable\n const appInfo = await this._algorand.app.getById(this.appId);\n program = isClearStateProgram ? appInfo.clearStateProgram : appInfo.approvalProgram;\n }\n return AppClient.exposeLogicError(e, this._appSpec, {\n isClearStateProgram,\n approvalSourceMap: this._approvalSourceMap,\n clearSourceMap: this._clearSourceMap,\n program,\n });\n }\n /**\n * Export the current source maps for the app.\n * @returns The source maps\n */\n exportSourceMaps() {\n if (!this._approvalSourceMap || !this._clearSourceMap) {\n throw new Error(\"Unable to export source maps; they haven't been loaded into this client - you need to call create, update, or deploy first\");\n }\n return {\n approvalSourceMap: this._approvalSourceMap,\n clearSourceMap: this._clearSourceMap,\n };\n }\n /**\n * Import source maps for the app.\n * @param sourceMaps The source maps to import\n */\n importSourceMaps(sourceMaps) {\n this._approvalSourceMap = new SourceMap(sourceMaps.approvalSourceMap);\n this._clearSourceMap = new SourceMap(sourceMaps.clearSourceMap);\n }\n /**\n * Returns the ABI Method spec for the given method string for the app represented by this application client instance\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @returns A tuple with: [ARC-56 `Method`, algosdk `ABIMethod`]\n */\n getABIMethod(methodNameOrSignature) {\n return getArc56Method(methodNameOrSignature, this._appSpec);\n }\n /**\n * Checks for decode errors on the SendAppTransactionResult and maps the return value to the specified type\n * on the ARC-56 method, replacing the `return` property with the decoded type.\n *\n * If the return type is an ARC-56 struct then the struct will be returned.\n *\n * @param result The SendAppTransactionResult to be mapped\n * @param method The method that was called\n * @returns The smart contract response with an updated return value\n */\n async processMethodCallReturn(result, method) {\n const resultValue = await result;\n return { ...resultValue, return: getArc56ReturnValue(resultValue.return, method, this._appSpec.structs) };\n }\n /**\n * Compiles the approval and clear state programs (if TEAL templates provided),\n * performing any provided deploy-time parameter replacement and stores\n * the source maps.\n *\n * If no TEAL templates provided it will use any byte code provided in the app spec.\n *\n * Will store any generated source maps for later use in debugging.\n */\n async compile(compilation) {\n const result = await AppClient.compile(this._appSpec, this._algorand.app, compilation);\n if (result.compiledApproval) {\n this._approvalSourceMap = result.compiledApproval.sourceMap;\n }\n if (result.compiledClear) {\n this._clearSourceMap = result.compiledClear.sourceMap;\n }\n return result;\n }\n /**\n * Takes an error that may include a logic error from a call to the current app and re-exposes the\n * error to include source code information via the source map and ARC-56 spec.\n * @param e The error to parse\n * @param appSpec The app spec for the app\n * @param details Additional information to inform the error\n * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n */\n static exposeLogicError(e, appSpec, details) {\n const { isClearStateProgram, approvalSourceMap, clearSourceMap, program } = details;\n const sourceMap = isClearStateProgram ? clearSourceMap : approvalSourceMap;\n const errorDetails = LogicError.parseLogicError(e);\n // Return the error if we don't have a PC\n if (errorDetails === undefined || errorDetails?.pc === undefined)\n return e;\n /** The PC value to find in the ARC56 SourceInfo */\n let arc56Pc = errorDetails?.pc;\n const programSourceInfo = isClearStateProgram ? appSpec.sourceInfo?.clear : appSpec.sourceInfo?.approval;\n /** The offset to apply to the PC if using the cblocks pc offset method */\n let cblocksOffset = 0;\n // If the program uses cblocks offset, then we need to adjust the PC accordingly\n if (programSourceInfo?.pcOffsetMethod === 'cblocks') {\n if (program === undefined)\n throw new Error('Program bytes are required to calculate the ARC56 cblocks PC offset');\n cblocksOffset = getConstantBlockOffset(program);\n arc56Pc = errorDetails.pc - cblocksOffset;\n }\n // Find the source info for this PC and get the error message\n const sourceInfo = programSourceInfo?.sourceInfo.find((s) => s.pc.includes(arc56Pc));\n const errorMessage = sourceInfo?.errorMessage;\n // If we have the source we can display the TEAL in the error message\n if (appSpec.source) {\n let getLineForPc = (inputPc) => sourceMap?.getLineForPc?.(inputPc);\n // If the SourceMap is not defined, we need to provide our own function for going from a PC to TEAL based on ARC56 SourceInfo[]\n if (sourceMap === undefined) {\n getLineForPc = (inputPc) => {\n const teal = programSourceInfo?.sourceInfo.find((s) => s.pc.includes(inputPc - cblocksOffset))?.teal;\n if (teal === undefined)\n return undefined;\n return teal - 1;\n };\n }\n e = new LogicError(errorDetails, Buffer.from(isClearStateProgram ? appSpec.source.clear : appSpec.source.approval, 'base64')\n .toString()\n .split('\\n'), \n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n getLineForPc);\n }\n if (errorMessage) {\n const appId = asJson(e).match(/(?<=app=)\\d+/)?.[0] || '';\n const txId = asJson(e).match(/(?<=transaction )\\S+(?=:)/)?.[0];\n const error = new Error(`Runtime error when executing ${appSpec.name} (appId: ${appId}) in transaction ${txId}: ${errorMessage}`);\n error.cause = e;\n return error;\n }\n return e;\n }\n /**\n * Compiles the approval and clear state programs (if TEAL templates provided),\n * performing any provided deploy-time parameter replacement and returns\n * the compiled code and any compilation results (including source maps).\n *\n * If no TEAL templates provided it will use any byte code provided in the app spec.\n *\n * Will store any generated source maps for later use in debugging.\n * @param appSpec The app spec for the app\n * @param compilation Any compilation parameters to use\n */\n static async compile(appSpec, appManager, compilation) {\n const { deployTimeParams, updatable, deletable } = compilation ?? {};\n if (!appSpec.source) {\n if (!appSpec.byteCode?.approval || !appSpec.byteCode?.clear) {\n throw new Error(`Attempt to compile app ${appSpec.name} without source or byteCode`);\n }\n return {\n approvalProgram: Buffer.from(appSpec.byteCode.approval, 'base64'),\n clearStateProgram: Buffer.from(appSpec.byteCode.clear, 'base64'),\n };\n }\n const approvalTemplate = Buffer.from(appSpec.source.approval, 'base64').toString('utf-8');\n const compiledApproval = await appManager.compileTealTemplate(approvalTemplate, deployTimeParams, {\n updatable,\n deletable,\n });\n const clearTemplate = Buffer.from(appSpec.source.clear, 'base64').toString('utf-8');\n const compiledClear = await appManager.compileTealTemplate(clearTemplate, deployTimeParams);\n if (Config.debug) {\n await Config.events.emitAsync(EventType.AppCompiled, {\n sources: [\n { compiledTeal: compiledApproval, appName: appSpec.name, fileName: 'approval' },\n { compiledTeal: compiledClear, appName: appSpec.name, fileName: 'clear' },\n ],\n });\n }\n return {\n approvalProgram: compiledApproval.compiledBase64ToBytes,\n compiledApproval,\n clearStateProgram: compiledClear.compiledBase64ToBytes,\n compiledClear,\n };\n }\n /**\n * Returns ABI method arguments ready for a method call params object with default values populated\n * and structs replaced with tuples.\n *\n * It does this by replacing any `undefined` values with the equivalent default value from the given ARC-56 app spec.\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @param args The arguments to the method with `undefined` for any that should be populated with a default value\n */\n async getABIArgsWithDefaultValues(methodNameOrSignature, args, sender) {\n const m = getArc56Method(methodNameOrSignature, this._appSpec);\n return await Promise.all(args?.map(async (a, i) => {\n const arg = m.args[i];\n if (a !== undefined) {\n // If a struct then convert to tuple for the underlying call\n return arg.struct && typeof a === 'object' && !Array.isArray(a)\n ? getABITupleFromABIStruct(a, this._appSpec.structs[arg.struct], this._appSpec.structs)\n : a;\n }\n const defaultValue = arg.defaultValue;\n if (defaultValue) {\n switch (defaultValue.source) {\n case 'literal':\n return getABIDecodedValue(Buffer.from(defaultValue.data, 'base64'), m.method.args[i].defaultValue?.type ?? m.method.args[i].type, this._appSpec.structs);\n case 'method': {\n const method = this.getABIMethod(defaultValue.data);\n const result = await this.send.call({\n method: defaultValue.data,\n args: method.args.map(() => undefined),\n sender,\n });\n if (result.return === undefined) {\n throw new Error('Default value method call did not return a value');\n }\n if (typeof result.return === 'object' && !(result.return instanceof Uint8Array) && !Array.isArray(result.return)) {\n return getABITupleFromABIStruct(result.return, this._appSpec.structs[method.returns.struct], this._appSpec.structs);\n }\n return result.return;\n }\n case 'local':\n case 'global': {\n const state = defaultValue.source === 'global' ? await this.getGlobalState() : await this.getLocalState(sender);\n const value = Object.values(state).find((s) => s.keyBase64 === defaultValue.data);\n if (!value) {\n throw new Error(`Preparing default value for argument ${arg.name ?? `arg${i + 1}`} resulted in the failure: The key '${defaultValue.data}' could not be found in ${defaultValue.source} storage`);\n }\n return 'valueRaw' in value\n ? getABIDecodedValue(value.valueRaw, m.method.args[i].defaultValue?.type ?? m.method.args[i].type, this._appSpec.structs)\n : value.value;\n }\n case 'box': {\n const value = await this.getBoxValue(Buffer.from(defaultValue.data, 'base64'));\n return getABIDecodedValue(value, m.method.args[i].defaultValue?.type ?? m.method.args[i].type, this._appSpec.structs);\n }\n }\n }\n if (!algosdk.abiTypeIsTransaction(arg.type)) {\n throw new Error(`No value provided for required argument ${arg.name ?? `arg${i + 1}`} in call to method ${m.name}`);\n }\n }) ?? []);\n }\n getBareParamsMethods() {\n return {\n /** Return params for an update call, including deploy-time TEAL template replacements and compilation if provided */\n update: async (params) => {\n return this.getBareParams({\n ...params,\n ...(await this.compile(params)),\n }, OnApplicationComplete.UpdateApplicationOC);\n },\n /** Return params for an opt-in call */\n optIn: (params) => {\n return this.getBareParams(params, OnApplicationComplete.OptInOC);\n },\n /** Return params for a delete call */\n delete: (params) => {\n return this.getBareParams(params, OnApplicationComplete.DeleteApplicationOC);\n },\n /** Return params for a clear state call */\n clearState: (params) => {\n return this.getBareParams(params, OnApplicationComplete.ClearStateOC);\n },\n /** Return params for a close out call */\n closeOut: (params) => {\n return this.getBareParams(params, OnApplicationComplete.CloseOutOC);\n },\n /** Return params for a call (defaults to no-op) */\n call: (params) => {\n return this.getBareParams(params, params?.onComplete ?? OnApplicationComplete.NoOpOC);\n },\n };\n }\n getBareCreateTransactionMethods() {\n return {\n /** Returns a transaction for an update call, including deploy-time TEAL template replacements and compilation if provided */\n update: async (params) => {\n return this._algorand.createTransaction.appUpdate(await this.params.bare.update(params));\n },\n /** Returns a transaction for an opt-in call */\n optIn: (params) => {\n return this._algorand.createTransaction.appCall(this.params.bare.optIn(params));\n },\n /** Returns a transaction for a delete call */\n delete: (params) => {\n return this._algorand.createTransaction.appDelete(this.params.bare.delete(params));\n },\n /** Returns a transaction for a clear state call */\n clearState: (params) => {\n return this._algorand.createTransaction.appCall(this.params.bare.clearState(params));\n },\n /** Returns a transaction for a close out call */\n closeOut: (params) => {\n return this._algorand.createTransaction.appCall(this.params.bare.closeOut(params));\n },\n /** Returns a transaction for a call (defaults to no-op) */\n call: (params) => {\n return this._algorand.createTransaction.appCall(this.params.bare.call(params));\n },\n };\n }\n getBareSendMethods() {\n return {\n /** Signs and sends an update call, including deploy-time TEAL template replacements and compilation if provided */\n update: async (params) => {\n const compiled = await this.compile(params);\n return {\n ...(await this.handleCallErrors(async () => this._algorand.send.appUpdate(await this.params.bare.update(params)))),\n ...compiled,\n };\n },\n /** Signs and sends an opt-in call */\n optIn: (params) => {\n return this.handleCallErrors(() => this._algorand.send.appCall(this.params.bare.optIn(params)));\n },\n /** Signs and sends a delete call */\n delete: (params) => {\n return this.handleCallErrors(() => this._algorand.send.appDelete(this.params.bare.delete(params)));\n },\n /** Signs and sends a clear state call */\n clearState: (params) => {\n return this.handleCallErrors(() => this._algorand.send.appCall(this.params.bare.clearState(params)));\n },\n /** Signs and sends a close out call */\n closeOut: (params) => {\n return this.handleCallErrors(() => this._algorand.send.appCall(this.params.bare.closeOut(params)));\n },\n /** Signs and sends a call (defaults to no-op) */\n call: (params) => {\n return this.handleCallErrors(() => this._algorand.send.appCall(this.params.bare.call(params)));\n },\n };\n }\n getMethodCallParamsMethods() {\n return {\n /** Return params for a payment transaction to fund the app account */\n fundAppAccount: (params) => {\n return {\n ...params,\n sender: this.getSender(params.sender),\n signer: this.getSigner(params.sender, params.signer),\n receiver: this.appAddress,\n };\n },\n /** Return params for an update ABI call, including deploy-time TEAL template replacements and compilation if provided */\n update: async (params) => {\n return (await this.getABIParams({\n ...params,\n ...(await this.compile(params)),\n }, OnApplicationComplete.UpdateApplicationOC));\n },\n /** Return params for an opt-in ABI call */\n optIn: async (params) => {\n return (await this.getABIParams(params, OnApplicationComplete.OptInOC));\n },\n /** Return params for an delete ABI call */\n delete: async (params) => {\n return (await this.getABIParams(params, OnApplicationComplete.DeleteApplicationOC));\n },\n /** Return params for an close out ABI call */\n closeOut: async (params) => {\n return (await this.getABIParams(params, OnApplicationComplete.CloseOutOC));\n },\n /** Return params for an ABI call */\n call: async (params) => {\n return (await this.getABIParams(params, params.onComplete ?? OnApplicationComplete.NoOpOC));\n },\n };\n }\n getMethodCallSendMethods() {\n return {\n /** Sign and send transactions for a payment transaction to fund the app account */\n fundAppAccount: (params) => {\n return this._algorand.send.payment(this.params.fundAppAccount(params));\n },\n /**\n * Sign and send transactions for an update ABI call, including deploy-time TEAL template replacements and compilation if provided\n */\n update: async (params) => {\n const compiled = await this.compile(params);\n return {\n ...(await this.handleCallErrors(async () => this.processMethodCallReturn(this._algorand.send.appUpdateMethodCall(await this.params.update({ ...params })), getArc56Method(params.method, this._appSpec)))),\n ...compiled,\n };\n },\n /**\n * Sign and send transactions for an opt-in ABI call\n */\n optIn: (params) => {\n return this.handleCallErrors(async () => this.processMethodCallReturn(this._algorand.send.appCallMethodCall(await this.params.optIn(params)), getArc56Method(params.method, this._appSpec)));\n },\n /**\n * Sign and send transactions for a delete ABI call\n */\n delete: (params) => {\n return this.handleCallErrors(async () => this.processMethodCallReturn(this._algorand.send.appDeleteMethodCall(await this.params.delete(params)), getArc56Method(params.method, this._appSpec)));\n },\n /**\n * Sign and send transactions for a close out ABI call\n */\n closeOut: (params) => {\n return this.handleCallErrors(async () => this.processMethodCallReturn(this._algorand.send.appCallMethodCall(await this.params.closeOut(params)), getArc56Method(params.method, this._appSpec)));\n },\n /**\n * Sign and send transactions for a call (defaults to no-op)\n */\n call: async (params) => {\n // Read-only call - do it via simulate\n if ((params.onComplete === OnApplicationComplete.NoOpOC || !params.onComplete) &&\n getArc56Method(params.method, this._appSpec).method.readonly) {\n const result = await this._algorand\n .newGroup()\n .addAppCallMethodCall(await this.params.call(params))\n .simulate({\n allowUnnamedResources: params.populateAppCallResources ?? true,\n // Simulate calls for a readonly method shouldn't invoke signing\n skipSignatures: true,\n });\n return this.processMethodCallReturn({\n ...result,\n transaction: result.transactions.at(-1),\n confirmation: result.confirmations.at(-1),\n // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain\n return: (result.returns?.length ?? 0 > 0) ? result.returns?.at(-1) : undefined,\n }, getArc56Method(params.method, this._appSpec));\n }\n return this.handleCallErrors(async () => this.processMethodCallReturn(this._algorand.send.appCallMethodCall(await this.params.call(params)), getArc56Method(params.method, this._appSpec)));\n },\n };\n }\n getMethodCallCreateTransactionMethods() {\n return {\n /** Return transaction for a payment transaction to fund the app account */\n fundAppAccount: (params) => {\n return this._algorand.createTransaction.payment(this.params.fundAppAccount(params));\n },\n /**\n * Return transactions for an update ABI call, including deploy-time TEAL template replacements and compilation if provided\n */\n update: async (params) => {\n return this._algorand.createTransaction.appUpdateMethodCall(await this.params.update(params));\n },\n /**\n * Return transactions for an opt-in ABI call\n */\n optIn: async (params) => {\n return this._algorand.createTransaction.appCallMethodCall(await this.params.optIn(params));\n },\n /**\n * Return transactions for a delete ABI call\n */\n delete: async (params) => {\n return this._algorand.createTransaction.appDeleteMethodCall(await this.params.delete(params));\n },\n /**\n * Return transactions for a close out ABI call\n */\n closeOut: async (params) => {\n return this._algorand.createTransaction.appCallMethodCall(await this.params.closeOut(params));\n },\n /**\n * Return transactions for an ABI call (defaults to no-op)\n */\n call: async (params) => {\n return this._algorand.createTransaction.appCallMethodCall(await this.params.call(params));\n },\n };\n }\n /** Returns the sender for a call, using the provided sender or using the `defaultSender`\n * if none provided and throws an error if neither provided */\n getSender(sender) {\n if (!sender && !this._defaultSender) {\n throw new Error(`No sender provided and no default sender present in app factory for call to app ${this._appName}`);\n }\n return sender ?? this._defaultSender;\n }\n /** Returns the signer for a call, using the provided signer or the `defaultSigner`\n * if no signer was provided and the sender resolves to the default sender, the call will use default signer\n * or `undefined` otherwise (so the signer is resolved from `AlgorandClient`) */\n getSigner(sender, signer) {\n return signer ?? (!sender || sender === this._defaultSender ? this._defaultSigner : undefined);\n }\n getBareParams(params, onComplete) {\n return {\n ...params,\n appId: this._appId,\n sender: this.getSender(params?.sender),\n signer: this.getSigner(params?.sender, params?.signer),\n onComplete,\n };\n }\n async getABIParams(params, onComplete) {\n const sender = this.getSender(params.sender);\n const method = getArc56Method(params.method, this._appSpec);\n const args = await this.getABIArgsWithDefaultValues(params.method, params.args, sender);\n return {\n ...params,\n appId: this._appId,\n sender: sender,\n signer: this.getSigner(params.sender, params.signer),\n method,\n onComplete,\n args,\n };\n }\n /** Make the given call and catch any errors, augmenting with debugging information before re-throwing. */\n async handleCallErrors(call) {\n try {\n return await call();\n }\n catch (e) {\n throw await this.exposeLogicError(e);\n }\n }\n getBoxMethods() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n const stateMethods = {\n /**\n * Returns all single-key state values in a record keyed by the key name and the value a decoded ABI value.\n */\n getAll: async () => {\n return Object.fromEntries(await Promise.all(Object.keys(that._appSpec.state.keys.box).map(async (key) => [key, await stateMethods.getValue(key)])));\n },\n /**\n * Returns a single state value for the current app with the value a decoded ABI value.\n * @param name The name of the state value to retrieve the value for\n * @returns\n */\n getValue: async (name) => {\n const metadata = that._appSpec.state.keys.box[name];\n const value = await that.getBoxValue(Buffer.from(metadata.key, 'base64'));\n return getABIDecodedValue(value, metadata.valueType, that._appSpec.structs);\n },\n /**\n *\n * @param mapName The name of the map to read from\n * @param key The key within the map (without any map prefix) as either a Buffer with the bytes or a value\n * that will be converted to bytes by encoding it using the specified ABI key type\n * in the ARC-56 spec\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getMapValue: async (mapName, key) => {\n const metadata = that._appSpec.state.maps.box[mapName];\n const prefix = Buffer.from(metadata.prefix ?? '', 'base64');\n const encodedKey = Buffer.concat([prefix, getABIEncodedValue(key, metadata.keyType, that._appSpec.structs)]);\n const base64Key = Buffer.from(encodedKey).toString('base64');\n const value = await that.getBoxValue(Buffer.from(base64Key, 'base64'));\n return getABIDecodedValue(value, metadata.valueType, that._appSpec.structs);\n },\n /**\n *\n * @param mapName The name of the map to read from\n * @param key The key within the map as either a Buffer with the bytes or a value\n * that will be converted to bytes by encoding it using the specified ABI key type\n * in the ARC-56 spec\n * @param appState\n */\n getMap: async (mapName) => {\n const metadata = that._appSpec.state.maps.box[mapName];\n const prefix = Buffer.from(metadata.prefix ?? '', 'base64');\n const boxNames = await that.getBoxNames();\n return new Map(await Promise.all(boxNames\n .filter((b) => binaryStartsWith(b.nameRaw, prefix))\n .map(async (b) => {\n const encodedKey = Buffer.concat([prefix, b.nameRaw]);\n const base64Key = Buffer.from(encodedKey).toString('base64');\n return [\n getABIDecodedValue(b.nameRaw.slice(prefix.length), metadata.keyType, that._appSpec.structs),\n getABIDecodedValue(await that.getBoxValue(Buffer.from(base64Key, 'base64')), metadata.valueType, that._appSpec.structs),\n ];\n })));\n },\n };\n return stateMethods;\n }\n getStateMethods(stateGetter, keyGetter, mapGetter) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n const stateMethods = {\n /**\n * Returns all single-key state values in a record keyed by the key name and the value a decoded ABI value.\n */\n getAll: async () => {\n const appState = await stateGetter();\n return Object.fromEntries(await Promise.all(Object.keys(keyGetter()).map(async (key) => [key, await stateMethods.getValue(key, appState)])));\n },\n /**\n * Returns a single state value for the current app with the value a decoded ABI value.\n * @param name The name of the state value to retrieve the value for\n * @param appState Optional cached value of the current state\n * @returns\n */\n getValue: async (name, appState) => {\n const state = Object.values(appState ?? (await stateGetter()));\n const metadata = keyGetter()[name];\n const value = state.find((s) => s.keyBase64 === metadata.key);\n if (value && 'valueRaw' in value) {\n return getABIDecodedValue(value.valueRaw, metadata.valueType, that._appSpec.structs);\n }\n return value?.value;\n },\n /**\n * Returns a single value from the given map for the current app with the value a decoded ABI value.\n * @param mapName The name of the map to read from\n * @param key The key within the map (without any map prefix) as either a Buffer with the bytes or a value\n * that will be converted to bytes by encoding it using the specified ABI key type\n * in the ARC-56 spec\n * @param appState Optional cached value of the current state\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getMapValue: async (mapName, key, appState) => {\n const state = Object.values(appState ?? (await stateGetter()));\n const metadata = mapGetter()[mapName];\n const prefix = Buffer.from(metadata.prefix ?? '', 'base64');\n const encodedKey = Buffer.concat([prefix, getABIEncodedValue(key, metadata.keyType, that._appSpec.structs)]);\n const base64Key = Buffer.from(encodedKey).toString('base64');\n const value = state.find((s) => s.keyBase64 === base64Key);\n if (value && 'valueRaw' in value) {\n return getABIDecodedValue(value.valueRaw, metadata.valueType, that._appSpec.structs);\n }\n return value?.value;\n },\n /**\n * Returns all map values for the given map.\n * @param mapName The name of the map to read from\n * @param appState Optional cached value of the current state\n * @returns A map of all key-value pairs in the map as a `Record`\n */\n getMap: async (mapName) => {\n const state = Object.values(await stateGetter());\n const metadata = mapGetter()[mapName];\n const prefix = Buffer.from(metadata.prefix ?? '', 'base64');\n return new Map(state\n .filter((s) => binaryStartsWith(s.keyRaw, prefix))\n .map((s) => {\n const key = s.keyRaw.slice(prefix.length);\n return [\n getABIDecodedValue(key, metadata.keyType, this._appSpec.structs),\n getABIDecodedValue('valueRaw' in s ? s.valueRaw : s.value, metadata.valueType, this._appSpec.structs),\n ];\n }));\n },\n };\n return stateMethods;\n }\n}\n/**\n * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientById` or\n * `algorand.client.getAppClientByCreatorAndName`.\n * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n *\n * Application client - a class that wraps an ARC-0032 app spec and provides high productivity methods to deploy and call the app */\nclass ApplicationClient {\n /**\n * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientById` or\n * `algorand.client.getAppClientByCreatorAndName`.\n * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n *\n * Create a new ApplicationClient instance\n * @param appDetails The details of the app\n * @param algod An algod instance\n */\n constructor(appDetails, algod) {\n const { app, sender, params, deployTimeParams, ...appIdentifier } = appDetails;\n this.algod = algod;\n this.appSpec = typeof app == 'string' ? JSON.parse(app) : app;\n this._appName = appIdentifier.name ?? this.appSpec.contract.name;\n this.deployTimeParams = deployTimeParams;\n if (appIdentifier.resolveBy === 'id') {\n if (appIdentifier.id < 0) {\n throw new Error(`Attempt to create application client with invalid app id of ${appIdentifier.id}`);\n }\n this._appId = appIdentifier.id;\n }\n else {\n this._appId = 0;\n this._creator = appIdentifier.creatorAddress;\n if (appIdentifier.findExistingUsing instanceof Indexer) {\n this.indexer = appIdentifier.findExistingUsing;\n }\n else {\n if (appIdentifier.findExistingUsing.creator !== this._creator) {\n throw new Error(`Attempt to create application client with invalid existingDeployments against a different creator (${appIdentifier.findExistingUsing.creator}) instead of expected creator ${this._creator}`);\n }\n this.existingDeployments = appIdentifier.findExistingUsing;\n }\n }\n this._appAddress = algosdk.getApplicationAddress(this._appId);\n this.sender = sender;\n this.params = params;\n }\n /**\n * @deprecated Use `AppClient.compile()` instead.\n *\n * Compiles the approval and clear state programs and sets up the source map.\n * @param compilation The deploy-time parameters for the compilation\n * @returns The compiled approval and clear state programs\n */\n async compile(compilation) {\n const { deployTimeParams, updatable, deletable } = compilation ?? {};\n const approvalTemplate = Buffer.from(this.appSpec.source.approval, 'base64').toString('utf-8');\n const approval = replaceDeployTimeControlParams(performTemplateSubstitution(approvalTemplate, deployTimeParams ?? this.deployTimeParams), {\n updatable,\n deletable,\n });\n const approvalCompiled = await compileTeal(approval, this.algod);\n this._approvalSourceMap = approvalCompiled?.sourceMap;\n const clearTemplate = Buffer.from(this.appSpec.source.clear, 'base64').toString('utf-8');\n const clear = performTemplateSubstitution(clearTemplate, deployTimeParams ?? this.deployTimeParams);\n const clearCompiled = await compileTeal(clear, this.algod);\n this._clearSourceMap = clearCompiled?.sourceMap;\n if (Config.debug) {\n await Config.events.emitAsync(EventType.AppCompiled, {\n sources: [\n { compiledTeal: approvalCompiled, appName: this._appName, fileName: 'approval' },\n { compiledTeal: clearCompiled, appName: this._appName, fileName: 'clear' },\n ],\n });\n }\n return { approvalCompiled, clearCompiled };\n }\n /**\n * Export the current source maps for the app.\n * @returns The source maps\n */\n exportSourceMaps() {\n if (!this._approvalSourceMap || !this._clearSourceMap) {\n throw new Error(\"Unable to export source maps; they haven't been loaded into this client - you need to call create, update, or deploy first\");\n }\n return {\n approvalSourceMap: this._approvalSourceMap,\n clearSourceMap: this._clearSourceMap,\n };\n }\n /**\n * Import source maps for the app.\n * @param sourceMaps The source maps to import\n */\n importSourceMaps(sourceMaps) {\n this._approvalSourceMap = new SourceMap(sourceMaps.approvalSourceMap);\n this._clearSourceMap = new SourceMap(sourceMaps.clearSourceMap);\n }\n /**\n * @deprecated Use `deploy` from an `AppFactory` instance instead.\n *\n * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deploy Deployment details\n * @returns The metadata and transaction result(s) of the deployment, or just the metadata if it didn't need to issue transactions\n */\n async deploy(deploy) {\n const { schema, sender: deploySender, version, allowUpdate, allowDelete, sendParams, createArgs, createOnCompleteAction, updateArgs, deleteArgs, ...deployArgs } = deploy ?? {};\n if (this._appId !== 0) {\n throw new Error(`Attempt to deploy app which already has an app id of ${this._appId}`);\n }\n const sender = deploySender ?? this.sender;\n if (!sender) {\n throw new Error('No sender provided, unable to deploy app');\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const from = sender ?? this.sender;\n if (!this._creator) {\n throw new Error(\"Attempt to `deploy` a contract without specifying `resolveBy: 'creatorAndName'` in the constructor\");\n }\n if (this._creator !== getSenderAddress(from)) {\n throw new Error(`Attempt to deploy contract with a sender address (${getSenderAddress(from)}) that differs from the given creator address for this application client: ${this._creator}`);\n }\n const approval = Buffer.from(this.appSpec.source.approval, 'base64').toString('utf-8');\n const compilation = {\n deployTimeParams: deployArgs.deployTimeParams,\n updatable: allowUpdate !== undefined\n ? allowUpdate\n : getDeployTimeControl(approval, this.appSpec, UPDATABLE_TEMPLATE_NAME, 'update_application'),\n deletable: allowDelete !== undefined\n ? allowDelete\n : getDeployTimeControl(approval, this.appSpec, DELETABLE_TEMPLATE_NAME, 'delete_application'),\n };\n const { approvalCompiled, clearCompiled } = await this.compile(compilation);\n try {\n await this.getAppReference();\n const result = await deployApp({\n from: sender,\n approvalProgram: approvalCompiled.compiledBase64ToBytes,\n clearStateProgram: clearCompiled.compiledBase64ToBytes,\n metadata: {\n name: this._appName,\n version: version ?? '1.0',\n updatable: compilation.updatable,\n deletable: compilation.deletable,\n },\n schema: {\n globalByteSlices: this.appSpec.state.global.num_byte_slices,\n globalInts: this.appSpec.state.global.num_uints,\n localByteSlices: this.appSpec.state.local.num_byte_slices,\n localInts: this.appSpec.state.local.num_uints,\n ...schema,\n },\n transactionParams: this.params,\n ...(sendParams ?? {}),\n existingDeployments: this.existingDeployments,\n createArgs: await this.getCallArgs(createArgs, sender),\n createOnCompleteAction: createOnCompleteAction,\n updateArgs: await this.getCallArgs(updateArgs, sender),\n deleteArgs: await this.getCallArgs(deleteArgs, sender),\n ...deployArgs,\n }, this.algod, this.indexer);\n // Nothing needed to happen\n if (result.operationPerformed === 'nothing') {\n return result;\n }\n if (!this.existingDeployments) {\n throw new Error('Expected existingDeployments to be present');\n }\n const { transaction, confirmation, operationPerformed, ...appMetadata } = result;\n this.existingDeployments = {\n creator: this.existingDeployments.creator,\n apps: { ...this.existingDeployments.apps, [this._appName]: appMetadata },\n };\n return { ...result, ...{ compiledApproval: approvalCompiled, compiledClear: clearCompiled } };\n }\n catch (e) {\n throw this.exposeLogicError(e);\n }\n }\n /**\n * @deprecated Use `create` from an `AppFactory` instance instead.\n *\n * Creates a smart contract app, returns the details of the created app.\n * @param create The parameters to create the app with\n * @returns The details of the created app, or the transaction to create it if `skipSending` and the compilation result\n */\n async create(create) {\n const { sender: createSender, note, sendParams, deployTimeParams, updatable, deletable, onCompleteAction, schema, ...args } = create ?? {};\n if (this._appId !== 0) {\n throw new Error(`Attempt to create app which already has an app id of ${this._appId}`);\n }\n const sender = createSender ?? this.sender;\n if (!sender) {\n throw new Error('No sender provided, unable to create app');\n }\n const { approvalCompiled, clearCompiled } = await this.compile(create);\n try {\n const result = await createApp({\n from: sender,\n approvalProgram: approvalCompiled.compiledBase64ToBytes,\n clearStateProgram: clearCompiled.compiledBase64ToBytes,\n schema: {\n globalByteSlices: this.appSpec.state.global.num_byte_slices,\n globalInts: this.appSpec.state.global.num_uints,\n localByteSlices: this.appSpec.state.local.num_byte_slices,\n localInts: this.appSpec.state.local.num_uints,\n ...schema,\n },\n onCompleteAction,\n args: await this.getCallArgs(args, sender),\n note: note,\n transactionParams: this.params,\n ...(sendParams ?? {}),\n }, this.algod);\n if (result.confirmation) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this._appId = result.confirmation.applicationIndex;\n this._appAddress = getApplicationAddress(this._appId);\n }\n return { ...result, ...{ compiledApproval: approvalCompiled, compiledClear: clearCompiled } };\n }\n catch (e) {\n throw await this.exposeLogicError(e);\n }\n }\n /**\n * @deprecated Use `appClient.send.update` or `appClient.createTransaction.update` from an `AppClient` instance instead.\n *\n * Updates the smart contract app.\n * @param update The parameters to update the app with\n * @returns The transaction send result and the compilation result\n */\n async update(update) {\n const { sender: updateSender, note, sendParams, deployTimeParams, updatable, deletable, ...args } = update ?? {};\n if (this._appId === 0) {\n throw new Error(`Attempt to update app which doesn't have an app id defined`);\n }\n const sender = updateSender ?? this.sender;\n if (!sender) {\n throw new Error('No sender provided, unable to create app');\n }\n const { approvalCompiled, clearCompiled } = await this.compile(update);\n try {\n const result = await updateApp({\n appId: this._appId,\n from: sender,\n approvalProgram: approvalCompiled.compiledBase64ToBytes,\n clearStateProgram: clearCompiled.compiledBase64ToBytes,\n args: await this.getCallArgs(args, sender),\n note: note,\n transactionParams: this.params,\n ...(sendParams ?? {}),\n }, this.algod);\n return { ...result, ...{ compiledApproval: approvalCompiled, compiledClear: clearCompiled } };\n }\n catch (e) {\n throw await this.exposeLogicError(e);\n }\n }\n /**\n * @deprecated Use `appClient.send.call` or `appClient.createTransaction.call` from an `AppClient` instance instead.\n *\n * Issues a no_op (normal) call to the app.\n * @param call The call details.\n * @returns The result of the call\n */\n async call(call) {\n if (\n // ABI call\n call?.method &&\n // We aren't skipping the send\n !call.sendParams?.skipSending &&\n // There isn't an ATC passed in\n !call.sendParams?.atc &&\n // The method is readonly\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.appSpec.hints[this.getABIMethodSignature(this.getABIMethod(call.method))].read_only) {\n const atc = new AtomicTransactionComposer();\n await this.callOfType({ ...call, sendParams: { ...call.sendParams, atc } }, 'no_op');\n const result = await atc.simulate(this.algod);\n if (result.simulateResponse.txnGroups.some((group) => group.failureMessage)) {\n throw new Error(result.simulateResponse.txnGroups.find((x) => x.failureMessage)?.failureMessage);\n }\n const txns = atc.buildGroup();\n return {\n transaction: txns[txns.length - 1].txn,\n confirmation: result.simulateResponse.txnGroups[0].txnResults.at(-1)?.txnResult,\n confirmations: result.simulateResponse.txnGroups[0].txnResults.map((t) => t.txnResult),\n transactions: txns.map((t) => t.txn),\n return: (result.methodResults?.length ?? 0 > 0) ? result.methodResults[result.methodResults.length - 1] : undefined,\n };\n }\n return await this.callOfType(call, 'no_op');\n }\n /**\n * @deprecated Use `appClient.send.optIn` or `appClient.createTransaction.optIn` from an `AppClient` instance instead.\n *\n * Issues a opt_in call to the app.\n * @param call The call details.\n * @returns The result of the call\n */\n async optIn(call) {\n return await this.callOfType(call, 'opt_in');\n }\n /**\n * @deprecated Use `appClient.send.closeOut` or `appClient.createTransaction.closeOut` from an `AppClient` instance instead.\n *\n * Issues a close_out call to the app.\n * @param call The call details.\n * @returns The result of the call\n */\n async closeOut(call) {\n return await this.callOfType(call, 'close_out');\n }\n /**\n * @deprecated Use `appClient.send.clearState` or `appClient.createTransaction.clearState` from an `AppClient` instance instead.\n *\n * Issues a clear_state call to the app.\n * @param call The call details.\n * @returns The result of the call\n */\n async clearState(call) {\n return await this.callOfType(call, 'clear_state');\n }\n /**\n * @deprecated Use `appClient.send.delete` or `appClient.createTransaction.delete` from an `AppClient` instance instead.\n *\n * Issues a delete_application call to the app.\n * @param call The call details.\n * @returns The result of the call\n */\n async delete(call) {\n return await this.callOfType(call, 'delete_application');\n }\n /**\n * @deprecated Use `appClient.send.call` or `appClient.createTransaction.call` from an `AppClient` instance instead.\n *\n * Issues a call to the app with the given call type.\n * @param call The call details.\n * @param callType The call type\n * @returns The result of the call\n */\n async callOfType(call = {}, callType) {\n const { sender: callSender, note, sendParams, ...args } = call;\n const sender = callSender ?? this.sender;\n if (!sender) {\n throw new Error('No sender provided, unable to call app');\n }\n const appMetadata = await this.getAppReference();\n if (appMetadata.appId === 0) {\n throw new Error(`Attempt to call an app that can't be found '${this._appName}' for creator '${this._creator}'.`);\n }\n try {\n return await callApp({\n appId: appMetadata.appId,\n callType: callType,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n from: sender,\n args: await this.getCallArgs(args, sender),\n note: note,\n transactionParams: this.params,\n ...(sendParams ?? {}),\n }, this.algod);\n }\n catch (e) {\n throw this.exposeLogicError(e);\n }\n }\n /**\n * Funds Algo into the app account for this app.\n * @param fund The parameters for the funding or the funding amount\n * @returns The result of the funding\n */\n async fundAppAccount(fund) {\n const { amount, sender, note, sendParams } = 'microAlgos' in fund ? { amount: fund } : fund;\n if (!sender && !this.sender) {\n throw new Error('No sender provided, unable to call app');\n }\n const ref = await this.getAppReference();\n return legacySendTransactionBridge(this.algod, sender ?? this.sender, sendParams ?? {}, {\n receiver: ref.appAddress,\n sender: getSenderAddress(sender ?? this.sender),\n amount: amount,\n note: encodeTransactionNote(note),\n }, (c) => c.payment, (c) => c.payment, this.params);\n }\n /**\n * Returns global state for the current app.\n * @returns The global state\n */\n async getGlobalState() {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n return getAppGlobalState(appRef.appId, this.algod);\n }\n /**\n * Returns local state for the given account / account address.\n * @returns The global state\n */\n async getLocalState(account) {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n return getAppLocalState(appRef.appId, account, this.algod);\n }\n /**\n * Returns the names of all current boxes for the current app.\n * @returns The names of the boxes\n */\n async getBoxNames() {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n return await getAppBoxNames(appRef.appId, this.algod);\n }\n /**\n * Returns the value of the given box for the current app.\n * @param name The name of the box to return either as a string, binary array or `BoxName`\n * @returns The current box value as a byte array\n */\n async getBoxValue(name) {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n return await getAppBoxValue(appRef.appId, name, this.algod);\n }\n /**\n * Returns the value of the given box for the current app.\n * @param name The name of the box to return either as a string, binary array or `BoxName`\n * @param type\n * @returns The current box value as a byte array\n */\n async getBoxValueFromABIType(name, type) {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n return await getAppBoxValueFromABIType({ appId: appRef.appId, boxName: name, type }, this.algod);\n }\n /**\n * Returns the values of all current boxes for the current app.\n * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n * @param filter Optional filter to filter which boxes' values are returned\n * @returns The (name, value) pair of the boxes with values as raw byte arrays\n */\n async getBoxValues(filter) {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n const names = await this.getBoxNames();\n return await Promise.all(names\n .filter(filter ?? ((_) => true))\n .map(async (boxName) => ({ name: boxName, value: await getAppBoxValue(appRef.appId, boxName, this.algod) })));\n }\n /**\n * Returns the values of all current boxes for the current app decoded using an ABI Type.\n * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n * @param type The ABI type to decode the values with\n * @param filter Optional filter to filter which boxes' values are returned\n * @returns The (name, value) pair of the boxes with values as the ABI Value\n */\n async getBoxValuesFromABIType(type, filter) {\n const appRef = await this.getAppReference();\n if (appRef.appId === 0) {\n throw new Error('No app has been created yet, unable to get global state');\n }\n const names = await this.getBoxNames();\n return await Promise.all(names.filter(filter ?? ((_) => true)).map(async (boxName) => ({\n name: boxName,\n value: await getAppBoxValueFromABIType({ appId: appRef.appId, boxName, type }, this.algod),\n })));\n }\n /**\n * @deprecated Use `appClient.params.*` from an `AppClient` instance instead.\n *\n * Returns the arguments for an app call for the given ABI method or raw method specification.\n * @param args The call args specific to this application client\n * @param sender The sender of this call. Will be used to fetch any default argument values if applicable\n * @returns The call args ready to pass into an app call\n */\n async getCallArgs(args, sender) {\n if (!args) {\n return undefined;\n }\n if (args.method) {\n const abiMethod = this.getABIMethodParams(args.method);\n if (!abiMethod) {\n throw new Error(`Attempt to call ABI method ${args.method}, but it wasn't found`);\n }\n const methodSignature = this.getABIMethodSignature(abiMethod);\n return {\n ...args,\n method: abiMethod,\n methodArgs: await Promise.all(args.methodArgs.map(async (arg, index) => {\n if (arg !== undefined)\n return arg;\n const argName = abiMethod.args[index].name;\n const defaultValueStrategy = argName && this.appSpec.hints?.[methodSignature]?.default_arguments?.[argName];\n if (!defaultValueStrategy)\n throw new Error(`Argument at position ${index} with the name ${argName} is undefined and does not have a default value strategy`);\n switch (defaultValueStrategy.source) {\n case 'constant':\n return defaultValueStrategy.data;\n case 'abi-method': {\n const method = defaultValueStrategy.data;\n const result = await this.callOfType({\n method: this.getABIMethodSignature(method),\n methodArgs: method.args.map(() => undefined),\n sender,\n }, 'no_op');\n return result.return?.returnValue;\n }\n case 'local-state':\n case 'global-state': {\n const state = defaultValueStrategy.source === 'global-state' ? await this.getGlobalState() : await this.getLocalState(sender);\n const key = defaultValueStrategy.data;\n if (key in state) {\n return state[key].value;\n }\n else {\n throw new Error(`Preparing default value for argument at position ${index} with the name ${argName} resulted in the failure: The key '${key}' could not be found in ${defaultValueStrategy.source}`);\n }\n }\n }\n })),\n };\n }\n else {\n return args;\n }\n }\n /**\n * @deprecated Use `appClient.getABIMethod` instead.\n *\n * Returns the ABI Method parameters for the given method name string for the app represented by this application client instance\n * @param method Either the name of the method or the ABI method spec definition string\n * @returns The ABI method params for the given method\n */\n getABIMethodParams(method) {\n if (!method.includes('(')) {\n const methods = this.appSpec.contract.methods.filter((m) => m.name === method);\n if (methods.length > 1) {\n throw new Error(`Received a call to method ${method} in contract ${this._appName}, but this resolved to multiple methods; please pass in an ABI signature instead: ${methods\n .map(this.getABIMethodSignature)\n .join(', ')}`);\n }\n return methods[0];\n }\n return this.appSpec.contract.methods.find((m) => this.getABIMethodSignature(m) === method);\n }\n /**\n * Returns the ABI Method for the given method name string for the app represented by this application client instance\n * @param method Either the name of the method or the ABI method spec definition string\n * @returns The ABI method for the given method\n */\n getABIMethod(method) {\n const methodParams = this.getABIMethodParams(method);\n return methodParams ? new ABIMethod(methodParams) : undefined;\n }\n /**\n * @deprecated Use `appClient.appId` and `appClient.appAddress` from an `AppClient` instance instead.\n *\n * Gets the reference information for the current application instance.\n * `appId` will be 0 if it can't find an app.\n * @returns The app reference, or if deployed using the `deploy` method, the app metadata too\n */\n async getAppReference() {\n if (!this.existingDeployments && this._creator) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.existingDeployments = await getCreatorAppsByName(this._creator, this.indexer);\n }\n if (this.existingDeployments && this._appId === 0) {\n const app = this.existingDeployments.apps[this._appName];\n if (!app) {\n return {\n appId: 0,\n appAddress: getApplicationAddress(0),\n };\n }\n return app;\n }\n return {\n appId: this._appId,\n appAddress: this._appAddress,\n };\n }\n /**\n * Takes an error that may include a logic error from a smart contract call and re-exposes the error to include source code information via the source map.\n * This is automatically used within `ApplicationClient` but if you pass `skipSending: true` e.g. if doing a group transaction\n * then you can use this in a try/catch block to get better debugging information.\n * @param e The error to parse\n * @param isClear Whether or not the code was running the clear state program\n * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n */\n exposeLogicError(e, isClear) {\n if ((!isClear && this._approvalSourceMap == undefined) || (isClear && this._clearSourceMap == undefined))\n return e;\n const errorDetails = LogicError.parseLogicError(e);\n if (errorDetails !== undefined)\n return new LogicError(errorDetails, Buffer.from(isClear ? this.appSpec.source.clear : this.appSpec.source.approval, 'base64')\n .toString()\n .split('\\n'), \n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n (pc) => (isClear ? this._clearSourceMap : this._approvalSourceMap).getLineForPc(pc));\n else\n return e;\n }\n getABIMethodSignature(method) {\n return 'getSignature' in method ? method.getSignature() : new ABIMethod(method).getSignature();\n }\n}\n\nexport { AppClient, ApplicationClient };\n//# sourceMappingURL=app-client.mjs.map\n","import algosdk from 'algosdk';\n\n/** Wrapper class to ensure safe, explicit conversion between µAlgo, Algo and numbers */\nclass AlgoAmount {\n /** Return the amount as a number in µAlgo */\n get microAlgos() {\n return this.amountInMicroAlgo;\n }\n /** Return the amount as a number in µAlgo */\n get microAlgo() {\n return this.amountInMicroAlgo;\n }\n /** Return the amount as a number in Algo */\n get algos() {\n return algosdk.microalgosToAlgos(Number(this.amountInMicroAlgo));\n }\n /** Return the amount as a number in Algo */\n get algo() {\n return algosdk.microalgosToAlgos(Number(this.amountInMicroAlgo));\n }\n constructor(amount) {\n this.amountInMicroAlgo =\n 'microAlgos' in amount\n ? BigInt(amount.microAlgos)\n : 'microAlgo' in amount\n ? BigInt(amount.microAlgo)\n : 'algos' in amount\n ? BigInt(algosdk.algosToMicroalgos(Number(amount.algos)))\n : BigInt(algosdk.algosToMicroalgos(Number(amount.algo)));\n }\n toString() {\n return `${this.microAlgo.toLocaleString('en-US')} µALGO`;\n }\n /** valueOf allows you to use `AlgoAmount` in comparison operations such as `<` and `>=` etc.,\n * but it's not recommended to use this to convert to a number, it's much safer to explicitly call\n * the algos or microAlgos properties\n */\n valueOf() {\n return Number(this.microAlgo);\n }\n /** Create a `AlgoAmount` object representing the given number of Algo */\n static Algos(amount) {\n return new AlgoAmount({ algos: amount });\n }\n /** Create a `AlgoAmount` object representing the given number of Algo */\n static Algo(amount) {\n return new AlgoAmount({ algos: amount });\n }\n /** Create a `AlgoAmount` object representing the given number of µAlgo */\n static MicroAlgos(amount) {\n return new AlgoAmount({ microAlgos: amount });\n }\n /** Create a `AlgoAmount` object representing the given number of µAlgo */\n static MicroAlgo(amount) {\n return new AlgoAmount({ microAlgos: amount });\n }\n}\n\nexport { AlgoAmount };\n//# sourceMappingURL=amount.mjs.map\n","import algosdk from 'algosdk';\nimport { Buffer } from 'buffer';\nimport { Config } from '../config.mjs';\nimport { EventType } from '../types/lifecycle-events.mjs';\nimport { asJson, toNumber } from '../util.mjs';\nimport { performAtomicTransactionComposerSimulate } from './perform-atomic-transaction-composer-simulate.mjs';\n\nvar AtomicTransactionComposer = algosdk.AtomicTransactionComposer;\nvar modelsv2 = algosdk.modelsv2;\nconst MAX_TRANSACTION_GROUP_SIZE = 16;\nconst MAX_APP_CALL_FOREIGN_REFERENCES = 8;\nconst MAX_APP_CALL_ACCOUNT_REFERENCES = 4;\n/**\n * @deprecated Convert your data to a `string` or `Uint8Array`, if using ARC-2 use `TransactionComposer.arc2Note`.\n *\n * Encodes a transaction note into a byte array ready to be included in an Algorand transaction.\n *\n * @param note The transaction note\n * @returns the transaction note ready for inclusion in a transaction\n *\n * Case on the value of `data` this either be:\n * * `null` | `undefined`: `undefined`\n * * `string`: The string value\n * * Uint8Array: passthrough\n * * Arc2TransactionNote object: ARC-0002 compatible transaction note\n * * Else: The object/value converted into a JSON string representation\n */\nfunction encodeTransactionNote(note) {\n if (note == null || typeof note === 'undefined') {\n return undefined;\n }\n else if (typeof note === 'object' && note.constructor === Uint8Array) {\n return note;\n }\n else if (typeof note === 'object' && 'dAppName' in note) {\n const arc2Payload = `${note.dAppName}:${note.format}${typeof note.data === 'string' ? note.data : asJson(note.data)}`;\n const encoder = new TextEncoder();\n return encoder.encode(arc2Payload);\n }\n else {\n const n = typeof note === 'string' ? note : asJson(note);\n const encoder = new TextEncoder();\n return encoder.encode(n);\n }\n}\n/** Encodes a transaction lease into a 32-byte array ready to be included in an Algorand transaction.\n *\n * @param lease The transaction lease as a string or binary array or null/undefined if there is no lease\n * @returns the transaction lease ready for inclusion in a transaction or `undefined` if there is no lease\n * @throws if the length of the data is > 32 bytes or empty\n * @example algokit.encodeLease('UNIQUE_ID')\n * @example algokit.encodeLease(new Uint8Array([1, 2, 3]))\n */\nfunction encodeLease(lease) {\n if (lease === null || typeof lease === 'undefined') {\n return undefined;\n }\n else if (typeof lease === 'object' && lease.constructor === Uint8Array) {\n if (lease.length === 0 || lease.length > 32) {\n throw new Error(`Received invalid lease; expected something with length between 1 and 32, but received bytes with length ${lease.length}`);\n }\n if (lease.length === 32)\n return lease;\n const lease32 = new Uint8Array(32);\n lease32.set(lease, 0);\n return lease32;\n }\n else if (typeof lease === 'string') {\n if (lease.length === 0 || lease.length > 32) {\n throw new Error(`Received invalid lease; expected something with length between 1 and 32, but received '${lease}' with length ${lease.length}`);\n }\n const encoder = new TextEncoder();\n const lease32 = new Uint8Array(32);\n lease32.set(encoder.encode(lease), 0);\n return lease32;\n }\n else {\n throw new Error(`Unknown lease type received of ${typeof lease}`);\n }\n}\n/**\n * @deprecated Use `algorand.client` to interact with accounts, and use `.addr` to get the address\n * and/or move from using `SendTransactionFrom` to `TransactionSignerAccount` and use `.addr` instead.\n *\n * Returns the public address of the given transaction sender.\n * @param sender A transaction sender\n * @returns The public address\n */\nconst getSenderAddress = function (sender) {\n return typeof sender === 'string' ? sender : 'addr' in sender ? sender.addr : sender.address();\n};\n/**\n * @deprecated Use `AlgorandClient` / `TransactionComposer` to construct transactions instead or\n * construct an `algosdk.TransactionWithSigner` manually instead.\n *\n * Given a transaction in a variety of supported formats, returns a TransactionWithSigner object ready to be passed to an\n * AtomicTransactionComposer's addTransaction method.\n * @param transaction One of: A TransactionWithSigner object (returned as is), a TransactionToSign object (signer is obtained from the\n * signer property), a Transaction object (signer is extracted from the defaultSender parameter), an async SendTransactionResult returned by\n * one of algokit utils' helpers (signer is obtained from the defaultSender parameter)\n * @param defaultSender The default sender to be used to obtain a signer where the object provided to the transaction parameter does not\n * include a signer.\n * @returns A TransactionWithSigner object.\n */\nconst getTransactionWithSigner = async (transaction, defaultSender) => {\n if ('txn' in transaction)\n return transaction;\n if (defaultSender === undefined)\n throw new Error('Default sender must be provided when passing in a transaction object that does not contain its own signer');\n return transaction instanceof Promise\n ? {\n txn: (await transaction).transaction,\n signer: getSenderTransactionSigner(defaultSender),\n }\n : 'transaction' in transaction\n ? {\n txn: transaction.transaction,\n signer: getSenderTransactionSigner(transaction.signer),\n }\n : {\n txn: transaction,\n signer: getSenderTransactionSigner(defaultSender),\n };\n};\nconst memoize = (fn) => {\n const cache = new Map();\n const cached = function (val) {\n return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);\n };\n cached.cache = cache;\n return cached;\n};\n/**\n * @deprecated Use `TransactionSignerAccount` instead of `SendTransactionFrom` or use\n * `algosdk.makeBasicAccountTransactionSigner` / `algosdk.makeLogicSigAccountTransactionSigner`.\n *\n * Returns a `TransactionSigner` for the given transaction sender.\n * This function has memoization, so will return the same transaction signer for a given sender.\n * @param sender A transaction sender\n * @returns A transaction signer\n */\nconst getSenderTransactionSigner = memoize(function (sender) {\n return 'signer' in sender\n ? sender.signer\n : 'lsig' in sender\n ? algosdk.makeLogicSigAccountTransactionSigner(sender)\n : algosdk.makeBasicAccountTransactionSigner(sender);\n});\n/**\n * @deprecated Use `AlgorandClient` / `TransactionComposer` to sign transactions\n * or use the relevant underlying `account.signTxn` / `algosdk.signLogicSigTransactionObject`\n * / `multiSigAccount.sign` / `TransactionSigner` methods directly.\n *\n * Signs a single transaction by the given signer.\n * @param transaction The transaction to sign\n * @param signer The signer to sign\n * @returns The signed transaction as a `Uint8Array`\n */\nconst signTransaction = async (transaction, signer) => {\n return 'sk' in signer\n ? transaction.signTxn(signer.sk)\n : 'lsig' in signer\n ? algosdk.signLogicSigTransactionObject(transaction, signer).blob\n : 'sign' in signer\n ? signer.sign(transaction)\n : (await signer.signer([transaction], [0]))[0];\n};\n/**\n * @deprecated Use `AlgorandClient` / `TransactionComposer` to send transactions.\n *\n * Prepares a transaction for sending and then (if instructed) signs and sends the given transaction to the chain.\n *\n * @param send The details for the transaction to prepare/send, including:\n * * `transaction`: The unsigned transaction\n * * `from`: The account to sign the transaction with: either an account with private key loaded or a logic signature account\n * * `config`: The sending configuration for this transaction\n * @param algod An algod client\n *\n * @returns An object with transaction (`transaction`) and (if `skipWaiting` is `false` or `undefined`) confirmation (`confirmation`)\n */\nconst sendTransaction = async function (send, algod) {\n const { transaction, from, sendParams } = send;\n const { skipSending, skipWaiting, fee, maxFee, suppressLog, maxRoundsToWaitForConfirmation, atc } = sendParams ?? {};\n controlFees(transaction, { fee, maxFee });\n if (atc) {\n atc.addTransaction({ txn: transaction, signer: getSenderTransactionSigner(from) });\n return { transaction };\n }\n if (skipSending) {\n return { transaction };\n }\n let txnToSend = transaction;\n const populateResources = sendParams?.populateAppCallResources ?? Config.populateAppCallResources;\n // Populate resources if the transaction is an appcall and populateAppCallResources wasn't explicitly set to false\n // NOTE: Temporary false by default until this algod bug is fixed: https://github.com/algorand/go-algorand/issues/5914\n if (txnToSend.type === algosdk.TransactionType.appl && populateResources) {\n const newAtc = new AtomicTransactionComposer();\n newAtc.addTransaction({ txn: txnToSend, signer: getSenderTransactionSigner(from) });\n const packed = await populateAppCallResources(newAtc, algod);\n txnToSend = packed.buildGroup()[0].txn;\n }\n const signedTransaction = await signTransaction(txnToSend, from);\n await algod.sendRawTransaction(signedTransaction).do();\n Config.getLogger(suppressLog).verbose(`Sent transaction ID ${txnToSend.txID()} ${txnToSend.type} from ${getSenderAddress(from)}`);\n let confirmation = undefined;\n if (!skipWaiting) {\n confirmation = await waitForConfirmation(txnToSend.txID(), maxRoundsToWaitForConfirmation ?? 5, algod);\n }\n return { transaction: txnToSend, confirmation };\n};\n/**\n * Get all of the unamed resources used by the group in the given ATC\n *\n * @param algod The algod client to use for the simulation\n * @param atc The ATC containing the txn group\n * @returns The unnamed resources accessed by the group and by each transaction in the group\n */\nasync function getUnnamedAppCallResourcesAccessed(atc, algod) {\n const simulateRequest = new algosdk.modelsv2.SimulateRequest({\n txnGroups: [],\n allowUnnamedResources: true,\n allowEmptySignatures: true,\n fixSigners: true,\n });\n const nullSigner = algosdk.makeEmptyTransactionSigner();\n const emptySignerAtc = atc.clone();\n emptySignerAtc['transactions'].forEach((t) => {\n t.signer = nullSigner;\n });\n const result = await emptySignerAtc.simulate(algod, simulateRequest);\n const groupResponse = result.simulateResponse.txnGroups[0];\n if (groupResponse.failureMessage) {\n throw Error(`Error during resource population simulation in transaction ${groupResponse.failedAt}: ${groupResponse.failureMessage}`);\n }\n return {\n group: groupResponse.unnamedResourcesAccessed,\n txns: groupResponse.txnResults.map(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (t) => t.unnamedResourcesAccessed),\n };\n}\n/**\n * Take an existing Atomic Transaction Composer and return a new one with the required\n * app call resources packed into it\n *\n * @param algod The algod client to use for the simulation\n * @param atc The ATC containing the txn group\n * @returns A new ATC with the resources packed into the transactions\n *\n * @privateRemarks\n *\n * This entire function will eventually be implemented in simulate upstream in algod. The simulate endpoint will return\n * an array of refference arrays for each transaction, so this eventually will eventually just call simulate and set the\n * reference arrays in the transactions to the reference arrays returned by simulate.\n *\n * See https://github.com/algorand/go-algorand/pull/5684\n *\n */\nasync function populateAppCallResources(atc, algod) {\n const unnamedResourcesAccessed = await getUnnamedAppCallResourcesAccessed(atc, algod);\n const group = atc.buildGroup();\n unnamedResourcesAccessed.txns.forEach((r, i) => {\n if (r === undefined)\n return;\n if (r.boxes || r.extraBoxRefs)\n throw Error('Unexpected boxes at the transaction level');\n if (r.appLocals)\n throw Error('Unexpected app local at the transaction level');\n if (r.assetHoldings)\n throw Error('Unexpected asset holding at the transaction level');\n // Do accounts first because the account limit is 4\n r.accounts?.forEach((a) => {\n group[i].txn.appAccounts = [...(group[i].txn.appAccounts ?? []), algosdk.decodeAddress(a)];\n });\n r.apps?.forEach((a) => {\n group[i].txn.appForeignApps = [...(group[i].txn.appForeignApps ?? []), Number(a)];\n });\n r.assets?.forEach((a) => {\n group[i].txn.appForeignAssets = [...(group[i].txn.appForeignAssets ?? []), Number(a)];\n });\n const accounts = group[i].txn.appAccounts?.length || 0;\n if (accounts > MAX_APP_CALL_ACCOUNT_REFERENCES)\n throw Error(`Account reference limit of ${MAX_APP_CALL_ACCOUNT_REFERENCES} exceeded in transaction ${i}`);\n const assets = group[i].txn.appForeignAssets?.length || 0;\n const apps = group[i].txn.appForeignApps?.length || 0;\n const boxes = group[i].txn.boxes?.length || 0;\n if (accounts + assets + apps + boxes > MAX_APP_CALL_FOREIGN_REFERENCES) {\n throw Error(`Resource reference limit of ${MAX_APP_CALL_FOREIGN_REFERENCES} exceeded in transaction ${i}`);\n }\n });\n const populateGroupResource = (txns, reference, type) => {\n const isApplBelowLimit = (t) => {\n if (t.txn.type !== algosdk.TransactionType.appl)\n return false;\n const accounts = t.txn.appAccounts?.length || 0;\n const assets = t.txn.appForeignAssets?.length || 0;\n const apps = t.txn.appForeignApps?.length || 0;\n const boxes = t.txn.boxes?.length || 0;\n return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES;\n };\n // If this is a asset holding or app local, first try to find a transaction that already has the account available\n if (type === 'assetHolding' || type === 'appLocal') {\n const { account } = reference;\n let txnIndex = txns.findIndex((t) => {\n if (!isApplBelowLimit(t))\n return false;\n return (\n // account is in the foreign accounts array\n t.txn.appAccounts?.map((a) => algosdk.encodeAddress(a.publicKey)).includes(account) ||\n // account is available as an app account\n t.txn.appForeignApps?.map((a) => algosdk.getApplicationAddress(a)).includes(account) ||\n // account is available since it's in one of the fields\n Object.values(t.txn)\n .map((f) => asJson(f))\n .includes(asJson(algosdk.decodeAddress(account))));\n });\n if (txnIndex > -1) {\n if (type === 'assetHolding') {\n const { asset } = reference;\n txns[txnIndex].txn.appForeignAssets = [...(txns[txnIndex].txn.appForeignAssets ?? []), Number(asset)];\n }\n else {\n const { app } = reference;\n txns[txnIndex].txn.appForeignApps = [...(txns[txnIndex].txn.appForeignApps ?? []), Number(app)];\n }\n return;\n }\n // Now try to find a txn that already has that app or asset available\n txnIndex = txns.findIndex((t) => {\n if (!isApplBelowLimit(t))\n return false;\n // check if there is space in the accounts array\n if ((t.txn.appAccounts?.length || 0) >= MAX_APP_CALL_ACCOUNT_REFERENCES)\n return false;\n if (type === 'assetHolding') {\n const { asset } = reference;\n return t.txn.appForeignAssets?.includes(Number(asset));\n }\n else {\n const { app } = reference;\n return t.txn.appForeignApps?.includes(Number(app)) || t.txn.appIndex === Number(app);\n }\n });\n if (txnIndex > -1) {\n const { account } = reference;\n txns[txnIndex].txn.appAccounts = [...(txns[txnIndex].txn.appAccounts ?? []), algosdk.decodeAddress(account)];\n return;\n }\n }\n // If this is a box, first try to find a transaction that already has the app available\n if (type === 'box') {\n const { app, name } = reference;\n const txnIndex = txns.findIndex((t) => {\n if (!isApplBelowLimit(t))\n return false;\n // If the app is in the foreign array OR the app being called, then we know it's available\n return t.txn.appForeignApps?.includes(Number(app)) || t.txn.appIndex === Number(app);\n });\n if (txnIndex > -1) {\n txns[txnIndex].txn.boxes = [...(txns[txnIndex].txn.boxes ?? []), { appIndex: Number(app), name }];\n return;\n }\n }\n // Find the txn index to put the reference(s)\n const txnIndex = txns.findIndex((t) => {\n if (t.txn.type !== algosdk.TransactionType.appl)\n return false;\n const accounts = t.txn.appAccounts?.length || 0;\n if (type === 'account')\n return accounts < MAX_APP_CALL_ACCOUNT_REFERENCES;\n const assets = t.txn.appForeignAssets?.length || 0;\n const apps = t.txn.appForeignApps?.length || 0;\n const boxes = t.txn.boxes?.length || 0;\n // If we're adding local state or asset holding, we need space for the acocunt and the other reference\n if (type === 'assetHolding' || type === 'appLocal') {\n return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES - 1 && accounts < MAX_APP_CALL_ACCOUNT_REFERENCES;\n }\n // If we're adding a box, we need space for both the box ref and the app ref\n if (type === 'box' && BigInt(reference.app) !== BigInt(0)) {\n return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES - 1;\n }\n return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES;\n });\n if (txnIndex === -1) {\n throw Error('No more transactions below reference limit. Add another app call to the group.');\n }\n if (type === 'account') {\n txns[txnIndex].txn.appAccounts = [...(txns[txnIndex].txn.appAccounts ?? []), algosdk.decodeAddress(reference)];\n }\n else if (type === 'app') {\n txns[txnIndex].txn.appForeignApps = [...(txns[txnIndex].txn.appForeignApps ?? []), Number(reference)];\n }\n else if (type === 'box') {\n const { app, name } = reference;\n txns[txnIndex].txn.boxes = [...(txns[txnIndex].txn.boxes ?? []), { appIndex: Number(app), name }];\n if (app.toString() !== '0') {\n txns[txnIndex].txn.appForeignApps = [...(txns[txnIndex].txn.appForeignApps ?? []), Number(app)];\n }\n }\n else if (type === 'assetHolding') {\n const { asset, account } = reference;\n txns[txnIndex].txn.appForeignAssets = [...(txns[txnIndex].txn.appForeignAssets ?? []), Number(asset)];\n txns[txnIndex].txn.appAccounts = [...(txns[txnIndex].txn.appAccounts ?? []), algosdk.decodeAddress(account)];\n }\n else if (type === 'appLocal') {\n const { app, account } = reference;\n txns[txnIndex].txn.appAccounts = [...(txns[txnIndex].txn.appAccounts ?? []), algosdk.decodeAddress(account)];\n txns[txnIndex].txn.appForeignApps = [...(txns[txnIndex].txn.appForeignApps ?? []), Number(app)];\n }\n else if (type === 'asset') {\n txns[txnIndex].txn.appForeignAssets = [...(txns[txnIndex].txn.appForeignAssets ?? []), Number(reference)];\n }\n };\n const g = unnamedResourcesAccessed.group;\n if (g) {\n // Do cross-reference resources first because they are the most restrictive in terms\n // of which transactions can be used\n g.appLocals?.forEach((a) => {\n populateGroupResource(group, a, 'appLocal');\n // Remove resources from the group if we're adding them here\n g.accounts = g.accounts?.filter((acc) => acc !== a.account);\n g.apps = g.apps?.filter((app) => BigInt(app) !== BigInt(a.app));\n });\n g.assetHoldings?.forEach((a) => {\n populateGroupResource(group, a, 'assetHolding');\n // Remove resources from the group if we're adding them here\n g.accounts = g.accounts?.filter((acc) => acc !== a.account);\n g.assets = g.assets?.filter((asset) => BigInt(asset) !== BigInt(a.asset));\n });\n // Do accounts next because the account limit is 4\n g.accounts?.forEach((a) => {\n populateGroupResource(group, a, 'account');\n });\n g.boxes?.forEach((b) => {\n populateGroupResource(group, b, 'box');\n // Remove apps as resource from the group if we're adding it here\n g.apps = g.apps?.filter((app) => BigInt(app) !== BigInt(b.app));\n });\n g.assets?.forEach((a) => {\n populateGroupResource(group, a, 'asset');\n });\n g.apps?.forEach((a) => {\n populateGroupResource(group, a, 'app');\n });\n if (g.extraBoxRefs) {\n for (let i = 0; i < g.extraBoxRefs; i += 1) {\n const ref = new algosdk.modelsv2.BoxReference({ app: 0, name: new Uint8Array(0) });\n populateGroupResource(group, ref, 'box');\n }\n }\n }\n const newAtc = new algosdk.AtomicTransactionComposer();\n group.forEach((t) => {\n // eslint-disable-next-line no-param-reassign\n t.txn.group = undefined;\n newAtc.addTransaction(t);\n });\n newAtc['methodCalls'] = atc['methodCalls'];\n return newAtc;\n}\n/**\n * Signs and sends transactions that have been collected by an `AtomicTransactionComposer`.\n * @param atcSend The parameters controlling the send, including `atc` The `AtomicTransactionComposer` and params to control send behaviour\n * @param algod An algod client\n * @returns An object with transaction IDs, transactions, group transaction ID (`groupTransactionId`) if more than 1 transaction sent, and (if `skipWaiting` is `false` or unset) confirmation (`confirmation`)\n */\nconst sendAtomicTransactionComposer = async function (atcSend, algod) {\n const { atc: givenAtc, sendParams, ...executeParams } = atcSend;\n let atc;\n // const hasAppCalls = () =>\n // givenAtc\n // .buildGroup()\n // .map((t) => t.txn.type)\n // .includes(algosdk.TransactionType.appl)\n atc = givenAtc;\n try {\n // If populateAppCallResources is true OR if populateAppCallResources is undefined and there are app calls, then populate resources\n // NOTE: Temporary false by default until this algod bug is fixed: https://github.com/algorand/go-algorand/issues/5914\n const populateResources = executeParams?.populateAppCallResources ?? sendParams?.populateAppCallResources ?? Config.populateAppCallResources;\n if (populateResources) {\n atc = await populateAppCallResources(givenAtc, algod);\n }\n const transactionsWithSigner = atc.buildGroup();\n const transactionsToSend = transactionsWithSigner.map((t) => {\n return t.txn;\n });\n let groupId = undefined;\n if (transactionsToSend.length > 1) {\n groupId = transactionsToSend[0].group ? Buffer.from(transactionsToSend[0].group).toString('base64') : '';\n Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Sending group of ${transactionsToSend.length} transactions (${groupId})`, {\n transactionsToSend,\n });\n Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).debug(`Transaction IDs (${groupId})`, transactionsToSend.map((t) => t.txID()));\n }\n if (Config.debug && Config.traceAll) {\n // Dump the traces to a file for use with AlgoKit AVM debugger\n const simulateResponse = await performAtomicTransactionComposerSimulate(atc, algod);\n await Config.events.emitAsync(EventType.TxnGroupSimulated, {\n simulateResponse,\n });\n }\n const result = await atc.execute(algod, executeParams?.maxRoundsToWaitForConfirmation ?? sendParams?.maxRoundsToWaitForConfirmation ?? 5);\n if (transactionsToSend.length > 1) {\n Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Group transaction (${groupId}) sent with ${transactionsToSend.length} transactions`);\n }\n else {\n Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Sent transaction ID ${transactionsToSend[0].txID()} ${transactionsToSend[0].type} from ${algosdk.encodeAddress(transactionsToSend[0].from.publicKey)}`);\n }\n let confirmations = undefined;\n if (!sendParams?.skipWaiting) {\n confirmations = await Promise.all(transactionsToSend.map(async (t) => modelsv2.PendingTransactionResponse.from_obj_for_encoding(await algod.pendingTransactionInformation(t.txID()).do())));\n }\n return {\n groupId,\n confirmations,\n txIds: transactionsToSend.map((t) => t.txID()),\n transactions: transactionsToSend,\n returns: result.methodResults.map(getABIReturnValue),\n };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n catch (e) {\n // Create a new error object so the stack trace is correct (algosdk throws an error with a more limited stack trace)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const err = new Error(typeof e === 'object' ? e?.message : 'Received error executing Atomic Transaction Composer');\n err.cause = e;\n if (typeof e === 'object') {\n // Remove headers as it doesn't have anything useful.\n delete e.response?.headers;\n err.response = e.response;\n err.name = e.name;\n }\n if (Config.debug && typeof e === 'object') {\n err.traces = [];\n Config.logger.error('Received error executing Atomic Transaction Composer and debug flag enabled; attempting simulation to get more information', err);\n const simulate = await performAtomicTransactionComposerSimulate(atc, algod);\n if (Config.debug && !Config.traceAll) {\n // Emit the event only if traceAll: false, as it should have already been emitted above\n await Config.events.emitAsync(EventType.TxnGroupSimulated, {\n simulateResponse: simulate,\n });\n }\n if (simulate && simulate.txnGroups[0].failedAt) {\n for (const txn of simulate.txnGroups[0].txnResults) {\n err.traces.push({\n trace: txn.execTrace?.get_obj_for_encoding(),\n appBudget: txn.appBudgetConsumed,\n logicSigBudget: txn.logicSigBudgetConsumed,\n logs: txn.txnResult.logs,\n message: simulate.txnGroups[0].failureMessage,\n });\n }\n }\n }\n else {\n Config.logger.error('Received error executing Atomic Transaction Composer, for more information enable the debug flag', err);\n }\n throw err;\n }\n};\nconst convertABIDecodedBigIntToNumber = (value, type) => {\n if (typeof value === 'bigint') {\n if (type instanceof algosdk.ABIUintType) {\n return type.bitSize < 53 ? Number(value) : value;\n }\n else {\n return value;\n }\n }\n else if (Array.isArray(value) && (type instanceof algosdk.ABIArrayStaticType || type instanceof algosdk.ABIArrayDynamicType)) {\n return value.map((v) => convertABIDecodedBigIntToNumber(v, type.childType));\n }\n else if (Array.isArray(value) && type instanceof algosdk.ABITupleType) {\n return value.map((v, i) => convertABIDecodedBigIntToNumber(v, type.childTypes[i]));\n }\n else {\n return value;\n }\n};\n/**\n * Takes an algosdk `ABIResult` and converts it to an `ABIReturn`.\n * Converts `bigint`'s for Uint's < 64 to `number` for easier use.\n * @param result The `ABIReturn`\n */\nfunction getABIReturnValue(result) {\n if (result.decodeError) {\n return {\n decodeError: result.decodeError,\n };\n }\n return {\n method: result.method,\n rawReturnValue: result.rawReturnValue,\n decodeError: undefined,\n returnValue: result.returnValue !== undefined && result.method.returns.type !== 'void'\n ? convertABIDecodedBigIntToNumber(result.returnValue, result.method.returns.type)\n : result.returnValue,\n };\n}\n/**\n * @deprecated Use `performAtomicTransactionComposerSimulate`, dry-run is a deprecated Algorand feature.\n *\n * Performs a dry run of the transactions loaded into the given AtomicTransactionComposer`\n * @param atc The AtomicTransactionComposer` with transaction(s) loaded\n * @param algod An Algod client\n * @returns The dryrun result\n */\nasync function performAtomicTransactionComposerDryrun(atc, algod) {\n const signedTransactions = await atc.gatherSignatures();\n const txns = signedTransactions.map((t) => {\n return algosdk.decodeSignedTransaction(t);\n });\n const dryrun = await algosdk.createDryrun({ client: algod, txns });\n return new algosdk.DryrunResult(await algod.dryrun(dryrun).do());\n}\n/**\n * @deprecated Use `TransactionComposer` (`algorand.newGroup()`) or `AtomicTransactionComposer` to construct and send group transactions instead.\n *\n * Signs and sends a group of [up to 16](https://developer.algorand.org/docs/get-details/atomic_transfers/#create-transactions) transactions to the chain\n *\n * @param groupSend The group details to send, with:\n * * `transactions`: The array of transactions to send along with their signing account\n * * `sendParams`: The parameters to dictate how the group is sent\n * @param algod An algod client\n * @returns An object with transaction IDs, transactions, group transaction ID (`groupTransactionId`) if more than 1 transaction sent, and (if `skipWaiting` is `false` or unset) confirmation (`confirmation`)\n */\nconst sendGroupOfTransactions = async function (groupSend, algod) {\n const { transactions, signer, sendParams } = groupSend;\n const defaultTransactionSigner = signer ? getSenderTransactionSigner(signer) : undefined;\n const transactionsWithSigner = await Promise.all(transactions.map(async (t) => {\n if ('signer' in t)\n return {\n txn: t.transaction,\n signer: getSenderTransactionSigner(t.signer),\n sender: t.signer,\n };\n const txn = 'then' in t ? (await t).transaction : t;\n if (!signer) {\n throw new Error(`Attempt to send transaction ${txn.txID()} as part of a group transaction, but no signer parameter was provided.`);\n }\n return {\n txn,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n signer: defaultTransactionSigner,\n sender: signer,\n };\n }));\n const atc = new AtomicTransactionComposer();\n transactionsWithSigner.forEach((txn) => atc.addTransaction(txn));\n return (await sendAtomicTransactionComposer({ atc, sendParams }, algod));\n};\n/**\n * Wait until the transaction is confirmed or rejected, or until `timeout`\n * number of rounds have passed.\n *\n * @param algod An algod client\n * @param transactionId The transaction ID to wait for\n * @param maxRoundsToWait Maximum number of rounds to wait\n *\n * @return Pending transaction information\n * @throws Throws an error if the transaction is not confirmed or rejected in the next `timeout` rounds\n */\nconst waitForConfirmation = async function (transactionId, maxRoundsToWait, algod) {\n if (maxRoundsToWait < 0) {\n throw new Error(`Invalid timeout, received ${maxRoundsToWait}, expected > 0`);\n }\n // Get current round\n const status = modelsv2.NodeStatusResponse.from_obj_for_encoding(await algod.status().do());\n if (status === undefined) {\n throw new Error('Unable to get node status');\n }\n // Loop for up to `timeout` rounds looking for a confirmed transaction\n const startRound = BigInt(status.lastRound) + 1n;\n let currentRound = startRound;\n while (currentRound < startRound + BigInt(maxRoundsToWait)) {\n try {\n const pendingInfo = modelsv2.PendingTransactionResponse.from_obj_for_encoding(await algod.pendingTransactionInformation(transactionId).do());\n if (pendingInfo !== undefined) {\n const confirmedRound = pendingInfo.confirmedRound;\n if (confirmedRound && confirmedRound > 0) {\n return pendingInfo;\n }\n else {\n const poolError = pendingInfo.poolError;\n if (poolError != null && poolError.length > 0) {\n // If there was a pool error, then the transaction has been rejected!\n throw new Error(`Transaction ${transactionId} was rejected; pool error: ${poolError}`);\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }\n catch (e) {\n if (e.name === 'URLTokenBaseHTTPError') {\n currentRound++;\n continue;\n }\n }\n await algod.statusAfterBlock(toNumber(currentRound)).do();\n currentRound++;\n }\n throw new Error(`Transaction ${transactionId} not confirmed after ${maxRoundsToWait} rounds`);\n};\n/**\n * @deprecated Use `TransactionComposer` and the `maxFee` field in the transaction params instead.\n *\n * Limit the acceptable fee to a defined amount of µAlgo.\n * This also sets the transaction to be flatFee to ensure the transaction only succeeds at\n * the estimated rate.\n * @param transaction The transaction to cap or suggested params object about to be used to create a transaction\n * @param maxAcceptableFee The maximum acceptable fee to pay\n */\nfunction capTransactionFee(transaction, maxAcceptableFee) {\n // If a flat fee hasn't already been defined\n if (!transaction.flatFee) {\n // Once a transaction has been constructed by algosdk, transaction.fee indicates what the total transaction fee\n // Will be based on the current suggested fee-per-byte value.\n if (transaction.fee > maxAcceptableFee.microAlgo) {\n throw new Error(`Cancelled transaction due to high network congestion fees. Algorand suggested fees would cause this transaction to cost ${transaction.fee} µALGO. Cap for this transaction is ${maxAcceptableFee.microAlgo} µALGO.`);\n }\n else if (transaction.fee > algosdk.ALGORAND_MIN_TX_FEE) {\n Config.logger.warn(`Algorand network congestion fees are in effect. This transaction will incur a fee of ${transaction.fee} µALGO.`);\n }\n // Now set the flat on the transaction. Otherwise the network may increase the fee above our cap and perform the transaction.\n transaction.flatFee = true;\n }\n}\n/**\n * @deprecated Use `TransactionComposer` and the `maxFee` and `staticFee` fields in the transaction params instead.\n *\n * Allows for control of fees on a `Transaction` or `SuggestedParams` object\n * @param transaction The transaction or suggested params\n * @param feeControl The fee control parameters\n */\nfunction controlFees(transaction, feeControl) {\n const { fee, maxFee } = feeControl;\n if (fee) {\n transaction.fee = Number(fee.microAlgo);\n transaction.flatFee = true;\n }\n if (maxFee !== undefined) {\n capTransactionFee(transaction, maxFee);\n }\n return transaction;\n}\n/**\n * @deprecated Use `suggestedParams ? { ...suggestedParams } : await algod.getTransactionParams().do()` instead\n *\n * Returns suggested transaction parameters from algod unless some are already provided.\n * @param params Optionally provide parameters to use\n * @param algod Algod algod\n * @returns The suggested transaction parameters\n */\nasync function getTransactionParams(params, algod) {\n return params ? { ...params } : await algod.getTransactionParams().do();\n}\n/**\n * @deprecated Use `atc.clone().buildGroup()` instead.\n *\n * Returns the array of transactions currently present in the given `AtomicTransactionComposer`\n * @param atc The atomic transaction composer\n * @returns The array of transactions with signers\n */\nfunction getAtomicTransactionComposerTransactions(atc) {\n try {\n return atc.clone().buildGroup();\n }\n catch {\n return [];\n }\n}\n\nexport { MAX_APP_CALL_ACCOUNT_REFERENCES, MAX_APP_CALL_FOREIGN_REFERENCES, MAX_TRANSACTION_GROUP_SIZE, capTransactionFee, controlFees, encodeLease, encodeTransactionNote, getABIReturnValue, getAtomicTransactionComposerTransactions, getSenderAddress, getSenderTransactionSigner, getTransactionParams, getTransactionWithSigner, performAtomicTransactionComposerDryrun, populateAppCallResources, sendAtomicTransactionComposer, sendGroupOfTransactions, sendTransaction, signTransaction, waitForConfirmation };\n//# sourceMappingURL=transaction.mjs.map\n","import algosdk from 'algosdk';\nimport { legacySendAppTransactionBridge, _getAppArgsForABICall, _getBoxReference } from './transaction/legacy-bridge.mjs';\nimport { getSenderAddress, encodeLease } from './transaction/transaction.mjs';\nimport { AppManager } from './types/app-manager.mjs';\nimport { toNumber } from './util.mjs';\n\nvar ABIMethod = algosdk.ABIMethod;\nvar modelsv2 = algosdk.modelsv2;\nvar OnApplicationComplete = algosdk.OnApplicationComplete;\n/**\n * @deprecated Use `algorand.send.appCreate()` / `algorand.createTransaction.appCreate()` / `algorand.send.appCreateMethodCall()`\n * / `algorand.createTransaction.appCreateMethodCall()` instead\n *\n * Creates a smart contract app, returns the details of the created app.\n * @param create The parameters to create the app with\n * @param algod An algod client\n * @returns The details of the created app, or the transaction to create it if `skipSending` and the compilation result\n */\nasync function createApp(create, algod) {\n const onComplete = getAppOnCompleteAction(create.onCompleteAction);\n if (onComplete === algosdk.OnApplicationComplete.ClearStateOC) {\n throw new Error('Cannot create an app with on-complete action of ClearState');\n }\n const result = create.args?.method\n ? await legacySendAppTransactionBridge(algod, create.from, create.args, create, {\n sender: getSenderAddress(create.from),\n onComplete,\n approvalProgram: create.approvalProgram,\n clearStateProgram: create.clearStateProgram,\n method: create.args.method instanceof ABIMethod ? create.args.method : new ABIMethod(create.args.method),\n extraProgramPages: create.schema.extraPages,\n schema: create.schema,\n }, (c) => c.appCreateMethodCall, (c) => c.appCreateMethodCall)\n : await legacySendAppTransactionBridge(algod, create.from, create.args, create, {\n sender: getSenderAddress(create.from),\n onComplete,\n approvalProgram: create.approvalProgram,\n clearStateProgram: create.clearStateProgram,\n extraProgramPages: create.schema.extraPages,\n schema: create.schema,\n }, (c) => c.appCreate, (c) => c.appCreate);\n return { ...result, appId: 'appId' in result ? Number(result.appId) : 0, appAddress: 'appAddress' in result ? result.appAddress : '' };\n}\n/**\n * @deprecated Use `algorand.send.appUpdate()` / `algorand.createTransaction.appUpdate()` / `algorand.send.appUpdateMethodCall()`\n * / `algorand.createTransaction.appUpdateMethodCall()` instead\n *\n * Updates a smart contract app.\n * @param update The parameters to update the app with\n * @param algod An algod client\n * @returns The transaction send result and the compilation result\n */\nasync function updateApp(update, algod) {\n return update.args?.method\n ? await legacySendAppTransactionBridge(algod, update.from, update.args, update, {\n appId: BigInt(update.appId),\n sender: getSenderAddress(update.from),\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n approvalProgram: update.approvalProgram,\n clearStateProgram: update.clearStateProgram,\n method: update.args.method instanceof ABIMethod ? update.args.method : new ABIMethod(update.args.method),\n }, (c) => c.appUpdateMethodCall, (c) => c.appUpdateMethodCall)\n : await legacySendAppTransactionBridge(algod, update.from, update.args, update, {\n appId: BigInt(update.appId),\n sender: getSenderAddress(update.from),\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n approvalProgram: update.approvalProgram,\n clearStateProgram: update.clearStateProgram,\n }, (c) => c.appUpdate, (c) => c.appUpdate);\n}\n/**\n * @deprecated Use `algosdk.OnApplicationComplete` directly instead.\n *\n * Returns a `algosdk.OnApplicationComplete` for the given onCompleteAction.\n *\n * If given `undefined` will return `OnApplicationComplete.NoOpOC`.\n *\n * If given an `AppCallType` will convert the string enum to the correct underlying `algosdk.OnApplicationComplete`.\n *\n * @param onCompletionAction The on completion action\n * @returns The `algosdk.OnApplicationComplete`\n */\nfunction getAppOnCompleteAction(onCompletionAction) {\n switch (onCompletionAction) {\n case undefined:\n case 'no_op':\n case OnApplicationComplete.NoOpOC:\n return OnApplicationComplete.NoOpOC;\n case 'opt_in':\n case OnApplicationComplete.OptInOC:\n return OnApplicationComplete.OptInOC;\n case 'close_out':\n case OnApplicationComplete.CloseOutOC:\n return OnApplicationComplete.CloseOutOC;\n case 'clear_state':\n case OnApplicationComplete.ClearStateOC:\n return OnApplicationComplete.ClearStateOC;\n case 'update_application':\n case OnApplicationComplete.UpdateApplicationOC:\n return OnApplicationComplete.UpdateApplicationOC;\n case 'delete_application':\n case OnApplicationComplete.DeleteApplicationOC:\n return OnApplicationComplete.DeleteApplicationOC;\n }\n}\n/**\n * @deprecated Use `algorand.send.appUpdate()` / `algorand.createTransaction.appUpdate()` / `algorand.send.appUpdateMethodCall()`\n * / `algorand.createTransaction.appUpdateMethodCall()` instead\n *\n * Issues a call to a given app.\n * @param call The call details.\n * @param algod An algod client\n * @returns The result of the call\n */\nasync function callApp(call, algod) {\n const onComplete = getAppOnCompleteAction(call.callType);\n if (onComplete === algosdk.OnApplicationComplete.UpdateApplicationOC) {\n throw new Error('Cannot execute an app call with on-complete action of Update');\n }\n if (call.args?.method && onComplete === algosdk.OnApplicationComplete.ClearStateOC) {\n throw new Error('Cannot execute an ABI method call with on-complete action of ClearState');\n }\n return call.args?.method\n ? await legacySendAppTransactionBridge(algod, call.from, call.args, call, {\n appId: BigInt(call.appId),\n sender: getSenderAddress(call.from),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onComplete: onComplete,\n method: call.args.method instanceof ABIMethod ? call.args.method : new ABIMethod(call.args.method),\n }, (c) => c.appCallMethodCall, (c) => c.appCallMethodCall)\n : await legacySendAppTransactionBridge(algod, call.from, call.args, call, {\n appId: BigInt(call.appId),\n sender: getSenderAddress(call.from),\n onComplete,\n }, (c) => c.appCall, (c) => c.appCall);\n}\n/**\n * @deprecated Use `AppManager.getABIReturn` instead.\n *\n * Returns any ABI return values for the given app call arguments and transaction confirmation.\n * @param args The arguments that were used for the call\n * @param confirmation The transaction confirmation from algod\n * @returns The return value for the method call\n */\nfunction getABIReturn(args, confirmation) {\n if (!args || !args.method) {\n return undefined;\n }\n const method = 'txnCount' in args.method ? args.method : new ABIMethod(args.method);\n return AppManager.getABIReturn(confirmation, method);\n}\n/**\n * @deprecated Use `algorand.app.getGlobalState` instead.\n *\n * Returns the current global state values for the given app ID\n * @param appId The ID of the app return global state for\n * @param algod An algod client instance\n * @returns The current global state\n */\nasync function getAppGlobalState(appId, algod) {\n return await new AppManager(algod).getGlobalState(BigInt(appId));\n}\n/**\n * @deprecated Use `algorand.app.getLocalState` instead.\n *\n * Returns the current global state values for the given app ID and account\n * @param appId The ID of the app return global state for\n * @param account Either the string address of an account or an account object for the account to get local state for the given app\n * @param algod An algod client instance\n * @returns The current local state for the given (app, account) combination\n */\nasync function getAppLocalState(appId, account, algod) {\n return new AppManager(algod).getLocalState(BigInt(appId), getSenderAddress(account));\n}\n/**\n * @deprecated Use `algorand.app.getBoxNames` instead.\n * Returns the names of the boxes for the given app.\n * @param appId The ID of the app return box names for\n * @param algod An algod client instance\n * @returns The current box names\n */\nasync function getAppBoxNames(appId, algod) {\n return new AppManager(algod).getBoxNames(BigInt(appId));\n}\n/**\n * @deprecated Use `algorand.app.getBoxValue` instead.\n * Returns the value of the given box name for the given app.\n * @param appId The ID of the app return box names for\n * @param boxName The name of the box to return either as a string, binary array or `BoxName`\n * @param algod An algod client instance\n * @returns The current box value as a byte array\n */\nasync function getAppBoxValue(appId, boxName, algod) {\n return new AppManager(algod).getBoxValue(BigInt(appId), typeof boxName !== 'string' && 'name' in boxName ? boxName.nameRaw : boxName);\n}\n/**\n * @deprecated Use `algorand.app.getBoxValues` instead.\n * Returns the value of the given box names for the given app.\n * @param appId The ID of the app return box names for\n * @param boxNames The names of the boxes to return either as a string, binary array or `BoxName`\n * @param algod An algod client instance\n * @returns The current box values as a byte array in the same order as the passed in box names\n */\nasync function getAppBoxValues(appId, boxNames, algod) {\n return new AppManager(algod).getBoxValues(BigInt(appId), boxNames.map((b) => (typeof b !== 'string' && 'name' in b ? b.nameRaw : b)));\n}\n/**\n * @deprecated Use `algorand.app.getBoxValueFromABIType` instead.\n * Returns the value of the given box name for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @param algod An algod client instance\n * @returns The current box value as an ABI value\n */\nasync function getAppBoxValueFromABIType(request, algod) {\n return new AppManager(algod).getBoxValueFromABIType({\n appId: BigInt(request.appId),\n boxName: typeof request.boxName !== 'string' && 'name' in request.boxName ? request.boxName.nameRaw : request.boxName,\n type: request.type,\n });\n}\n/**\n * @deprecated Use `algorand.app.getBoxValuesFromABIType` instead.\n * Returns the value of the given box names for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @param algod An algod client instance\n * @returns The current box values as an ABI value in the same order as the passed in box names\n */\nasync function getAppBoxValuesFromABIType(request, algod) {\n return new AppManager(algod).getBoxValuesFromABIType({\n appId: BigInt(request.appId),\n boxNames: request.boxNames.map((b) => (typeof b !== 'string' && 'name' in b ? b.nameRaw : b)),\n type: request.type,\n });\n}\n/**\n * @deprecated Use `AppManager.decodeAppState` instead.\n *\n * Converts an array of global/local state values from the algod api to a more friendly\n * generic object keyed by the UTF-8 value of the key.\n * @param state A `global-state`, `local-state`, `global-state-deltas` or `local-state-deltas`\n * @returns An object keyeed by the UTF-8 representation of the key with various parsings of the values\n */\nfunction decodeAppState(state) {\n return AppManager.decodeAppState(state);\n}\n/**\n * @deprecated Use `TransactionComposer` methods to construct transactions instead.\n *\n * Returns the app args ready to load onto an app `Transaction` object\n * @param args The app call args\n * @returns The args ready to load into a `Transaction`\n */\nfunction getAppArgsForTransaction(args) {\n if (!args)\n return undefined;\n const encoder = new TextEncoder();\n return {\n accounts: args?.accounts?.map(_getAccountAddress),\n appArgs: args?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a)),\n boxes: args.boxes?.map(getBoxReference),\n foreignApps: args?.apps,\n foreignAssets: args?.assets,\n lease: encodeLease(args?.lease),\n };\n}\n/**\n * @deprecated Use `TransactionComposer` methods to construct transactions instead.\n *\n * Returns the app args ready to load onto an ABI method call in `AtomicTransactionComposer`\n * @param args The ABI app call args\n * @param from The transaction signer\n * @returns The parameters ready to pass into `addMethodCall` within AtomicTransactionComposer\n */\nasync function getAppArgsForABICall(args, from) {\n return _getAppArgsForABICall(args, from);\n}\n/**\n * @deprecated Use `AppManager.getBoxReference()` instead.\n *\n * Returns a `algosdk.BoxReference` given a `BoxIdentifier` or `BoxReference`.\n * @param box The box to return a reference for\n * @returns The box reference ready to pass into a `Transaction`\n */\nfunction getBoxReference(box) {\n return _getBoxReference(box);\n}\nfunction _getAccountAddress(account) {\n return typeof account === 'string' ? account : algosdk.encodeAddress(account.publicKey);\n}\n/**\n * @deprecated Use `algorand.app.getById` instead.\n *\n * Gets the current data for the given app from algod.\n *\n * @param appId The id of the app\n * @param algod An algod client\n * @returns The data about the app\n */\nasync function getAppById(appId, algod) {\n return modelsv2.Application.from_obj_for_encoding(await algod.getApplicationByID(toNumber(appId)).do());\n}\n/**\n * @deprecated Use `algorand.app.compileTeal` instead.\n *\n * Compiles the given TEAL using algod and returns the result, including source map.\n *\n * @param algod An algod client\n * @param tealCode The TEAL code\n * @returns The information about the compiled file\n */\nasync function compileTeal(tealCode, algod) {\n return await new AppManager(algod).compileTeal(tealCode);\n}\n/**\n * @deprecated Use `abiMethod.getSignature()` or `new ABIMethod(abiMethodParams).getSignature()` instead.\n *\n * Returns the encoded ABI spec for a given ABI Method\n * @param method The method to return a signature for\n * @returns The encoded ABI method spec e.g. `method_name(uint64,string)string`\n */\nconst getABIMethodSignature = (method) => {\n return 'getSignature' in method ? method.getSignature() : new ABIMethod(method).getSignature();\n};\n\nexport { callApp, compileTeal, createApp, decodeAppState, getABIMethodSignature, getABIReturn, getAppArgsForABICall, getAppArgsForTransaction, getAppBoxNames, getAppBoxValue, getAppBoxValueFromABIType, getAppBoxValues, getAppBoxValuesFromABIType, getAppById, getAppGlobalState, getAppLocalState, getAppOnCompleteAction, getBoxReference, updateApp };\n//# sourceMappingURL=app.mjs.map\n","import algosdk from 'algosdk';\n\nvar modelsv2 = algosdk.modelsv2;\n/**\n * Performs a simulation of the transactions loaded into the given AtomicTransactionComposer.\n * @param atc The AtomicTransactionComposer with transaction(s) loaded.\n * @param algod An Algod client to perform the simulation.\n * @returns The simulation result, which includes various details about how the transactions would be processed.\n */\nasync function performAtomicTransactionComposerSimulate(atc, algod) {\n const unsignedTransactionsSigners = atc.buildGroup();\n const decodedSignedTransactions = unsignedTransactionsSigners.map((ts) => algosdk.encodeUnsignedSimulateTransaction(ts.txn));\n const simulateRequest = new modelsv2.SimulateRequest({\n allowEmptySignatures: true,\n fixSigners: true,\n allowMoreLogging: true,\n execTraceConfig: new modelsv2.SimulateTraceConfig({\n enable: true,\n scratchChange: true,\n stackChange: true,\n stateChange: true,\n }),\n txnGroups: [\n new modelsv2.SimulateRequestTransactionGroup({\n txns: decodedSignedTransactions.map((txn) => algosdk.decodeObj(txn)),\n }),\n ],\n });\n const simulateResult = await algod.simulateTransactions(simulateRequest).do();\n return simulateResult;\n}\n\nexport { performAtomicTransactionComposerSimulate };\n//# sourceMappingURL=perform-atomic-transaction-composer-simulate.mjs.map\n","import algosdk from 'algosdk';\nimport { Config } from '../config.mjs';\nimport { chunkArray } from '../util.mjs';\nimport { MAX_TRANSACTION_GROUP_SIZE } from './composer.mjs';\n\nvar AssetModel = algosdk.modelsv2.Asset;\n/** Allows management of asset information. */\nclass AssetManager {\n /**\n * Create a new asset manager.\n * @param algod An algod client\n * @param newGroup A function that creates a new `TransactionComposer` transaction group\n * @example Create a new asset manager\n * ```typescript\n * const assetManager = new AssetManager(algod, () => new TransactionComposer({algod, () => signer, () => suggestedParams}))\n * ```\n */\n constructor(algod, newGroup) {\n this._algod = algod;\n this._newGroup = newGroup;\n }\n /**\n * Returns the current asset information for the asset with the given ID.\n *\n * @example\n * ```typescript\n * const assetInfo = await assetManager.getById(12353n);\n * ```\n *\n * @param assetId The ID of the asset\n * @returns The asset information\n */\n async getById(assetId) {\n const asset = AssetModel.from_obj_for_encoding(await this._algod.getAssetByID(Number(assetId)).do());\n return {\n assetId: BigInt(asset.index),\n total: BigInt(asset.params.total),\n decimals: Number(asset.params.decimals),\n assetName: asset.params.name,\n assetNameAsBytes: asset.params.nameB64,\n unitName: asset.params.unitName,\n unitNameAsBytes: asset.params.unitNameB64,\n url: asset.params.url,\n urlAsBytes: asset.params.urlB64,\n creator: asset.params.creator,\n manager: asset.params.manager,\n clawback: asset.params.clawback,\n freeze: asset.params.freeze,\n reserve: asset.params.reserve,\n defaultFrozen: asset.params.defaultFrozen,\n metadataHash: asset.params.metadataHash,\n };\n }\n /**\n * Returns the given sender account's asset holding for a given asset.\n *\n * @example\n * ```typescript\n * const address = \"XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA\";\n * const assetId = 123345n;\n * const accountInfo = await algorand.asset.getAccountInformation(address, assetId);\n * ```\n *\n * [Response data schema details](https://developer.algorand.org/docs/rest-apis/algod/#get-v2accountsaddressassetsasset-id)\n * @param sender The address of the sender/account to look up\n * @param assetId The ID of the asset to return a holding for\n * @returns The account asset holding information\n */\n async getAccountInformation(sender, assetId) {\n const info = await this._algod.accountAssetInformation(typeof sender === 'string' ? sender : sender.addr, Number(assetId)).do();\n return {\n assetId: BigInt(assetId),\n balance: BigInt(info['asset-holding']['amount']),\n frozen: info['asset-holding']['is-frozen'] === true,\n round: BigInt(info['round']),\n };\n }\n /**\n * Opt an account in to a list of Algorand Standard Assets.\n *\n * Transactions will be sent in batches of 16 as transaction groups.\n *\n * @param account The account to opt-in\n * @param assetIds The list of asset IDs to opt-in to\n * @param options Any parameters to control the transaction or execution of the transaction\n * @example Example using AlgorandClient\n * ```typescript\n * // Basic example\n * algorand.asset.bulkOptIn(\"ACCOUNTADDRESS\", [12345n, 67890n])\n * // With configuration\n * algorand.asset.bulkOptIn(\"ACCOUNTADDRESS\", [12345n, 67890n], { maxFee: (1000).microAlgo(), suppressLog: true })\n * ```\n * @returns An array of records matching asset ID to transaction ID of the opt in\n */\n async bulkOptIn(account, assetIds, options) {\n const results = [];\n for (const assetGroup of chunkArray(assetIds, MAX_TRANSACTION_GROUP_SIZE)) {\n const composer = this._newGroup();\n for (const assetId of assetGroup) {\n composer.addAssetOptIn({\n ...options,\n sender: typeof account === 'string' ? account : account.addr,\n assetId: BigInt(assetId),\n });\n }\n const result = await composer.send(options);\n Config.getLogger(options?.suppressLog).info(`Successfully opted in ${account} for assets ${assetGroup.join(', ')} with transaction IDs ${result.txIds.join(', ')}` +\n `\\n Grouped under ${result.groupId} in round ${result.confirmations?.[0]?.confirmedRound}.`);\n assetGroup.forEach((assetId, index) => {\n results.push({ assetId: BigInt(assetId), transactionId: result.txIds[index] });\n });\n }\n return results;\n }\n /**\n * Opt an account out of a list of Algorand Standard Assets.\n *\n * Transactions will be sent in batches of 16 as transaction groups.\n *\n * @param account The account to opt-in\n * @param assetIds The list of asset IDs to opt-out of\n * @param options Any parameters to control the transaction or execution of the transaction\n * @example Example using AlgorandClient\n * ```typescript\n * // Basic example\n * algorand.asset.bulkOptOut(\"ACCOUNTADDRESS\", [12345n, 67890n])\n * // With configuration\n * algorand.asset.bulkOptOut(\"ACCOUNTADDRESS\", [12345n, 67890n], { ensureZeroBalance: true, maxFee: (1000).microAlgo(), suppressLog: true })\n * ```\n * @returns An array of records matching asset ID to transaction ID of the opt in\n */\n async bulkOptOut(account, assetIds, options) {\n const results = [];\n const sender = typeof account === 'string' ? account : account.addr;\n for (const assetGroup of chunkArray(assetIds, MAX_TRANSACTION_GROUP_SIZE)) {\n const composer = this._newGroup();\n const notOptedInAssetIds = [];\n const nonZeroBalanceAssetIds = [];\n for (const assetId of assetGroup) {\n if (options?.ensureZeroBalance !== false) {\n try {\n const accountAssetInfo = await this.getAccountInformation(sender, assetId);\n if (accountAssetInfo.balance !== 0n) {\n nonZeroBalanceAssetIds.push(BigInt(assetId));\n }\n }\n catch {\n notOptedInAssetIds.push(BigInt(assetId));\n }\n }\n }\n if (notOptedInAssetIds.length > 0 || nonZeroBalanceAssetIds.length > 0) {\n throw new Error(`Account ${sender}${notOptedInAssetIds.length > 0 ? ` is not opted-in to Asset${notOptedInAssetIds.length > 1 ? 's' : ''} ${notOptedInAssetIds.join(', ')}` : ''}${nonZeroBalanceAssetIds.length > 0\n ? ` has non-zero balance for Asset${nonZeroBalanceAssetIds.length > 1 ? 's' : ''} ${nonZeroBalanceAssetIds.join(', ')}`\n : ''}; can't opt-out.`);\n }\n for (const assetId of assetGroup) {\n composer.addAssetOptOut({\n ...options,\n creator: (await this.getById(BigInt(assetId))).creator,\n sender,\n assetId: BigInt(assetId),\n });\n }\n const result = await composer.send(options);\n Config.getLogger(options?.suppressLog).info(`Successfully opted ${account} out of assets ${assetGroup.join(', ')} with transaction IDs ${result.txIds.join(', ')}` +\n `\\n Grouped under ${result.groupId} in round ${result.confirmations?.[0]?.confirmedRound}.`);\n assetGroup.forEach((assetId, index) => {\n results.push({ assetId: BigInt(assetId), transactionId: result.txIds[index] });\n });\n }\n return results;\n }\n}\n\nexport { AssetManager };\n//# sourceMappingURL=asset-manager.mjs.map\n","export var IconsManifest = [\n {\n \"id\": \"ci\",\n \"name\": \"Circum Icons\",\n \"projectUrl\": \"https://circumicons.com/\",\n \"license\": \"MPL-2.0 license\",\n \"licenseUrl\": \"https://github.com/Klarr-Agency/Circum-Icons/blob/main/LICENSE\"\n },\n {\n \"id\": \"fa\",\n \"name\": \"Font Awesome 5\",\n \"projectUrl\": \"https://fontawesome.com/\",\n \"license\": \"CC BY 4.0 License\",\n \"licenseUrl\": \"https://creativecommons.org/licenses/by/4.0/\"\n },\n {\n \"id\": \"fa6\",\n \"name\": \"Font Awesome 6\",\n \"projectUrl\": \"https://fontawesome.com/\",\n \"license\": \"CC BY 4.0 License\",\n \"licenseUrl\": \"https://creativecommons.org/licenses/by/4.0/\"\n },\n {\n \"id\": \"io\",\n \"name\": \"Ionicons 4\",\n \"projectUrl\": \"https://ionicons.com/\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/ionic-team/ionicons/blob/master/LICENSE\"\n },\n {\n \"id\": \"io5\",\n \"name\": \"Ionicons 5\",\n \"projectUrl\": \"https://ionicons.com/\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/ionic-team/ionicons/blob/master/LICENSE\"\n },\n {\n \"id\": \"md\",\n \"name\": \"Material Design icons\",\n \"projectUrl\": \"http://google.github.io/material-design-icons/\",\n \"license\": \"Apache License Version 2.0\",\n \"licenseUrl\": \"https://github.com/google/material-design-icons/blob/master/LICENSE\"\n },\n {\n \"id\": \"ti\",\n \"name\": \"Typicons\",\n \"projectUrl\": \"http://s-ings.com/typicons/\",\n \"license\": \"CC BY-SA 3.0\",\n \"licenseUrl\": \"https://creativecommons.org/licenses/by-sa/3.0/\"\n },\n {\n \"id\": \"go\",\n \"name\": \"Github Octicons icons\",\n \"projectUrl\": \"https://octicons.github.com/\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/primer/octicons/blob/master/LICENSE\"\n },\n {\n \"id\": \"fi\",\n \"name\": \"Feather\",\n \"projectUrl\": \"https://feathericons.com/\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/feathericons/feather/blob/master/LICENSE\"\n },\n {\n \"id\": \"lu\",\n \"name\": \"Lucide\",\n \"projectUrl\": \"https://lucide.dev/\",\n \"license\": \"ISC\",\n \"licenseUrl\": \"https://github.com/lucide-icons/lucide/blob/main/LICENSE\"\n },\n {\n \"id\": \"gi\",\n \"name\": \"Game Icons\",\n \"projectUrl\": \"https://game-icons.net/\",\n \"license\": \"CC BY 3.0\",\n \"licenseUrl\": \"https://creativecommons.org/licenses/by/3.0/\"\n },\n {\n \"id\": \"wi\",\n \"name\": \"Weather Icons\",\n \"projectUrl\": \"https://erikflowers.github.io/weather-icons/\",\n \"license\": \"SIL OFL 1.1\",\n \"licenseUrl\": \"http://scripts.sil.org/OFL\"\n },\n {\n \"id\": \"di\",\n \"name\": \"Devicons\",\n \"projectUrl\": \"https://vorillaz.github.io/devicons/\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"ai\",\n \"name\": \"Ant Design Icons\",\n \"projectUrl\": \"https://github.com/ant-design/ant-design-icons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"bs\",\n \"name\": \"Bootstrap Icons\",\n \"projectUrl\": \"https://github.com/twbs/icons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"ri\",\n \"name\": \"Remix Icon\",\n \"projectUrl\": \"https://github.com/Remix-Design/RemixIcon\",\n \"license\": \"Apache License Version 2.0\",\n \"licenseUrl\": \"http://www.apache.org/licenses/\"\n },\n {\n \"id\": \"fc\",\n \"name\": \"Flat Color Icons\",\n \"projectUrl\": \"https://github.com/icons8/flat-color-icons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"gr\",\n \"name\": \"Grommet-Icons\",\n \"projectUrl\": \"https://github.com/grommet/grommet-icons\",\n \"license\": \"Apache License Version 2.0\",\n \"licenseUrl\": \"http://www.apache.org/licenses/\"\n },\n {\n \"id\": \"hi\",\n \"name\": \"Heroicons\",\n \"projectUrl\": \"https://github.com/tailwindlabs/heroicons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"hi2\",\n \"name\": \"Heroicons 2\",\n \"projectUrl\": \"https://github.com/tailwindlabs/heroicons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"si\",\n \"name\": \"Simple Icons\",\n \"projectUrl\": \"https://simpleicons.org/\",\n \"license\": \"CC0 1.0 Universal\",\n \"licenseUrl\": \"https://creativecommons.org/publicdomain/zero/1.0/\"\n },\n {\n \"id\": \"sl\",\n \"name\": \"Simple Line Icons\",\n \"projectUrl\": \"https://thesabbir.github.io/simple-line-icons/\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"im\",\n \"name\": \"IcoMoon Free\",\n \"projectUrl\": \"https://github.com/Keyamoon/IcoMoon-Free\",\n \"license\": \"CC BY 4.0 License\",\n \"licenseUrl\": \"https://github.com/Keyamoon/IcoMoon-Free/blob/master/License.txt\"\n },\n {\n \"id\": \"bi\",\n \"name\": \"BoxIcons\",\n \"projectUrl\": \"https://github.com/atisawd/boxicons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/atisawd/boxicons/blob/master/LICENSE\"\n },\n {\n \"id\": \"cg\",\n \"name\": \"css.gg\",\n \"projectUrl\": \"https://github.com/astrit/css.gg\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"vsc\",\n \"name\": \"VS Code Icons\",\n \"projectUrl\": \"https://github.com/microsoft/vscode-codicons\",\n \"license\": \"CC BY 4.0\",\n \"licenseUrl\": \"https://creativecommons.org/licenses/by/4.0/\"\n },\n {\n \"id\": \"tb\",\n \"name\": \"Tabler Icons\",\n \"projectUrl\": \"https://github.com/tabler/tabler-icons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://opensource.org/licenses/MIT\"\n },\n {\n \"id\": \"tfi\",\n \"name\": \"Themify Icons\",\n \"projectUrl\": \"https://github.com/lykmapipo/themify-icons\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/thecreation/standard-icons/blob/master/modules/themify-icons/LICENSE\"\n },\n {\n \"id\": \"rx\",\n \"name\": \"Radix Icons\",\n \"projectUrl\": \"https://icons.radix-ui.com\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/radix-ui/icons/blob/master/LICENSE\"\n },\n {\n \"id\": \"pi\",\n \"name\": \"Phosphor Icons\",\n \"projectUrl\": \"https://github.com/phosphor-icons/core\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/phosphor-icons/core/blob/main/LICENSE\"\n },\n {\n \"id\": \"lia\",\n \"name\": \"Icons8 Line Awesome\",\n \"projectUrl\": \"https://icons8.com/line-awesome\",\n \"license\": \"MIT\",\n \"licenseUrl\": \"https://github.com/icons8/line-awesome/blob/master/LICENSE.md\"\n }\n]","import React from \"react\";\nexport var DefaultContext = {\n color: undefined,\n size: undefined,\n className: undefined,\n style: undefined,\n attr: undefined\n};\nexport var IconContext = React.createContext && /*#__PURE__*/React.createContext(DefaultContext);","var _excluded = [\"attr\", \"size\", \"title\"];\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nimport React from \"react\";\nimport { IconContext, DefaultContext } from \"./iconContext.mjs\";\nfunction Tree2Element(tree) {\n return tree && tree.map((node, i) => /*#__PURE__*/React.createElement(node.tag, _objectSpread({\n key: i\n }, node.attr), Tree2Element(node.child)));\n}\nexport function GenIcon(data) {\n return props => /*#__PURE__*/React.createElement(IconBase, _extends({\n attr: _objectSpread({}, data.attr)\n }, props), Tree2Element(data.child));\n}\nexport function IconBase(props) {\n var elem = conf => {\n var {\n attr,\n size,\n title\n } = props,\n svgProps = _objectWithoutProperties(props, _excluded);\n var computedSize = size || conf.size || \"1em\";\n var className;\n if (conf.className) className = conf.className;\n if (props.className) className = (className ? className + \" \" : \"\") + props.className;\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n stroke: \"currentColor\",\n fill: \"currentColor\",\n strokeWidth: \"0\"\n }, conf.attr, attr, svgProps, {\n className: className,\n style: _objectSpread(_objectSpread({\n color: props.color || conf.color\n }, conf.style), props.style),\n height: computedSize,\n width: computedSize,\n xmlns: \"http://www.w3.org/2000/svg\"\n }), title && /*#__PURE__*/React.createElement(\"title\", null, title), props.children);\n };\n return IconContext !== undefined ? /*#__PURE__*/React.createElement(IconContext.Consumer, null, conf => elem(conf)) : elem(DefaultContext);\n}","export * from \"./iconsManifest.mjs\";\nexport * from \"./iconBase.mjs\";\nexport * from \"./iconContext.mjs\";","class AsyncEventEmitter {\n constructor() {\n this.listenerWrapperMap = new WeakMap();\n this.listenerMap = {};\n this.off = this.removeListener;\n }\n async emitAsync(eventName, event) {\n for (const listener of this.listenerMap[eventName] ?? []) {\n await listener(event, eventName);\n }\n }\n on(eventName, listener) {\n if (!this.listenerMap[eventName])\n this.listenerMap[eventName] = [];\n this.listenerMap[eventName].push(listener);\n return this;\n }\n once(eventName, listener) {\n const wrappedListener = async (event, eventName) => {\n try {\n return await listener(event, eventName);\n }\n finally {\n this.removeListener(eventName, wrappedListener);\n }\n };\n this.listenerWrapperMap.set(listener, wrappedListener);\n return this.on(eventName, wrappedListener);\n }\n removeListener(eventName, listener) {\n const wrappedListener = this.listenerWrapperMap.get(listener);\n if (wrappedListener) {\n this.listenerWrapperMap.delete(listener);\n if (this.listenerMap[eventName]?.indexOf(wrappedListener) !== -1) {\n this.listenerMap[eventName].splice(this.listenerMap[eventName].indexOf(wrappedListener), 1);\n }\n }\n else {\n if (this.listenerMap[eventName]?.indexOf(listener) !== -1) {\n this.listenerMap[eventName].splice(this.listenerMap[eventName].indexOf(listener), 1);\n }\n }\n return this;\n }\n}\n\nexport { AsyncEventEmitter };\n//# sourceMappingURL=async-event-emitter.mjs.map\n","import { AsyncEventEmitter } from './async-event-emitter.mjs';\nimport { nullLogger, consoleLogger } from './logging.mjs';\n\n/** Updatable AlgoKit config */\nclass UpdatableConfig {\n get populateAppCallResources() {\n return this.config.populateAppCallResources;\n }\n get logger() {\n return this.config.logger;\n }\n get debug() {\n return this.config.debug;\n }\n get projectRoot() {\n return this.config.projectRoot;\n }\n get traceAll() {\n return this.config.traceAll;\n }\n get traceBufferSizeMb() {\n return this.config.traceBufferSizeMb;\n }\n get maxSearchDepth() {\n return this.config.maxSearchDepth;\n }\n get events() {\n return this.config.events;\n }\n /**\n * Returns the current logger, or the null logger if true is passed in to `returnNullLogger`\n * @param returnNullLogger Whether or not to return the null logger\n * @returns The requested logger\n */\n getLogger(returnNullLogger) {\n if (returnNullLogger) {\n return nullLogger;\n }\n return this.logger;\n }\n /**\n * Temporarily run with debug set to true.\n * @param lambda A lambda expression with code to run with debug config set to true\n */\n withDebug(lambda) {\n const original = this.config.debug;\n try {\n this.config.debug = true;\n lambda();\n }\n finally {\n this.config.debug = original;\n }\n }\n constructor() {\n this.config = {\n logger: consoleLogger,\n debug: false,\n projectRoot: null,\n traceAll: false,\n traceBufferSizeMb: 256,\n maxSearchDepth: 10,\n populateAppCallResources: false,\n events: new AsyncEventEmitter(),\n };\n }\n /**\n * Update the AlgoKit configuration with your own configuration settings\n * @param newConfig Partial or complete config to replace\n */\n configure(newConfig) {\n this.config = { ...this.config, ...newConfig };\n }\n}\n\nexport { UpdatableConfig };\n//# sourceMappingURL=config.mjs.map\n","import { UpdatableConfig } from './types/config.mjs';\n\n/** The AlgoKit config. To update it use the configure method. */\nconst Config = new UpdatableConfig();\n\nexport { Config };\n//# sourceMappingURL=config.mjs.map\n","/**\n * Converts a value which might be a number or a bigint into a number to be used with apis that don't support bigint.\n *\n * Throws an UnsafeConversionError if the conversion would result in an unsafe integer for the Number type\n * @param value\n */\nconst toNumber = (value) => {\n if (typeof value === 'number')\n return value;\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new UnsafeConversionError(`Cannot convert ${value} to a Number as it is larger than the maximum safe integer the Number type can hold.`);\n }\n else if (value < BigInt(Number.MIN_SAFE_INTEGER)) {\n throw new UnsafeConversionError(`Cannot convert ${value} to a Number as it is smaller than the minimum safe integer the Number type can hold.`);\n }\n return Number(value);\n};\nclass UnsafeConversionError extends Error {\n}\n/**\n * Calculates the amount of funds to add to a wallet to bring it up to the minimum spending balance.\n * @param minSpendingBalance The minimum spending balance for the wallet\n * @param currentSpendingBalance The current spending balance for the wallet\n * @param minFundingIncrement The minimum amount of funds that can be added to the wallet\n * @returns The amount of funds to add to the wallet or null if the wallet is already above the minimum spending balance\n */\nconst calculateFundAmount = (minSpendingBalance, currentSpendingBalance, minFundingIncrement) => {\n if (minSpendingBalance > currentSpendingBalance) {\n const minFundAmount = minSpendingBalance - currentSpendingBalance;\n return BigInt(Math.max(Number(minFundAmount), Number(minFundingIncrement)));\n }\n else {\n return null;\n }\n};\n/**\n * Returns the given array split into chunks of `batchSize` batches.\n * @param array The array to chunk\n * @param batchSize The size of batches to split the array into\n * @returns A generator that yields the array split into chunks of `batchSize` batches\n */\nfunction* chunkArray(array, batchSize) {\n for (let i = 0; i < array.length; i += batchSize)\n yield array.slice(i, i + batchSize);\n}\n/**\n * Memoize calls to the given function in an in-memory map.\n * @param fn The function to memoize\n * @returns The memoized function\n */\nconst memoize = (fn) => {\n const cache = new Map();\n const cached = function (val) {\n return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);\n };\n cached.cache = cache;\n return cached;\n};\nconst binaryStartsWith = (base, startsWith) => {\n if (startsWith.length > base.length)\n return false;\n for (let i = 0; i < startsWith.length; i++) {\n if (base[i] !== startsWith[i])\n return false;\n }\n return true;\n};\nconst defaultJsonValueReplacer = (key, value) => {\n if (typeof value === 'bigint') {\n try {\n return toNumber(value);\n }\n catch {\n return value.toString();\n }\n }\n return value;\n};\nconst asJson = (value, replacer = defaultJsonValueReplacer, space) => {\n return JSON.stringify(value, replacer, space);\n};\n\nexport { UnsafeConversionError, asJson, binaryStartsWith, calculateFundAmount, chunkArray, defaultJsonValueReplacer, memoize, toNumber };\n//# sourceMappingURL=util.mjs.map\n","/** The name of the TEAL template variable for deploy-time immutability control */\nconst UPDATABLE_TEMPLATE_NAME = 'TMPL_UPDATABLE';\n/** The name of the TEAL template variable for deploy-time permanence control */\nconst DELETABLE_TEMPLATE_NAME = 'TMPL_DELETABLE';\n/** The app create/update [ARC-2](https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md) transaction note prefix */\nconst APP_DEPLOY_NOTE_DAPP = 'ALGOKIT_DEPLOYER';\n/** The maximum number of bytes in a single app code page */\nconst APP_PAGE_MAX_SIZE = 2048;\n/** First 4 bytes of SHA-512/256 hash of \"return\" for retrieving ABI return values */\nconst ABI_RETURN_PREFIX = new Uint8Array([21, 31, 124, 117]);\n/** What action to perform when deploying an app and an update is detected in the TEAL code */\nvar OnUpdate;\n(function (OnUpdate) {\n /** Fail the deployment */\n OnUpdate[OnUpdate[\"Fail\"] = 0] = \"Fail\";\n /** Update the app */\n OnUpdate[OnUpdate[\"UpdateApp\"] = 1] = \"UpdateApp\";\n /** Delete the app and create a new one in its place */\n OnUpdate[OnUpdate[\"ReplaceApp\"] = 2] = \"ReplaceApp\";\n /** Create a new app */\n OnUpdate[OnUpdate[\"AppendApp\"] = 3] = \"AppendApp\";\n})(OnUpdate || (OnUpdate = {}));\n/** What action to perform when deploying an app and a breaking schema change is detected */\nvar OnSchemaBreak;\n(function (OnSchemaBreak) {\n /** Fail the deployment */\n OnSchemaBreak[OnSchemaBreak[\"Fail\"] = 0] = \"Fail\";\n /** Delete the app and create a new one in its place */\n OnSchemaBreak[OnSchemaBreak[\"ReplaceApp\"] = 1] = \"ReplaceApp\";\n /** Create a new app */\n OnSchemaBreak[OnSchemaBreak[\"AppendApp\"] = 2] = \"AppendApp\";\n})(OnSchemaBreak || (OnSchemaBreak = {}));\n\nexport { ABI_RETURN_PREFIX, APP_DEPLOY_NOTE_DAPP, APP_PAGE_MAX_SIZE, DELETABLE_TEMPLATE_NAME, OnSchemaBreak, OnUpdate, UPDATABLE_TEMPLATE_NAME };\n//# sourceMappingURL=app.mjs.map\n","import algosdk from 'algosdk';\nimport { Buffer } from 'buffer';\nimport { Config } from '../config.mjs';\nimport { asJson, defaultJsonValueReplacer } from '../util.mjs';\nimport { AppManager } from './app-manager.mjs';\n\nconst getMethodCallForLog = ({ method, args }) => {\n return `${method.name}(${(args ?? []).map((a) => typeof a === 'object'\n ? asJson(a, (k, v) => {\n const newV = defaultJsonValueReplacer(k, v);\n return newV instanceof Uint8Array ? Buffer.from(newV).toString('base64') : newV;\n })\n : a)})`;\n};\n/** Orchestrates sending transactions for `AlgorandClient`. */\nclass AlgorandClientTransactionSender {\n /**\n * Creates a new `AlgorandClientSender`\n * @param newGroup A lambda that starts a new `TransactionComposer` transaction group\n * @param assetManager An `AssetManager` instance\n */\n constructor(newGroup, assetManager, appManager) {\n /**\n * Send a payment transaction to transfer Algo between accounts.\n * @param params The parameters for the payment transaction\n * @example Basic example\n * ```typescript\n * const result = await algorand.send.payment({\n * sender: 'SENDERADDRESS',\n * receiver: 'RECEIVERADDRESS',\n * amount: (4).algo(),\n * })\n * ```\n * @example Advanced example\n * ```typescript\n * const result = await algorand.send.payment({\n * amount: (4).algo(),\n * receiver: 'RECEIVERADDRESS',\n * sender: 'SENDERADDRESS',\n * closeRemainderTo: 'CLOSEREMAINDERTOADDRESS',\n * lease: 'lease',\n * note: 'note',\n * // Use this with caution, it's generally better to use algorand.account.rekeyAccount\n * rekeyTo: 'REKEYTOADDRESS',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n *\n * @returns The result of the transaction and the transaction that was sent\n */\n this.payment = this._send((c) => c.addPayment, {\n preLog: (params, transaction) => `Sending ${params.amount.microAlgo} µALGO from ${params.sender} to ${params.receiver} via transaction ${transaction.txID()}`,\n });\n /**\n * Create a new Algorand Standard Asset.\n *\n * The account that sends this transaction will automatically be\n * opted in to the asset and will hold all units after creation.\n *\n * @param params The parameters for the asset creation transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.send.assetCreate({sender: \"CREATORADDRESS\", total: 100n})\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.assetCreate({\n * sender: 'CREATORADDRESS',\n * total: 100n,\n * decimals: 2,\n * assetName: 'asset',\n * unitName: 'unit',\n * url: 'url',\n * metadataHash: 'metadataHash',\n * defaultFrozen: false,\n * manager: 'MANAGERADDRESS',\n * reserve: 'RESERVEADDRESS',\n * freeze: 'FREEZEADDRESS',\n * clawback: 'CLAWBACKADDRESS',\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetCreate = async (params) => {\n const result = await this._send((c) => c.addAssetCreate, {\n postLog: (params, result) => `Created asset${params.assetName ? ` ${params.assetName}` : ''}${params.unitName ? ` (${params.unitName})` : ''} with ${params.total} units and ${params.decimals ?? 0} decimals created by ${params.sender} with ID ${result.confirmation.assetIndex} via transaction ${result.txIds.at(-1)}`,\n })(params);\n return { ...result, assetId: BigInt(result.confirmation.assetIndex ?? 0) };\n };\n /**\n * Configure an existing Algorand Standard Asset.\n *\n * **Note:** The manager, reserve, freeze, and clawback addresses\n * are immutably empty if they are not set. If manager is not set then\n * all fields are immutable from that point forward.\n *\n * @param params The parameters for the asset config transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.send.assetConfig({sender: \"MANAGERADDRESS\", assetId: 123456n, manager: \"MANAGERADDRESS\" })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.assetConfig({\n * sender: 'MANAGERADDRESS',\n * assetId: 123456n,\n * manager: 'MANAGERADDRESS',\n * reserve: 'RESERVEADDRESS',\n * freeze: 'FREEZEADDRESS',\n * clawback: 'CLAWBACKADDRESS',\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetConfig = this._send((c) => c.addAssetConfig, {\n preLog: (params, transaction) => `Configuring asset with ID ${params.assetId} via transaction ${transaction.txID()}`,\n });\n /**\n * Freeze or unfreeze an Algorand Standard Asset for an account.\n *\n * @param params The parameters for the asset freeze transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.send.assetFreeze({sender: \"MANAGERADDRESS\", assetId: 123456n, account: \"ACCOUNTADDRESS\", frozen: true })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.assetFreeze({\n * sender: 'MANAGERADDRESS',\n * assetId: 123456n,\n * account: 'ACCOUNTADDRESS',\n * frozen: true,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetFreeze = this._send((c) => c.addAssetFreeze, {\n preLog: (params, transaction) => `Freezing asset with ID ${params.assetId} via transaction ${transaction.txID()}`,\n });\n /**\n * Destroys an Algorand Standard Asset.\n *\n * Created assets can be destroyed only by the asset manager account.\n * All of the assets must be owned by the creator of the asset before\n * the asset can be deleted.\n *\n * @param params The parameters for the asset destroy transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.send.assetDestroy({sender: \"MANAGERADDRESS\", assetId: 123456n })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.assetDestroy({\n * sender: 'MANAGERADDRESS',\n * assetId: 123456n,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetDestroy = this._send((c) => c.addAssetDestroy, {\n preLog: (params, transaction) => `Destroying asset with ID ${params.assetId} via transaction ${transaction.txID()}`,\n });\n /**\n * Transfer an Algorand Standard Asset.\n *\n * @param params The parameters for the asset transfer transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.send.assetTransfer({sender: \"HOLDERADDRESS\", assetId: 123456n, amount: 1n, receiver: \"RECEIVERADDRESS\" })\n * ```\n * @example Advanced example (with clawback)\n * ```typescript\n * await algorand.send.assetTransfer({\n * sender: 'CLAWBACKADDRESS',\n * assetId: 123456n,\n * amount: 1n,\n * receiver: 'RECEIVERADDRESS',\n * clawbackTarget: 'HOLDERADDRESS',\n * // This field needs to be used with caution\n * closeAssetTo: 'ADDRESSTOCLOSETO'\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetTransfer = this._send((c) => c.addAssetTransfer, {\n preLog: (params, transaction) => `Transferring ${params.amount} units of asset with ID ${params.assetId} from ${params.sender} to ${params.receiver} via transaction ${transaction.txID()}`,\n });\n /**\n * Opt an account into an Algorand Standard Asset.\n *\n * @param params The parameters for the asset opt-in transaction\n *\n * @example Basic example\n * ```typescript\n * await algorand.send.assetOptIn({sender: \"SENDERADDRESS\", assetId: 123456n })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.assetOptIn({\n * sender: 'SENDERADDRESS',\n * assetId: 123456n,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetOptIn = this._send((c) => c.addAssetOptIn, {\n preLog: (params, transaction) => `Opting in ${params.sender} to asset with ID ${params.assetId} via transaction ${transaction.txID()}`,\n });\n /**\n * Opt an account out of an Algorand Standard Asset.\n *\n * *Note:* If the account has a balance of the asset,\n * it will not be able to opt-out unless `ensureZeroBalance`\n * is set to `false` (but then the account will lose the assets).\n *\n * @param params The parameters for the asset opt-out transaction\n *\n * @example Basic example (without creator, will be retrieved from algod)\n * ```typescript\n * await algorand.send.assetOptOut({sender: \"SENDERADDRESS\", assetId: 123456n, ensureZeroBalance: true })\n * ```\n * @example Basic example (with creator)\n * ```typescript\n * await algorand.send.assetOptOut({sender: \"SENDERADDRESS\", creator: \"CREATORADDRESS\", assetId: 123456n, ensureZeroBalance: true })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.assetOptOut({\n * sender: 'SENDERADDRESS',\n * assetId: 123456n,\n * creator: 'CREATORADDRESS',\n * ensureZeroBalance: true,\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n * })\n * ```\n * @returns The result of the transaction and the transaction that was sent\n */\n this.assetOptOut = async (params) => {\n if (params.ensureZeroBalance) {\n let balance = 0n;\n try {\n const accountAssetInfo = await this._assetManager.getAccountInformation(params.sender, params.assetId);\n balance = accountAssetInfo.balance;\n }\n catch {\n throw new Error(`Account ${params.sender} is not opted-in to Asset ${params.assetId}; can't opt-out.`);\n }\n if (balance !== 0n) {\n throw new Error(`Account ${params.sender} does not have a zero balance for Asset ${params.assetId}; can't opt-out.`);\n }\n }\n params.creator = params.creator ?? (await this._assetManager.getById(params.assetId)).creator;\n return await this._send((c) => c.addAssetOptOut, {\n preLog: (params, transaction) => `Opting ${params.sender} out of asset with ID ${params.assetId} to creator ${params.creator} via transaction ${transaction.txID()}`,\n })(params);\n };\n /**\n * Create a smart contract.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app creation transaction\n * @example Basic example\n * ```typescript\n * const result = await algorand.send.appCreate({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE' })\n * const createdAppId = result.appId\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.appCreate({\n * sender: 'CREATORADDRESS',\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * schema: {\n * globalInts: 1,\n * globalByteSlices: 2,\n * localInts: 3,\n * localByteSlices: 4\n * },\n * extraProgramPages: 1,\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCreate = this._sendAppCreateCall((c) => c.addAppCreate, {\n postLog: (params, result) => `App created by ${params.sender} with ID ${result.confirmation.applicationIndex} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Update a smart contract.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app update transaction\n * @example Basic example\n * ```typescript\n * await algorand.send.appUpdate({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE' })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.appUpdate({\n * sender: 'CREATORADDRESS',\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appUpdate = this._sendAppUpdateCall((c) => c.addAppUpdate, {\n postLog: (params, result) => `App ${params.appId} updated ${params.args ? ` with ${params.args.map((a) => Buffer.from(a).toString('base64'))}` : ''} by ${params.sender} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Delete a smart contract.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app deletion transaction\n * @example Basic example\n * ```typescript\n * await algorand.send.appDelete({ sender: 'CREATORADDRESS' })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.appDelete({\n * sender: 'CREATORADDRESS',\n * onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appDelete = this._sendAppCall((c) => c.addAppDelete, {\n postLog: (params, result) => `App ${params.appId} deleted ${params.args ? ` with ${params.args.map((a) => Buffer.from(a).toString('base64'))}` : ''} by ${params.sender} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Call a smart contract.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app call transaction\n * @example Basic example\n * ```typescript\n * await algorand.send.appCall({ sender: 'CREATORADDRESS' })\n * ```\n * @example Advanced example\n * ```typescript\n * await algorand.send.appCall({\n * sender: 'CREATORADDRESS',\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCall = this._sendAppCall((c) => c.addAppCall, {\n postLog: (params, result) => `App ${params.appId} called ${params.args ? ` with ${params.args.map((a) => Buffer.from(a).toString('base64'))}` : ''} by ${params.sender} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Create a smart contract via an ABI method.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app creation transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * const result = await algorand.send.appCreateMethodCall({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE', method: method, args: [\"arg1_value\"] })\n * const createdAppId = result.appId\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appCreate({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * schema: {\n * globalInts: 1,\n * globalByteSlices: 2,\n * localInts: 3,\n * localByteSlices: 4\n * },\n * extraProgramPages: 1,\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCreateMethodCall = this._sendAppCreateCall((c) => c.addAppCreateMethodCall, {\n postLog: (params, result) => `App created by ${params.sender} with ID ${result.confirmation.applicationIndex} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Update a smart contract via an ABI method.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app update transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appUpdateMethodCall({ sender: 'CREATORADDRESS', approvalProgram: 'TEALCODE', clearStateProgram: 'TEALCODE', method: method, args: [\"arg1_value\"] })\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appUpdateMethodCall({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * approvalProgram: \"TEALCODE\",\n * clearStateProgram: \"TEALCODE\",\n * onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appUpdateMethodCall = this._sendAppUpdateCall((c) => c.addAppUpdateMethodCall, {\n postLog: (params, result) => `App ${params.appId} updated with ${getMethodCallForLog(params)} by ${params.sender} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Delete a smart contract via an ABI method.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app deletion transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appDeleteMethodCall({ sender: 'CREATORADDRESS', method: method, args: [\"arg1_value\"] })\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appDeleteMethodCall({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appDeleteMethodCall = this._sendAppCall((c) => c.addAppDeleteMethodCall, {\n postLog: (params, result) => `App ${params.appId} deleted with ${getMethodCallForLog(params)} by ${params.sender} via transaction ${result.txIds.at(-1)}`,\n });\n /**\n * Call a smart contract via an ABI method.\n *\n * Note: you may prefer to use `algorand.client` to get an app client for more advanced functionality.\n *\n * @param params The parameters for the app call transaction\n * @example Basic example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appCallMethodCall({ sender: 'CREATORADDRESS', method: method, args: [\"arg1_value\"] })\n * ```\n * @example Advanced example\n * ```typescript\n * const method = new ABIMethod({\n * name: 'method',\n * args: [{ name: 'arg1', type: 'string' }],\n * returns: { type: 'string' },\n * })\n * await algorand.send.appCallMethodCall({\n * sender: 'CREATORADDRESS',\n * method: method,\n * args: [\"arg1_value\"],\n * onComplete: algosdk.OnApplicationComplete.OptInOC,\n * args: [new Uint8Array(1, 2, 3, 4)]\n * accountReferences: [\"ACCOUNT_1\"]\n * appReferences: [123n, 1234n]\n * assetReferences: [12345n]\n * boxReferences: [\"box1\", {appId: 1234n, name: \"box2\"}]\n * lease: 'lease',\n * note: 'note',\n * // You wouldn't normally set this field\n * firstValidRound: 1000n,\n * validityWindow: 10,\n * extraFee: (1000).microAlgo(),\n * staticFee: (1000).microAlgo(),\n * // Max fee doesn't make sense with extraFee AND staticFee\n * // already specified, but here for completeness\n * maxFee: (3000).microAlgo(),\n * // Signer only needed if you want to provide one,\n * // generally you'd register it with AlgorandClient\n * // against the sender and not need to pass it in\n * signer: transactionSigner,\n * maxRoundsToWaitForConfirmation: 5,\n * suppressLog: true,\n *})\n * ```\n */\n this.appCallMethodCall = this._sendAppCall((c) => c.addAppCallMethodCall, {\n postLog: (params, result) => `App ${params.appId} called with ${getMethodCallForLog(params)} by ${params.sender} via transaction ${result.txIds.at(-1)}`,\n });\n /** Register an online key. */\n this.onlineKeyRegistration = this._send((c) => c.addOnlineKeyRegistration, {\n preLog: (params, transaction) => `Registering online key for ${params.sender} via transaction ${transaction.txID()}`,\n });\n /** Register an offline key. */\n this.offlineKeyRegistration = this._send((c) => c.addOfflineKeyRegistration, {\n preLog: (params, transaction) => `Registering offline key for ${params.sender} via transaction ${transaction.txID()}`,\n });\n this._newGroup = newGroup;\n this._assetManager = assetManager;\n this._appManager = appManager;\n }\n newGroup() {\n return this._newGroup();\n }\n _send(c, log) {\n return async (params) => {\n const composer = this._newGroup();\n // Ensure `this` is properly populated\n c(composer).apply(composer, [params]);\n if (log?.preLog) {\n const transaction = (await composer.build()).transactions.at(-1).txn;\n Config.getLogger(params?.suppressLog).debug(log.preLog(params, transaction));\n }\n const rawResult = await composer.send(params);\n const result = {\n // Last item covers when a group is created by an app call with ABI transaction parameters\n transaction: rawResult.transactions.at(-1),\n confirmation: rawResult.confirmations.at(-1),\n txId: rawResult.txIds.at(-1),\n ...rawResult,\n };\n if (log?.postLog) {\n Config.getLogger(params?.suppressLog).debug(log.postLog(params, result));\n }\n return result;\n };\n }\n _sendAppCall(c, log) {\n return async (params) => {\n const result = await this._send(c, log)(params);\n return { ...result, return: AppManager.getABIReturn(result.confirmation, 'method' in params ? params.method : undefined) };\n };\n }\n _sendAppUpdateCall(c, log) {\n return async (params) => {\n const result = await this._sendAppCall(c, log)(params);\n const compiledApproval = typeof params.approvalProgram === 'string' ? this._appManager.getCompilationResult(params.approvalProgram) : undefined;\n const compiledClear = typeof params.clearStateProgram === 'string' ? this._appManager.getCompilationResult(params.clearStateProgram) : undefined;\n return { ...result, compiledApproval, compiledClear };\n };\n }\n _sendAppCreateCall(c, log) {\n return async (params) => {\n const result = await this._sendAppUpdateCall(c, log)(params);\n return {\n ...result,\n appId: BigInt(result.confirmation.applicationIndex),\n appAddress: algosdk.getApplicationAddress(result.confirmation.applicationIndex),\n };\n };\n }\n}\n\nexport { AlgorandClientTransactionSender };\n//# sourceMappingURL=algorand-client-transaction-sender.mjs.map\n"],"names":["DefaultContext","color","undefined","size","className","style","attr","React","_excluded","_extends","Object","assign","bind","target","i","arguments","length","source","key","prototype","hasOwnProperty","call","apply","ownKeys","e","r","t","keys","getOwnPropertySymbols","o","filter","getOwnPropertyDescriptor","enumerable","push","_objectSpread","forEach","obj","value","_toPropertyKey","_toPrimitive","Symbol","toPrimitive","TypeError","String","Number","defineProperty","configurable","writable","getOwnPropertyDescriptors","defineProperties","GenIcon","data","props","Tree2Element","tree","map","node","tag","child","IconBase","elem","conf","title","svgProps","_objectWithoutProperties","excluded","_objectWithoutPropertiesLoose","indexOf","sourceSymbolKeys","propertyIsEnumerable","computedSize","stroke","fill","strokeWidth","height","width","xmlns","children","IconContext","Consumer"],"sourceRoot":"","ignoreList":[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57]}