diff --git a/docs/index.html b/docs/index.html index 9b558da..17e19dc 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1 +1 @@ -Мультикошелек Ærly Birds
Введите адрес:
Адрес мультикошелька:
Баланс в TON:
Порог голосования (например 5/6, если для подтверждения требуется 5 из 6 подтверждающих):
Подтверждающие:
Предлагающие:
Идентификатор заявки:
Идентификатор заявки:
Тип заявки:
Идентификатор заявки:
Подтверждающие:
Предлагающие:
Порог голосования:
Идентификатор заявки:
Адрес заявки:
Баланс в TON:
Выполнено:
Одобрено:
Подтверждающие:
Заявка истекает:
Действия:
или отправьте 0,1 TON с комментарием "approve" на адрес заявки.
\ No newline at end of file +Мультикошелек Ærly Birds
Введите адрес:
Адрес мультикошелька:
Баланс в TON:
Порог голосования (например 5/6, если для подтверждения требуется 5 из 6 подтверждающих):
Подтверждающие:
Предлагающие:
Идентификатор заявки:
Идентификатор заявки:
Тип заявки:
Идентификатор заявки:
Подтверждающие:
Предлагающие:
Порог голосования:
Идентификатор заявки:
Адрес заявки:
Баланс в TON:
Выполнено:
Одобрено:
Подтверждающие:
Заявка истекает:
Действия:
или отправьте 0,1 TON с комментарием "approve" на адрес заявки.
\ No newline at end of file diff --git a/docs/main.js b/docs/main.js index d1d4be5..4520eab 100644 --- a/docs/main.js +++ b/docs/main.js @@ -1015,4 +1015,4 @@ color: ${e=>e.theme.colors.text.secondary}; `,Tc=Cr(Yn)` margin-top: 32px; -`,Oc=e=>{const t=Gn(e),r=nt(Bs),[n,i]=Ze(!0);let o;(null==r?void 0:r.wallet)&&"universalLink"in r.wallet&&("universal-link"===r.wallet.openMethod||L(r.wallet.universalLink)&&On())&&(o=r.wallet.universalLink);const s=()=>{const e=Jr(),t="returnStrategy"in e?e.returnStrategy:Ga.returnStrategy;if(L(o)){const r=!n();i(!1),El(o,{returnStrategy:t,twaReturnUrl:"twaReturnUrl"in e?e.twaReturnUrl:Ga.twaReturnUrl,forceRedirect:r})}else Tr(Bl(o,t))};return kt(Pc,Bt(t,{get children(){return[Qe((()=>e.icon)),kt(Mc,{get translationKey(){return e.headerTranslationKey},get translationValues(){return e.headerTranslationValues}}),kt(Uc,{get translationKey(){return e.textTranslationKey},get translationValues(){return e.textTranslationValues}}),kt(Pt,{get when(){return"open-wallet"!==e.showButton},get children(){return kt(Tc,{onClick:()=>e.onClose(),get children(){return kt(Sl,{translationKey:"common.close",children:"Close"})}})}}),kt(Pt,{get when(){return"open-wallet"===e.showButton&&o},get children(){return kt(Tc,{onClick:s,get children(){return kt(Sl,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}}))},Rc=e=>{const t=nt(Bs),[r]=Gi();return kt(Oc,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:t.wallet&&"name"in t.wallet?t.wallet.name:r("common.yourWallet",{},"Your wallet")}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return kt(Mo,{size:"m"})},onClose:()=>e.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},jc=e=>kt(Oc,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return kt(Bo,{size:"m"})},onClose:()=>e.onClose(),"data-tc-transaction-canceled-modal":"true"}),Lc=e=>kt(Oc,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return kt(ko,{size:"m"})},onClose:()=>e.onClose(),"data-tc-transaction-sent-modal":"true"}),zc=()=>kt(Ai,{get opened(){var e;return Qe((()=>null!==Jr()))()&&!0===(null==(e=Jr())?void 0:e.openModal)},get enableAndroidBackHandler(){return Ga.enableAndroidBackHandler},onClose:()=>Xr(null),"data-tc-actions-modal-container":"true",get children(){return kt(Mt,{get children(){return[kt(Ut,{get when(){return"transaction-sent"===Jr().name},get children(){return kt(Lc,{onClose:()=>Xr(null)})}}),kt(Ut,{get when(){return"transaction-canceled"===Jr().name},get children(){return kt(jc,{onClose:()=>Xr(null)})}}),kt(Ut,{get when(){return"confirm-transaction"===Jr().name},get children(){return kt(Rc,{onClose:()=>Xr(null)})}})]}})}}),Nc=e=>{const t=((e={},t=(navigator.language in e?navigator.language:Object.keys(e)[0]))=>{const[r,n]=Ze(t),[i,o]=bn(e);return[(e,t,n)=>{const o=Zi(i[r()],e,n||"");return"function"==typeof o?o(t):"string"==typeof o?((e,t,r=/{{(.*?)}}/g)=>e.replace(r,((e,r)=>Zi(t,r,""))))(o,t||{}):o},{add(e,t){o(e,(e=>Object.assign(e||{},t)))},locale:e=>e?n(e):r(),dict:e=>Zi(i,e)}]})(en,Ga.language);return customElements.define(kr,class extends HTMLElement{}),document.body.hasAttribute("ontouchstart")||document.body.setAttribute("ontouchstart",""),kt(Wi.Provider,{value:t,get children(){return kt(Bs.Provider,{get value(){return e.tonConnectUI},get children(){return kt(rn.Provider,{get value(){return Ga.connector},get children(){return[kt(Sr,{}),kt(br,{theme:kn,get children(){return[kt(Pt,{get when(){return Ga.buttonRootId},get children(){return kt(rr,{get mount(){return document.getElementById(Ga.buttonRootId)},get children(){return kt(Va,{})}})}}),kt(nr,{component:kr,get children(){return[kt(Ic,{}),kt(zc,{})]}})]}})]}})}})}})},Dc=()=>{setTimeout((()=>qr({status:"opened",closeReason:null})))},$c=e=>{setTimeout((()=>Xr(e)))};class Fc{constructor(e){Ie(this,"connector"),Ie(this,"setConnectRequestParametersCallback"),Ie(this,"consumers",[]),Ie(this,"state",Vr()),this.connector=e.connector,this.setConnectRequestParametersCallback=e.setConnectRequestParametersCallback,Ye((()=>{const e=Vr();this.state=e,this.consumers.forEach((t=>t(e)))}))}open(){return Pe(this,null,(function*(){const e=(yield this.connector.getWallets()).find(ee);return e?this.connectEmbeddedWallet(e):this.connectExternalWallet()}))}close(){var e;e="action-cancelled",setTimeout((()=>qr({status:"closed",closeReason:e})))}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter((t=>t!==e))}}connectEmbeddedWallet(e){const t=t=>{Qr(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},t)},r=Ga.connectRequestParameters;"loading"===(null==r?void 0:r.state)?this.setConnectRequestParametersCallback(t):t(null==r?void 0:r.value)}connectExternalWallet(){return Pe(this,null,(function*(){return On()&&Rn(),Dc(),new Promise((e=>{const t=this.onStateChange((r=>{const{status:n}=r;"opened"===n&&(t(),e())}))}))}))}}class Kc{constructor(e){Ie(this,"connector"),Ie(this,"consumers",[]),this.connector=e.connector,Ye((()=>{const e=Jr();this.consumers.forEach((t=>t(e)))}))}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter((t=>t!==e))}}}var Hc=r(3515);const Vc="d843619b379084d133f061606beecbf72ae2bf60e0622e808f2a3f631673599b",qc=async(e,t,r)=>{const n=r?"https://testnet.toncenter.com/api/v3/":"https://toncenter.com/api/v3/",i={"Content-Type":"application/json","X-API-Key":Vc},o=await fetch(n+e+"?"+new URLSearchParams(t),{method:"GET",headers:i}),s=await o.json();if(s.error)throw new Error(s.error);return s},Zc=async(e,t,r)=>{const n=r?"https://testnet.tonapi.io/v2/":"https://tonapi.io/v2/",i=await fetch(n+e+"?"+new URLSearchParams(t),{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer AHIQH4F4Y4XR6UIAAAAOGYUHWOWLUS6ZIPEXSCLAPOMMD6FSNMPUKHCIJHIP52YTU4VKURA"}}),o=await i.json();if(o.error)throw new Error(o.error);return o};class Wc{constructor(e,t){this.contractAddress=e,this.isTestnet=t,this.tonClient=new Hc.TonClient({endpoint:t?"https://testnet.toncenter.com/api/v2/jsonRPC":"https://toncenter.com/api/v2/jsonRPC",apiKey:Vc})}getState(){throw new Error("Method not implemented.")}get(e,t){return this.tonClient.runMethod(this.contractAddress,e,t)}external(e){throw new Error("Method not implemented.")}internal(e,t){throw new Error("Method not implemented.")}open(e){throw new Error("Method not implemented.")}getTransactions(e,t,r,n){throw new Error("Method not implemented.")}}const Gc=(e,t)=>a.Address.isFriendly(e)?a.Address.parseFriendly(e).isTestOnly&&!t?"Please enter mainnet address":null:"Invalid address",Yc={},Qc=async(e,t)=>{const r=e.toRawString();let n=Yc[r];return n||(n=(await qc("addressBook",{address:r},t))[r].user_friendly,Yc[r]=n),a.Address.parseFriendly(n)},Jc=async(e,t)=>{const r=await Qc(e,t);return Xc(r)},Xc=e=>{const t=ed(e),r=((e,t)=>(a.Address.parseFriendly(e),(t?"https://testnet.tonviewer.com/":"https://tonviewer.com/")+e))(t,e.isTestOnly);return`${t}`},ed=e=>e.address.toString({bounceable:e.isBounceable,testOnly:e.isTestOnly}),td=(e,t)=>e?t?e.equals(t):!e:!t,rd=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r{if(!e)throw console.error(t),new Error(t)},id=e=>{const t=document.createElement("div");return t.innerText=e,t.innerHTML};class od{}od.multisig={new_order:4145565967,execute:1963556701,execute_internal:2737592767},od.order={approve:2808226575,expired:6,approve_rejected:2947491902,approved:2187369462,init:2624846754},od.actions={send_message:4046986843,update_multisig_params:487390163};class sd{}sd.multisig={unauthorized_new_order:1007,invalid_new_order:1008,not_enough_ton:100,unauthorized_execute:101,singers_outdated:102,invalid_dictionary_sequence:103,expired:111},sd.order={unauthorized_init:104,already_approved:107,already_inited:105,unauthorized_sign:106,expired:111,unknown_op:65535,already_executed:112};class ad{}function ld(e){let t=a.Dictionary.empty(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Address());for(let r=0;r0||e.remainingRefs>0)throw new Error("remaining bits in data")}ad.bitsize={op:32,queryId:64,orderSeqno:256,signerIndex:8,actionIndex:8,time:48};class ud{constructor(e,t,r){this.address=e,this.init=t,this.configuration=r,this.orderSeqno=0n}static createFromAddress(e){let t=new ud(e);return t.orderSeqno=0n,t}static createFromConfig(e,t,r=0){const n=function(e){return(0,a.beginCell)().storeUint(0,ad.bitsize.orderSeqno).storeUint(e.threshold,ad.bitsize.signerIndex).storeRef((0,a.beginCell)().storeDictDirect(ld(e.signers))).storeUint(e.signers.length,ad.bitsize.signerIndex).storeDict(ld(e.proposers)).storeBit(e.allowArbitrarySeqno).endCell()}(e),i={code:t,data:n};return new ud((0,a.contractAddress)(r,i),i,e)}async sendDeploy(e,t,r){await e.internal(t,{value:r,sendMode:a.SendMode.PAY_GAS_SEPARATELY,body:(0,a.beginCell)().storeUint(0,ad.bitsize.op).storeUint(0,ad.bitsize.queryId).endCell()})}static packTransferRequest(e){let t=(0,a.beginCell)().store((0,a.storeMessageRelaxed)(e.message)).endCell();return(0,a.beginCell)().storeUint(od.actions.send_message,ad.bitsize.op).storeUint(e.sendMode,8).storeRef(t).endCell()}static packUpdateRequest(e){return(0,a.beginCell)().storeUint(od.actions.update_multisig_params,ad.bitsize.op).storeUint(e.threshold,ad.bitsize.signerIndex).storeRef((0,a.beginCell)().storeDictDirect(ld(e.signers))).storeDict(ld(e.proposers)).endCell()}static packOrder(e){let t=a.Dictionary.empty(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell());if(e.length>255)throw new Error("For action chains above 255, use packLarge method");for(let r=0;r{switch(e){case"unlock":return 0;case"out":return 1;case"in":return 2;case"full":return 3;default:throw new Error("Неправильное значение!")}},wd=e=>{switch(e){case"unlock":return"Разблокировать";case"out":return"Исходящие транзакции заблокированы";case"in":return"Входящие транзакции заблокированы";case"full":return"Исходящие и входящие транзакции заблокированы"}};function vd(e){if(e.remainingBits>0||e.remainingRefs>0)throw new Error("remaining bits in data")}class Cd{constructor(e,t){this.address=e,this.init=t}static createFromAddress(e){return new Cd(e)}static createFromConfig(e,t,r=0){const n=function(e){const t=e.jetton_content instanceof a.Cell?e.jetton_content:function(e){return(0,a.beginCell)().storeStringTail(e.uri).endCell()}(e.jetton_content);return(0,a.beginCell)().storeCoins(0).storeAddress(e.admin).storeAddress(null).storeRef(e.wallet_code).storeRef(t).endCell()}(e),i={code:t,data:n};return new Cd((0,a.contractAddress)(r,i),i)}async sendDeploy(e,t,r){await e.internal(t,{value:r,sendMode:a.SendMode.PAY_GAS_SEPARATELY,body:(0,a.beginCell)().storeUint(pd.top_up,32).storeUint(0,64).endCell()})}static mintMessage(e,t,r,n,i,o,s){const l=(0,a.beginCell)().storeUint(pd.internal_transfer,32).storeUint(0,64).storeCoins(t).storeAddress(r).storeAddress(n).storeCoins(o).storeMaybeRef(i).endCell();return(0,a.beginCell)().storeUint(pd.mint,32).storeUint(0,64).storeAddress(e).storeCoins(s).storeRef(l).endCell()}static parseMintInternalMessage(e){if(e.loadUint(32)!==pd.internal_transfer)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadCoins(),n=e.loadAddress(),i=e.loadAddress(),o=e.loadCoins(),s=e.loadBit()?e.loadRef().beginParse():e;return vd(e),{queryId:t,jettonAmount:r,fromAddress:n,responseAddress:i,forwardTonAmount:o,forwardPayload:s}}static parseMintMessage(e){if(e.loadUint(32)!==pd.mint)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadAddress(),n=e.loadCoins(),i=e.loadRef();return vd(e),{queryId:t,toAddress:r,tonAmount:n,internalMessage:this.parseMintInternalMessage(i.beginParse())}}static topUpMessage(){return(0,a.beginCell)().storeUint(pd.top_up,32).storeUint(0,64).endCell()}static parseTopUp(e){if(e.loadUint(32)!==pd.top_up)throw new Error("Invalid op");const t=e.loadUint(64);return vd(e),{queryId:t}}static changeAdminMessage(e){return(0,a.beginCell)().storeUint(pd.change_admin,32).storeUint(0,64).storeAddress(e).endCell()}static parseChangeAdmin(e){if(e.loadUint(32)!==pd.change_admin)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadAddress();return vd(e),{queryId:t,newAdminAddress:r}}static claimAdminMessage(e=0n){return(0,a.beginCell)().storeUint(pd.claim_admin,32).storeUint(e,64).endCell()}static parseClaimAdmin(e){if(e.loadUint(32)!==pd.claim_admin)throw new Error("Invalid op");const t=e.loadUint(64);return vd(e),{queryId:t}}static changeContentMessage(e){const t=e.uri;return(0,a.beginCell)().storeUint(pd.change_metadata_url,32).storeUint(0,64).storeStringTail(t).endCell()}static parseChangeContent(e){if(e.loadUint(32)!==pd.change_metadata_url)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadStringTail();return vd(e),{queryId:t,newMetadataUrl:r}}static lockWalletMessage(e,t,r,n=0){return(0,a.beginCell)().storeUint(pd.call_to,32).storeUint(n,64).storeAddress(e).storeCoins(r).storeRef((0,a.beginCell)().storeUint(pd.set_status,32).storeUint(n,64).storeUint(t,4).endCell()).endCell()}static parseSetStatus(e){if(e.loadUint(32)!==pd.set_status)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadUint(4);return vd(e),{queryId:t,newStatus:r}}static parseCallTo(e,t){if(e.loadUint(32)!==pd.call_to)throw new Error("Invalid op");const r=e.loadUint(64),n=e.loadAddress(),i=e.loadCoins(),o=e.loadRef();return vd(e),{queryId:r,toAddress:n,tonAmount:i,action:t(o.beginParse())}}static forceTransferMessage(e,t,r,n,i,o,s,l,c=0n){const d=md.transferMessage(e,t,n,i,o,s);return(0,a.beginCell)().storeUint(pd.call_to,32).storeUint(c,64).storeAddress(r).storeCoins(l).storeRef(d).endCell()}static parseTransfer(e){if(e.loadUint(32)!==pd.transfer)throw new Error("Invalid op");return{queryId:e.loadUint(64),jettonAmount:e.loadCoins(),toAddress:e.loadAddress(),responseAddress:e.loadAddress(),customPayload:e.loadMaybeRef(),forwardTonAmount:e.loadCoins(),forwardPayload:e.loadBit()?e.loadRef().beginParse():e}}static forceBurnMessage(e,t,r,n,i=0){return(0,a.beginCell)().storeUint(pd.call_to,32).storeUint(i,64).storeAddress(t).storeCoins(n).storeRef(md.burnMessage(e,r,null)).endCell()}static parseBurn(e){if(e.loadUint(32)!==pd.burn)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadCoins(),n=e.loadAddress(),i=e.loadMaybeRef();return vd(e),{queryId:t,jettonAmount:r,responseAddress:n,customPayload:i}}static upgradeMessage(e,t,r=0){return(0,a.beginCell)().storeUint(pd.upgrade,32).storeUint(r,64).storeRef(t).storeRef(e).endCell()}static parseUpgrade(e){if(e.loadUint(32)!==pd.upgrade)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadRef(),n=e.loadRef();return vd(e),{queryId:t,newData:r,newCode:n}}async getWalletAddress(e,t){const r=await e.get("get_wallet_address",[{type:"slice",cell:(0,a.beginCell)().storeAddress(t).endCell()}]);return nd(1===r.stack.remaining,"invalid get_wallet_address result"),r.stack.readAddress()}async getJettonData(e){let t=await e.get("get_jetton_data",[]);return nd(5===t.stack.remaining,"invalid get_jetton_data result"),{totalSupply:t.stack.readBigNumber(),mintable:t.stack.readBoolean(),adminAddress:t.stack.readAddress(),content:t.stack.readCell(),walletCode:t.stack.readCell()}}async getNextAdminAddress(e){const t=await e.get("get_next_admin_address",[]);return nd(1===t.stack.remaining,"invalid get_next_admin_address result"),t.stack.readAddressOpt()}}const _d=e=>{if(null===e)throw new Error("Invalid number");if(void 0===e)throw new Error("Invalid number");if(isNaN(e))throw new Error("Invalid number");if(e<0)throw new Error("Invalid number")},kd=async(e,t,r,n,i)=>{const o=await qc("account",{address:ed(e)},n);nd("active"===o.status,"Контракт не активен. Если вы только что создали заявку, она должна появиться в течение ~30 секунд."),nd(a.Cell.fromBase64(o.code).equals(t),"Код контракта НЕ совпадает с кодом мультикошелька заявки из этого хранилища");const s=o.balance,l=function(e){const t=e.beginParse(),r=t.loadAddress(),n=t.loadUintBig(256);if(0===t.remainingBits)throw new Error("Order not initialized");const i=t.loadUint(8),o=t.loadBoolean(),s=hd(t.loadRef()),a=t.loadUint(256),l=t.loadUint(8),c=t.loadUint(48),d=t.loadRef();return dd(t),{multisigAddress:r,orderSeqno:n,threshold:i,isExecuted:o,signers:s,approvalsMask:a,approvalsNum:l,expirationDate:c,order:d}}(a.Cell.fromBase64(o.data));_d(l.threshold),nd(l.threshold>0,"Порог голосующих не является положительным"),nd(l.threshold<=l.signers.length,"Недопустимый порог"),_d(l.approvalsMask),_d(l.approvalsNum),nd(l.approvalsNum<=l.signers.length,"Неправильное количество"),_d(l.expirationDate);const c=[];for(const e of l.signers)c.push(await Qc(e,n));nd(l.multisigAddress.equals(r.address.address),"Адрес мультикошелька не найден");const d=fd.createFromConfig({multisig:r.address.address,orderSeqno:l.orderSeqno},t);if(nd(d.address.equals(e.address),"Неправильный адрес заявки"),l.isExecuted||(nd(r.threshold<=l.threshold,"Количество подтверждающих не соответствует порогу заявки"),nd(rd(r.signers.map((e=>e.address)),l.signers),"Количество подтверждающих не совпадает с количествои в заявке")),i){const t=new Wc(e.address,n),r=fd.createFromAddress(e.address),i=await r.getOrderDataStrict(t);nd(i.multisig.equals(l.multisigAddress),"Invalid multisigAddress"),nd(i.order_seqno===l.orderSeqno,"Invalid orderSeqno"),nd(i.threshold===l.threshold,"Invalid threshold"),nd(i.executed===l.isExecuted,"Invalid isExecuted"),nd(rd(i.signers,l.signers),"Invalid signers"),nd(i._approvals===BigInt(l.approvalsMask),"Invalid approvalsMask"),nd(i.approvals_num===l.approvalsNum,"Invalid approvalsNum"),nd(i.expiration_date===BigInt(l.expirationDate),"Invalid expirationDate"),nd(i.order.hash().equals(l.order.hash()),"Invalid order")}const u=fd.createFromConfig({multisig:l.multisigAddress,orderSeqno:l.orderSeqno},t).address.equals(e.address),h=a.Dictionary.loadDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell(),l.order),f=async e=>{try{const t=e.beginParse();if(0===t.remainingBits&&0==t.remainingRefs)return"Отправьте TON с помощью мультикошелька без комментариев"}catch(e){}try{const t=e.beginParse();if(0==t.loadUint(32)){const e=t.loadStringTail();return`Отправьте TON с помощью мультикошелька с комментарием "${id(e)}"`}}catch(e){}try{const t=e.beginParse(),r=Cd.parseMintMessage(t);nd(0===r.internalMessage.forwardPayload.remainingBits&&0===r.internalMessage.forwardPayload.remainingRefs,"Полезная нагрузка выпуска не поддерживается");const i=await Jc(r.toAddress,n);return`Выпустить ${r.internalMessage.jettonAmount} жетонов (в единицах измерения) на адрес ${i}; ${(0,a.fromNano)(r.tonAmount)} TON для оплаты газа`}catch(e){}try{const t=e.beginParse();return Cd.parseTopUp(t),"Пополнить"}catch(e){}try{const t=e.beginParse(),r=Cd.parseChangeAdmin(t);return`Смена адреса администратора на ${await Jc(r.newAdminAddress,n)}`}catch(e){}try{const t=e.beginParse();return Cd.parseClaimAdmin(t),"Запросить адрес администратора"}catch(e){}try{const t=e.beginParse(),r=Cd.parseChangeContent(t);return`Смена URL метаданных на "${id(r.newMetadataUrl)}"`}catch(e){}try{const t=e.beginParse(),r=Cd.parseTransfer(t);if(r.customPayload)throw new Error("Отправка состояния не поддерживается");nd(0===r.forwardPayload.remainingBits&&0===r.forwardPayload.remainingRefs,"Отправка не поддерживается");const i=await Jc(r.toAddress,n);return`Отправка ${r.jettonAmount} жетонов с адреса мультикошелька на адрес польщователя ${i};`}catch(e){}try{const t=e.beginParse(),r=Cd.parseCallTo(t,Cd.parseSetStatus),i=await Jc(r.toAddress,n),o=(e=>{switch(e){case 0:return"unlock";case 1:return"out";case 2:return"in";case 3:return"full";default:throw new Error("Неправильное значение!")}})(r.action.newStatus);return`Блокировка жетонов пользователя ${i}. Смена состояния "${o}" - "${wd(o)}"; ${(0,a.fromNano)(r.tonAmount)} TON для оплаты газа`}catch(e){}try{const t=e.beginParse(),r=Cd.parseCallTo(t,Cd.parseTransfer);if(r.action.customPayload)throw new Error("Принудительная отправка не поддерживается");nd(0===r.action.forwardPayload.remainingBits&&0===r.action.forwardPayload.remainingRefs,"Принудительная отправка не поддерживается");const i=await Jc(r.toAddress,n),o=await Jc(r.action.toAddress,n);return`Принудительная отправка ${r.action.jettonAmount} с адреса польщователя ${i} на адрес ${o}; ${(0,a.fromNano)(r.tonAmount)} TON for gas`}catch(e){}try{const t=e.beginParse(),r=Cd.parseCallTo(t,Cd.parseBurn);if(r.action.customPayload)throw new Error("Сжигание не поддерживается");const i=await Jc(r.toAddress,n);return`Принудительное сжигание ${r.action.jettonAmount} жетонов с адреса пользователя ${i}; ${(0,a.fromNano)(r.tonAmount)} TON for gas`}catch(e){}throw new Error("Неподдерживаемое действие")};let p=[];const g=h.keys();for(let e of g){let t=`
Действие №${e}:
`;const r=h.get(e).beginParse(),i=r.loadUint(32);if(4046986843===i){const e=r.loadUint(8);let i=[],o=!1;1&e&&i.push("Pays fees separately"),2&e&&i.push("Ignore sending errors"),128&e&&(o=!0,i.push("CARRY ALL BALANCE")),64&e&&i.push("Carry all the remaining value of the inbound message"),32&e&&i.push("DESTROY ACCOUNT");const s=r.loadRef();dd(r);const l=(0,a.loadMessageRelaxed)(s.beginParse());console.log(l);const c=l.info,d=await Jc(c.dest,n);t+=`
Send ${o?"ALL BALANCE":(0,a.fromNano)(c.value.coins)} TON to ${d}
`,t+=`
${await f(l.body)}
`,e&&(t+=`
Send mode: ${i.join(", ")}.
`)}else{if(487390163!==i)throw new Error("Неправильное действие");{const e=r.loadUint(8),i=cd(r.loadRef()),o=r.loadUint(1)?cd(r.loadRef()):[];dd(r),nd(i.length>0,"Invalid new signers"),nd(e>0,"Invalid new threshold"),nd(e<=i.length,"Invalid new threshold"),t+="
Обновить параметры мультикошелька
",t+=`
Новый порог подписей : ${e.toString()}
`,t+="
Новые подтверждающие:
";for(let e=0;e#${e+1} - ${await Jc(r,n)}`}if(t+="
Новые предлагающие:
",o.length>0)for(let e=0;e#${e+1} - ${await Jc(r,n)}`}else t+="
Нет предлагающих
"}}p.push(t)}return{address:e,tonBalance:s,orderId:l.orderSeqno,isExecuted:l.isExecuted,approvalsNum:l.approvalsNum,approvalsMask:l.approvalsMask,threshold:l.threshold,signers:c,expiresAt:new Date(1e3*l.expirationDate),actions:p,stateInitMatches:u}};var xd=r(8287).hp;const Ad=e=>{const t=e.beginParse(),r=t.loadAddress(),n=t.loadUintBig(256);return dd(t),{multisigAddress:r,orderId:n}},Sd=e=>{const t=a.Address.parse(e.destination),r=(e=>{const t=e.beginParse();if(0!==t.loadUint(2))throw new Error("invalid init state prefix");const r=t.loadMaybeRef(),n=t.loadMaybeRef();if(t.loadBoolean())throw new Error("invalid init state empty libraries");return dd(t),{code:r,body:Ad(n)}})(a.Cell.fromBase64(e.init_state.body)),n=a.Cell.fromBase64(e.message_content.body).beginParse();nd(n.loadUint(32)===od.order.init,"invalid op");const i=n.loadUint(64),o=n.loadUint(8),s=n.loadRef().beginParse().loadDictDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Address()),l=n.loadUint(48),c=n.loadRef().beginParse().loadDictDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell()),d=n.loadUint(1);let u;return d&&(u=n.loadUint(8)),console.log("OUT",{queryId:i,threshold:o,signers:s,expiredAt:l,order:c,isSigner:d,signerIndex:u}),dd(n),{orderAddress:t,orderId:r.body.orderId}};var Bd=r(5269);const Ed=["uri","name","description","image","image_data","symbol","decimals","amount_style"],Id={serialize:(e,t)=>{t.storeRef((0,a.beginCell)().storeUint(0,8).storeStringTail(e).endCell())},parse:e=>{const t=e.loadRef().beginParse(),r=t.loadUint(8);if(0==r)return t.loadStringTail();if(1==r)return a.Dictionary.loadDirect(a.Dictionary.Keys.Uint(32),a.Dictionary.Values.Cell(),t).values().map((e=>e.beginParse().loadStringTail())).join("");throw Error(`Prefix ${r} is not supported yet`)}},Pd=async(e,t,r)=>{const n=await qc("account",{address:ed(e)},t);nd("active"===n.status,"Contract not active");const i=n.balance,o=new Wc(e.address,t),s=Cd.createFromAddress(e.address),l=await s.getJettonData(o);let c,d;const u=await(async e=>{const t=e.beginParse(),r=t.loadUint(8);if(1==r){const e=0==t.remainingBits;if(e&&0==t.remainingRefs)throw new Error("No data in content cell!");return e?t.loadStringRefTail():t.loadStringTail()}if(0==r){const e=a.Dictionary.load(a.Dictionary.Keys.BigUint(256),Id,t),r={};for(const t of Ed){const n=BigInt("0x"+(await(0,Bd.sha256)(t)).toString("hex")),i=e.get(n);void 0!==i&&(r[t]=i)}return r}throw new Error(`Unknown content format indicator:${r}`)})(l.content);if(u instanceof String)d=u;else{const e=u;d=e.uri;const t=e.decimals;if(void 0!==t&&(c=parseInt(t),isNaN(c)))throw new Error("invalid decimals")}let h;return r&&(h=await s.getNextAdminAddress(o)),{tonBalance:i,jettonMinterContract:s,adminAddress:l.adminAddress,nextAdminAddress:h,decimals:c,metadataUrl:d}};var Md=r(9107),Ud=r.n(Md),Td=r(8287).hp;function Od(e){let t=0;const r=Td.alloc(e.length+2);r.set(e);for(let e of r){let r=128;for(;r>0;)t<<=1,e&r&&(t+=1),r>>=1,t>65535&&(t&=65535,t^=4129)}return Td.from([Math.floor(t/256),t%256])}var Rd,jd,Ld=r(8287).hp;function zd(e){if("string"==typeof e&&!Nd.isFriendly(e))throw new Error("Unknown address type");const t=Ld.isBuffer(e)?e:Ld.from(e,"base64");if(36!==t.length)throw new Error("Unknown address type: byte length is not equal to 36");const r=t.subarray(0,34),n=t.subarray(34,36),i=Od(r);if(i[0]!==n[0]||i[1]!==n[1])throw new Error("Invalid checksum: "+e);let o=r[0],s=!1,a=!1;if(128&o&&(s=!0,o^=128),17!==o&&81!==o)throw"Unknown address tag";a=17===o;let l=null;return l=255===r[1]?-1:r[1],{isTestOnly:s,isBounceable:a,workchain:l,hashPart:r.subarray(2,34)}}class Nd{static isAddress(e){return e instanceof Nd}static isFriendly(e){return 48===e.length&&!!/[A-Za-z0-9+/_-]+/.test(e)}static isRaw(e){if(-1===e.indexOf(":"))return!1;let[t,r]=e.split(":");return!!Number.isInteger(parseFloat(t))&&!!/[a-f0-9]+/.test(r.toLowerCase())&&64===r.length}static normalize(e){return"string"==typeof e?Nd.parse(e).toString():e.toString()}static parse(e){if(Nd.isFriendly(e))return this.parseFriendly(e).address;if(Nd.isRaw(e))return this.parseRaw(e);throw new Error("Unknown address type: "+e)}static parseRaw(e){let t=parseInt(e.split(":")[0]),r=Ld.from(e.split(":")[1],"hex");return new Nd(t,r)}static parseFriendly(e){if(Ld.isBuffer(e)){let t=zd(e);return{isBounceable:t.isBounceable,isTestOnly:t.isTestOnly,address:new Nd(t.workchain,t.hashPart)}}{let t=zd(e.replace(/\-/g,"+").replace(/_/g,"/"));return{isBounceable:t.isBounceable,isTestOnly:t.isTestOnly,address:new Nd(t.workchain,t.hashPart)}}}constructor(e,t){if(this.toRawString=()=>this.workChain+":"+this.hash.toString("hex"),this.toRaw=()=>{const e=Ld.alloc(36);return e.set(this.hash),e.set([this.workChain,this.workChain,this.workChain,this.workChain],32),e},this.toStringBuffer=e=>{let t=!(!e||void 0===e.testOnly)&&e.testOnly,r=!e||void 0===e.bounceable||e.bounceable?17:81;t&&(r|=128);const n=Ld.alloc(34);n[0]=r,n[1]=this.workChain,n.set(this.hash,2);const i=Ld.alloc(36);return i.set(n),i.set(Od(n),34),i},this.toString=e=>{let t=!e||void 0===e.urlSafe||e.urlSafe,r=this.toStringBuffer(e);return t?r.toString("base64").replace(/\+/g,"-").replace(/\//g,"_"):r.toString("base64")},this[Rd]=()=>this.toString(),32!==t.length)throw new Error("Invalid address hash length: "+t.length);this.workChain=e,this.hash=t,Object.freeze(this)}equals(e){return e.workChain===this.workChain&&e.hash.equals(this.hash)}}Rd=Ud();class Dd{static isAddress(e){return e instanceof Dd}constructor(e,t){this[jd]=()=>this.toString(),this.value=e,this.bits=t}toString(){return`External<${this.bits}:${this.value}>`}}function $d(e){let t=new Zd(8*Math.ceil(e.length/8));t.writeBits(e);let r=8*Math.ceil(e.length/8)-e.length;for(let e=0;ethis.toString(),r<0)throw new Error(`Length ${r} is out of bounds`);this._length=r,this._data=e,this._offset=t}get length(){return this._length}at(e){if(e>=this._length)throw new Error(`Index ${e} > ${this._length} is out of bounds`);if(e<0)throw new Error(`Index ${e} < 0 is out of bounds`);let t=this._offset+e>>3,r=7-(this._offset+e)%8;return!!(this._data[t]&1<this._length)throw new Error(`Offset(${e}) > ${this._length} is out of bounds`);if(e<0)throw new Error(`Offset(${e}) < 0 is out of bounds`);if(0===t)return Hd.EMPTY;if(e+t>this._length)throw new Error(`Offset ${e} + Length ${t} > ${this._length} is out of bounds`);return new Hd(this._data,this._offset+e,t)}subbuffer(e,t){if(e>this._length)throw new Error(`Offset ${e} is out of bounds`);if(e<0)throw new Error(`Offset ${e} is out of bounds`);if(e+t>this._length)throw new Error(`Offset + Lenght = ${e+t} is out of bounds`);if(t%8!=0)return null;if((this._offset+e)%8!=0)return null;let r=this._offset+e>>3,n=r+(t>>3);return this._data.subarray(r,n)}equals(e){if(this._length!==e._length)return!1;for(let t=0;t8*this._buffer.length)throw new Error("BitBuilder overflow");("boolean"==typeof e&&!0===e||"number"==typeof e&&e>0)&&(this._buffer[t/8|0]|=1<<7-t%8),this._length++}writeBits(e){for(let t=0;t8*this._buffer.length)throw new Error("BitBuilder overflow");e.copy(this._buffer,this._length/8),this._length+=8*e.length}else for(let t=0;t=n)throw Error(`bitLength is too small for a value ${e}. Got ${t}`);if(this._length+t>8*this._buffer.length)throw new Error("BitBuilder overflow");const i=8-this._length%8;if(i>0){const e=Math.floor(this._length/8);if(t>BigInt(t-i));this._buffer[e]|=n,this._length+=i}}for(t-=i;t>0;)t>=8?(this._buffer[this._length/8]=Number(r>>BigInt(t-8)&0xffn),this._length+=8,t-=8):(this._buffer[this._length/8]=Number(r<=n)throw Error(`value is out of range for ${t} bits. Got ${e}`);r<0?(this.writeBit(!0),r=n+r):this.writeBit(!1),this.writeUint(r,t-1)}writeVarUint(e,t){let r=BigInt(e);if(t<0||!Number.isSafeInteger(t))throw Error(`invalid bit length. Got ${t}`);if(r<0)throw Error(`value is negative. Got ${e}`);if(0n===r)return void this.writeUint(0,t);const n=Math.ceil(r.toString(2).length/8),i=8*n;this.writeUint(n,t),this.writeUint(r,i)}writeVarInt(e,t){let r=BigInt(e);if(t<0||!Number.isSafeInteger(t))throw Error(`invalid bit length. Got ${t}`);if(0n===r)return void this.writeUint(0,t);let n=r>0?r:-r;const i=1+Math.ceil(n.toString(2).length/8),o=8*i;this.writeUint(i,t),this.writeInt(r,o)}writeCoins(e){this.writeVarUint(e,4)}writeAddress(e){if(null!=e){if(Nd.isAddress(e))return this.writeUint(2,2),this.writeUint(0,1),this.writeInt(e.workChain,8),void this.writeBuffer(e.hash);if(Dd.isAddress(e))return this.writeUint(1,2),this.writeUint(e.bits,9),void this.writeUint(e.value,e.bits);throw Error(`Invalid address. Got ${e}`)}this.writeUint(0,2)}build(){return new Hd(this._buffer,0,this._length)}buffer(){if(this._length%8!=0)throw new Error("BitBuilder buffer is not byte aligned");return this._buffer.subarray(0,this._length/8)}}!function(e){e[e.Ordinary=-1]="Ordinary",e[e.PrunedBranch=1]="PrunedBranch",e[e.Library=2]="Library",e[e.MerkleProof=3]="MerkleProof",e[e.MerkleUpdate=4]="MerkleUpdate"}(Vd||(Vd={}));var Wd,Gd=r(8287).hp;function Yd(e){if(e.remainingBits%8!=0)throw new Error(`Invalid string length: ${e.remainingBits}`);if(0!==e.remainingRefs&&1!==e.remainingRefs)throw new Error(`invalid number of refs: ${e.remainingRefs}`);let t;return t=0===e.remainingBits?Gd.alloc(0):e.loadBuffer(e.remainingBits/8),1===e.remainingRefs&&(t=Gd.concat([t,Yd(e.loadRef().beginParse())])),t}function Qd(e){return Yd(e).toString()}function Jd(e,t){if(e.length>0){let r=Math.floor(t.availableBits/8);if(e.length>r){let n=e.subarray(0,r),i=e.subarray(r);t=t.storeBuffer(n);let o=xu();Jd(i,o),t=t.storeRef(o.endCell())}else t=t.storeBuffer(e)}}function Xd(e,t){Jd(Gd.from(e),t)}class eu{constructor(e,t){this[Wd]=()=>this.toString(),this._reader=e.clone(),this._refs=[...t],this._refsOffset=0}get remainingBits(){return this._reader.remaining}get offsetBits(){return this._reader.offset}get remainingRefs(){return this._refs.length-this._refsOffset}get offsetRefs(){return this._refsOffset}skip(e){return this._reader.skip(e),this}loadBit(){return this._reader.loadBit()}preloadBit(){return this._reader.preloadBit()}loadBoolean(){return this.loadBit()}loadMaybeBoolean(){return this.loadBit()?this.loadBoolean():null}loadBits(e){return this._reader.loadBits(e)}preloadBits(e){return this._reader.preloadBits(e)}loadUint(e){return this._reader.loadUint(e)}loadUintBig(e){return this._reader.loadUintBig(e)}preloadUint(e){return this._reader.preloadUint(e)}preloadUintBig(e){return this._reader.preloadUintBig(e)}loadMaybeUint(e){return this.loadBit()?this.loadUint(e):null}loadMaybeUintBig(e){return this.loadBit()?this.loadUintBig(e):null}loadInt(e){return this._reader.loadInt(e)}loadIntBig(e){return this._reader.loadIntBig(e)}preloadInt(e){return this._reader.preloadInt(e)}preloadIntBig(e){return this._reader.preloadIntBig(e)}loadMaybeInt(e){return this.loadBit()?this.loadInt(e):null}loadMaybeIntBig(e){return this.loadBit()?this.loadIntBig(e):null}loadVarUint(e){return this._reader.loadVarUint(e)}loadVarUintBig(e){return this._reader.loadVarUintBig(e)}preloadVarUint(e){return this._reader.preloadVarUint(e)}preloadVarUintBig(e){return this._reader.preloadVarUintBig(e)}loadVarInt(e){return this._reader.loadVarInt(e)}loadVarIntBig(e){return this._reader.loadVarIntBig(e)}preloadVarInt(e){return this._reader.preloadVarInt(e)}preloadVarIntBig(e){return this._reader.preloadVarIntBig(e)}loadCoins(){return this._reader.loadCoins()}preloadCoins(){return this._reader.preloadCoins()}loadMaybeCoins(){return this._reader.loadBit()?this._reader.loadCoins():null}loadAddress(){return this._reader.loadAddress()}loadMaybeAddress(){return this._reader.loadMaybeAddress()}loadExternalAddress(){return this._reader.loadExternalAddress()}loadMaybeExternalAddress(){return this._reader.loadMaybeExternalAddress()}loadAddressAny(){return this._reader.loadAddressAny()}loadRef(){if(this._refsOffset>=this._refs.length)throw new Error("No more references");return this._refs[this._refsOffset++]}preloadRef(){if(this._refsOffset>=this._refs.length)throw new Error("No more references");return this._refs[this._refsOffset]}loadMaybeRef(){return this.loadBit()?this.loadRef():null}preloadMaybeRef(){return this.preloadBit()?this.preloadRef():null}loadBuffer(e){return this._reader.loadBuffer(e)}preloadBuffer(e){return this._reader.preloadBuffer(e)}loadStringTail(){return Qd(this)}loadMaybeStringTail(){return this.loadBit()?Qd(this):null}loadStringRefTail(){return Qd(this.loadRef().beginParse())}loadMaybeStringRefTail(){const e=this.loadMaybeRef();return e?Qd(e.beginParse()):null}loadDict(e,t){return $u.load(e,t,this)}loadDictDirect(e,t){return $u.loadDirect(e,t,this)}endParse(){if(this.remainingBits>0||this.remainingRefs>0)throw new Error("Slice is not empty")}asCell(){return xu().storeSlice(this).endCell()}asBuilder(){return xu().storeSlice(this)}clone(e=!1){if(e){let e=this._reader.clone();return e.reset(),new eu(e,this._refs)}{let e=new eu(this._reader,this._refs);return e._refsOffset=this._refsOffset,e}}toString(){return this.asCell().toString()}}Wd=Ud();var tu=r(8287).hp;class ru{constructor(e,t=0){this._checkpoints=[],this._bits=e,this._offset=t}get offset(){return this._offset}get remaining(){return this._bits.length-this._offset}skip(e){if(e<0||this._offset+e>this._bits.length)throw new Error(`Index ${this._offset+e} is out of bounds`);this._offset+=e}reset(){this._checkpoints.length>0?this._offset=this._checkpoints.pop():this._offset=0}save(){this._checkpoints.push(this._offset)}loadBit(){let e=this._bits.at(this._offset);return this._offset++,e}preloadBit(){return this._bits.at(this._offset)}loadBits(e){let t=this._bits.substring(this._offset,e);return this._offset+=e,t}preloadBits(e){return this._bits.substring(this._offset,e)}loadBuffer(e){let t=this._preloadBuffer(e,this._offset);return this._offset+=8*e,t}preloadBuffer(e){return this._preloadBuffer(e,this._offset)}loadUint(e){return Number(this.loadUintBig(e))}loadUintBig(e){let t=this.preloadUintBig(e);return this._offset+=e,t}preloadUint(e){return Number(this._preloadUint(e,this._offset))}preloadUintBig(e){return this._preloadUint(e,this._offset)}loadInt(e){let t=this._preloadInt(e,this._offset);return this._offset+=e,Number(t)}loadIntBig(e){let t=this._preloadInt(e,this._offset);return this._offset+=e,t}preloadInt(e){return Number(this._preloadInt(e,this._offset))}preloadIntBig(e){return this._preloadInt(e,this._offset)}loadVarUint(e){let t=Number(this.loadUint(e));return Number(this.loadUintBig(8*t))}loadVarUintBig(e){let t=Number(this.loadUint(e));return this.loadUintBig(8*t)}preloadVarUint(e){let t=Number(this._preloadUint(e,this._offset));return Number(this._preloadUint(8*t,this._offset+e))}preloadVarUintBig(e){let t=Number(this._preloadUint(e,this._offset));return this._preloadUint(8*t,this._offset+e)}loadVarInt(e){let t=Number(this.loadUint(e));return Number(this.loadIntBig(8*t))}loadVarIntBig(e){let t=Number(this.loadUint(e));return this.loadIntBig(8*t)}preloadVarInt(e){let t=Number(this._preloadUint(e,this._offset));return Number(this._preloadInt(8*t,this._offset+e))}preloadVarIntBig(e){let t=Number(this._preloadUint(e,this._offset));return this._preloadInt(8*t,this._offset+e)}loadCoins(){return this.loadVarUintBig(4)}preloadCoins(){return this.preloadVarUintBig(4)}loadAddress(){let e=Number(this._preloadUint(2,this._offset));if(2===e)return this._loadInternalAddress();throw new Error("Invalid address: "+e)}loadMaybeAddress(){let e=Number(this._preloadUint(2,this._offset));if(0===e)return this._offset+=2,null;if(2===e)return this._loadInternalAddress();throw new Error("Invalid address")}loadExternalAddress(){if(1===Number(this._preloadUint(2,this._offset)))return this._loadExternalAddress();throw new Error("Invalid address")}loadMaybeExternalAddress(){let e=Number(this._preloadUint(2,this._offset));if(0===e)return this._offset+=2,null;if(1===e)return this._loadExternalAddress();throw new Error("Invalid address")}loadAddressAny(){let e=Number(this._preloadUint(2,this._offset));if(0===e)return this._offset+=2,null;if(2===e)return this._loadInternalAddress();if(1===e)return this._loadExternalAddress();throw 3===e?Error("Unsupported"):Error("Unreachable")}loadPaddedBits(e){if(e%8!=0)throw new Error("Invalid number of bits");let t=e;for(;;){if(this._bits.at(this._offset+t-1)){t--;break}t--}let r=this._bits.substring(this._offset,t);return this._offset+=e,r}clone(){return new ru(this._bits,this._offset)}_preloadInt(e,t){if(0==e)return 0n;let r=this._bits.at(t),n=0n;for(let r=0;r>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135)>>24}(this._mask),this._hashCount=this._hashIndex+1}get value(){return this._mask}get level(){return 32-Math.clz32(this._mask)}get hashIndex(){return this._hashIndex}get hashCount(){return this._hashCount}apply(e){return new su(this._mask&(1<>e-1)%2!=0}}function au(e,t){let r,n=new ru(e),i=n.loadUint(8);if(1!==i)throw new Error(`Pruned branch cell must have type 1, got "${i}"`);if(0!==t.length)throw new Error(`Pruned Branch cell can't has refs, got "${t.length}"`);if(280===e.length)r=new su(1);else{if(r=new su(n.loadUint(8)),r.level<1||r.level>3)throw new Error(`Pruned Branch cell level must be >= 1 and <= 3, got "${r.level}/${r.value}"`);const t=16+272*r.apply(r.level-1).hashCount;if(e.length!==t)throw new Error(`Pruned branch cell must have exactly ${t} bits, got "${e.length}"`)}let o=[],s=[],a=[];for(let e=0;e>1);else if(e===Vd.MerkleUpdate)ou(t,r),n=new su((r[0].mask.value|r[1].mask.value)>>1);else{if(e!==Vd.Library)throw new Error("Unsupported exotic type");nu(t),n=new su}let o=[],s=[],a=e===Vd.PrunedBranch?1:n.hashCount,l=n.hashCount-a;for(let i=0,a=0;i<=n.level;i++){if(!n.isSignificant(i))continue;if(a0&&d++;let u=uu(t,c,r,i,n.apply(i).value,e),h=(0,Bd.sha256_sync)(u),f=a-l;o[f]=d,s[f]=h,a++}let c=[],d=[];if(i)for(let e=0;e<4;e++){const{hashIndex:t}=n.apply(e),{hashIndex:r}=n;t!==r?(c.push(i.pruned[t].hash),d.push(i.pruned[t].depth)):(c.push(s[0]),d.push(o[0]))}else for(let e=0;e<4;e++)c.push(s[n.apply(e).hashIndex]),d.push(o[n.apply(e).hashIndex]);return{mask:n,hashes:c,depths:d}}function fu(e,t){let r=BigInt(e);if("int"===t)return 0n===r||-1n===r?1:(r>0?r:-r).toString(2).length+1;if("uint"===t){if(r<0)throw Error(`value is negative. Got ${e}`);return r.toString(2).length}throw Error(`invalid mode. Got ${t}`)}var pu=r(8287).hp;const gu=2197175160;function mu(e){let t=-1;for(let r=0;r>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1;t^=4294967295;let r=pu.alloc(4);return r.writeInt32LE(t),r}function yu(e){return function(e){let t=0;for(let r=0;r<3;r++)t+=1&e,e>>=1;return t+1}(7&e)}function bu(e,t){const r=e.loadUint(8),n=r%8,i=!!(8&r),o=e.loadUint(8),s=Math.ceil(o/2),a=!!(o%2),l=r>>5,c=!!(16&r),d=c?32*yu(l):0,u=c?2*yu(l):0;e.skip(8*d),e.skip(8*u);let h=Hd.EMPTY;s>0&&(h=a?e.loadPaddedBits(8*s):e.loadBits(8*s));let f=[];for(let r=0;r=0;e--){if(n[e].result)throw Error("Impossible");let t=[];for(let r of n[e].refs){if(!n[r].result)throw Error("Invalid BOC file");t.push(n[r].result)}n[e].result=new ku({bits:n[e].bits,refs:t,exotic:n[e].exotic})}let i=[];for(let e=0;e{if(this.isExotic&&!e)throw new Error("Exotic cells cannot be parsed");return new eu(new ru(this.bits),this.refs)},this.hash=(e=3)=>this._hashes[Math.min(this._hashes.length-1,e)],this.depth=(e=3)=>this._depths[Math.min(this._depths.length-1,e)],this.level=()=>this.mask.level,this.equals=e=>this.hash().equals(e.hash()),this[Cu]=()=>this.toString();let t=Hd.EMPTY;e&&e.bits&&(t=e.bits);let r,n,i,o=[];e&&e.refs&&(o=[...e.refs]);let s=Vd.Ordinary;if(e&&e.exotic){let e=function(e,t){let r=new ru(e).preloadUint(8);if(1===r)return function(e,t){let r=au(e,t),n=[],i=[],o=new su(r.mask);for(let e=0;e>1);return{type:Vd.MerkleProof,depths:[],hashes:[],mask:r}}(e,t);if(4===r)return function(e,t){ou(e,t);let r=new su((t[0].level()|t[1].level())>>1);return{type:Vd.MerkleUpdate,depths:[],hashes:[],mask:r}}(e,t);throw Error("Invalid exotic cell type: "+r)}(t,o),a=hu(e.type,t,o);i=a.mask,n=a.depths,r=a.hashes,s=e.type}else{if(o.length>4)throw new Error("Invalid number of references");if(t.length>1023)throw new Error(`Bits overflow: ${t.length} > 1023`);let e=hu(Vd.Ordinary,t,o);i=e.mask,n=e.depths,r=e.hashes,s=Vd.Ordinary}this.type=s,this.bits=t,this.refs=o,this.mask=i,this._depths=n,this._hashes=r,Object.freeze(this),Object.freeze(this.refs),Object.freeze(this.bits),Object.freeze(this.mask),Object.freeze(this._depths),Object.freeze(this._hashes)}get isExotic(){return this.type!==Vd.Ordinary}toBoc(e){return function(e,t){let r=function(e){let t=[e],r=new Map,n=new Set,i=[];for(;t.length>0;){const e=[...t];t=[];for(let i of e){const e=i.hash().toString("hex");if(!r.has(e)){n.add(e),r.set(e,{cell:i,refs:i.refs.map((e=>e.hash().toString("hex")))});for(let e of i.refs)t.push(e)}}}let o=new Set;function s(e){if(!n.has(e))return;if(o.has(e))throw Error("Not a DAG");o.add(e);let t=r.get(e).refs;for(let e=t.length-1;e>=0;e--)s(t[e]);i.push(e),o.delete(e),n.delete(e)}for(;n.size>0;)s(Array.from(n)[0]);let a=new Map;for(let e=0;e=0;e--){let t=i[e];const n=r.get(t);l.push({cell:n.cell,refs:n.refs.map((e=>a.get(e)))})}return l}(e),n=r.length,i=t.idx,o=t.crc32,s=Math.max(Math.ceil(fu(n,"uint")/8),1),a=0,l=[];for(let e of r)a+=wu(e.cell,s),l.push(a);let c=Math.max(Math.ceil(fu(a,"uint")/8),1),d=8*(6+3*s+c+1*s+(i?n*c:0)+a+(o?4:0)),u=new Zd(d);if(u.writeUint(3052313714,32),u.writeBit(i),u.writeBit(o),u.writeBit(!1),u.writeUint(0,2),u.writeUint(s,3),u.writeUint(c,8),u.writeUint(n,8*s),u.writeUint(1,8*s),u.writeUint(0,8*s),u.writeUint(a,8*c),u.writeUint(0,8*s),i)for(let e=0;e=4)throw new Error("Too many references");if(e instanceof ku)this._refs.push(e);else{if(!(e instanceof Au))throw new Error("Invalid argument");this._refs.push(e.endCell())}return this}storeMaybeRef(e){return e?(this.storeBit(1),this.storeRef(e)):this.storeBit(0),this}storeSlice(e){let t=e.clone();for(t.remainingBits>0&&this.storeBits(t.loadBits(t.remainingBits));t.remainingRefs>0;)this.storeRef(t.loadRef());return this}storeMaybeSlice(e){return e?(this.storeBit(1),this.storeSlice(e)):this.storeBit(0),this}storeBuilder(e){return this.storeSlice(e.endCell().beginParse())}storeMaybeBuilder(e){return e?(this.storeBit(1),this.storeBuilder(e)):this.storeBit(0),this}storeWritable(e){return"object"==typeof e?e.writeTo(this):e(this),this}storeMaybeWritable(e){return e?(this.storeBit(1),this.storeWritable(e)):this.storeBit(0),this}store(e){return this.storeWritable(e),this}storeStringTail(e){return Xd(e,this),this}storeMaybeStringTail(e){return null!=e?(this.storeBit(1),Xd(e,this)):this.storeBit(0),this}storeStringRefTail(e){return this.storeRef(xu().storeStringTail(e)),this}storeMaybeStringRefTail(e){return null!=e?(this.storeBit(1),this.storeStringRefTail(e)):this.storeBit(0),this}storeDict(e,t,r){return e?e.store(this,t,r):this.storeBit(0),this}storeDictDirect(e,t,r){return e.storeDirect(this,t,r),this}endCell(e){return new ku({bits:this._bits.build(),refs:this._refs,exotic:e?.exotic})}asCell(){return this.endCell()}asSlice(){return this.endCell().beginParse()}}function Su(e){return xu().storeUint(1,8).storeUint(1,8).storeBuffer(e.hash(0)).storeUint(e.depth(0),16).endCell({exotic:!0})}function Bu(e,t,r,n){const i=t.asCell();let o=0,s=e;if(0==(t.loadBit()?1:0)){o=function(e){let t=0;for(;e.loadBit();)t++;return t}(t);for(let e=0;e0&&t.storeUint(BigInt("0b"+e),e.length)}(e,r):"long"===n?function(e,t,r){r.storeBit(1),r.storeBit(0);let n=Math.ceil(Math.log2(t+1));r.storeUint(e.length,n),e.length>0&&r.storeUint(BigInt("0b"+e),e.length)}(e,t,r):"same"===n&&function(e,t,r,n){n.storeBit(1),n.storeBit(1),n.storeBit(e);let i=Math.ceil(Math.log2(r+1));n.storeUint(t,i)}("1"===e[0],e.length,t,r)}function Ru(e,t,r,n){Ou(e.label,t,n),function(e,t,r,n){if("leaf"===e.type&&r(e.value,n),"fork"===e.type){const i=xu(),o=xu();Ru(e.left,t-1,r,i),Ru(e.right,t-1,r,o),n.storeRef(i),n.storeRef(o)}}(e.node,t-e.label.length,r,n)}function ju(e,t,r,n){const i=function(e,t){let r=new Map;for(let n of Array.from(e.keys())){const i=Mu(n.toString(2),t);r.set(i,e.get(n))}return Tu(r)}(e,t);Ru(i,t,r,n)}var Lu=r(8287).hp;function zu(e){if("number"==typeof e){if(!Number.isSafeInteger(e))throw Error("Invalid key type: not a safe integer: "+e);return"n:"+e.toString(10)}if("bigint"==typeof e)return"b:"+e.toString(10);if(Nd.isAddress(e))return"a:"+e.toString();if(Lu.isBuffer(e))return"f:"+e.toString("hex");if(Hd.isBitString(e))return"B:"+e.toString();throw Error("Invalid key type")}function Nu(e){let t=e.slice(0,2),r=e.slice(2);if("n:"===t)return parseInt(r,10);if("b:"===t)return BigInt(r);if("a:"===t)return Nd.parse(r);if("f:"===t)return Lu.from(r,"hex");if("B:"===t){const e="_"==r.slice(-1);if(e||r.length%2!=0){let t=e?r.length-1:r.length;const n=r.substr(0,t)+"0";return!e&&1&t?new Hd(Lu.from(n,"hex"),0,t<<2):function(e){let t=0;for(let r=e.length-1;r>=0;r--)if(0!==e[r]){const n=e[r];let i=n&-n;1&i||(i=Math.log2(i)+1),r>0&&(t=r<<3),t+=8-i;break}return new Hd(e,0,t)}(Lu.from(n,"hex"))}return new Hd(Lu.from(r,"hex"),0,r.length<<2)}throw Error("Invalid key type: "+t)}var Du=r(8287).hp;class $u{static empty(e,t){return e&&t?new $u(new Map,e,t):new $u(new Map,null,null)}static load(e,t,r){let n;if(r instanceof ku){if(r.isExotic)return $u.empty(e,t);n=r.beginParse()}else n=r;let i=n.loadMaybeRef();return i&&!i.isExotic?$u.loadDirect(e,t,i.beginParse()):$u.empty(e,t)}static loadDirect(e,t,r){if(!r)return $u.empty(e,t);let n;n=r instanceof ku?r.beginParse():r;let i=Pu(n,e.bits,t.parse),o=new Map;for(let[t,r]of i)o.set(zu(e.parse(t)),r);return new $u(o,e,t)}constructor(e,t,r){this._key=t,this._value=r,this._map=e}get size(){return this._map.size}get(e){return this._map.get(zu(e))}has(e){return this._map.has(zu(e))}set(e,t){return this._map.set(zu(e),t),this}delete(e){const t=zu(e);return this._map.delete(t)}clear(){this._map.clear()}*[Symbol.iterator](){for(const[e,t]of this._map){const r=Nu(e);yield[r,t]}}keys(){return Array.from(this._map.keys()).map((e=>Nu(e)))}values(){return Array.from(this._map.values())}store(e,t,r){if(0===this._map.size)e.storeBit(0);else{let n=this._key;null!=t&&(n=t);let i=this._value;if(null!=r&&(i=r),!n)throw Error("Key serializer is not defined");if(!i)throw Error("Value serializer is not defined");let o=new Map;for(const[e,t]of this._map)o.set(n.serialize(Nu(e)),t);e.storeBit(1);let s=xu();ju(o,n.bits,i.serialize,s),e.storeRef(s.endCell())}}storeDirect(e,t,r){if(0===this._map.size)throw Error("Cannot store empty dictionary directly");let n=this._key;null!=t&&(n=t);let i=this._value;if(null!=r&&(i=r),!n)throw Error("Key serializer is not defined");if(!i)throw Error("Value serializer is not defined");let o=new Map;for(const[e,t]of this._map)o.set(n.serialize(Nu(e)),t);ju(o,n.bits,i.serialize,e)}generateMerkleProof(e){return Eu(this,e,this._key)}generateMerkleUpdate(e,t){return function(e,t,r,n){const i=Eu(e,t,r).refs[0];return e.set(t,n),o=i,s=Eu(e,t,r).refs[0],xu().storeUint(4,8).storeBuffer(o.hash(0)).storeBuffer(s.hash(0)).storeUint(o.depth(0),16).storeUint(s.depth(0),16).storeRef(o).storeRef(s).endCell({exotic:!0});var o,s}(this,e,this._key,t)}}$u.Keys={Address:()=>({bits:267,serialize:e=>{if(!Nd.isAddress(e))throw Error("Key is not an address");return xu().storeAddress(e).endCell().beginParse().preloadUintBig(267)},parse:e=>xu().storeUint(e,267).endCell().beginParse().loadAddress()}),BigInt:e=>function(e){return{bits:e,serialize:t=>{if("bigint"!=typeof t)throw Error("Key is not a bigint");return xu().storeInt(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadIntBig(e)}}(e),Int:e=>function(e){return{bits:e,serialize:t=>{if("number"!=typeof t)throw Error("Key is not a number");if(!Number.isSafeInteger(t))throw Error("Key is not a safe integer: "+t);return xu().storeInt(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadInt(e)}}(e),BigUint:e=>function(e){return{bits:e,serialize:t=>{if("bigint"!=typeof t)throw Error("Key is not a bigint");if(t<0)throw Error("Key is negative: "+t);return xu().storeUint(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadUintBig(e)}}(e),Uint:e=>function(e){return{bits:e,serialize:t=>{if("number"!=typeof t)throw Error("Key is not a number");if(!Number.isSafeInteger(t))throw Error("Key is not a safe integer: "+t);if(t<0)throw Error("Key is negative: "+t);return xu().storeUint(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>Number(xu().storeUint(t,e).endCell().beginParse().loadUint(e))}}(e),Buffer:e=>function(e){return{bits:8*e,serialize:t=>{if(!Du.isBuffer(t))throw Error("Key is not a buffer");return xu().storeBuffer(t).endCell().beginParse().loadUintBig(8*e)},parse:t=>xu().storeUint(t,8*e).endCell().beginParse().loadBuffer(e)}}(e),BitString:e=>function(e){return{bits:e,serialize:t=>{if(!Hd.isBitString(t))throw Error("Key is not a BitString");return xu().storeBits(t).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadBits(e)}}(e)},$u.Values={BigInt:e=>function(e){return{serialize:(t,r)=>{r.storeInt(t,e)},parse:t=>t.loadIntBig(e)}}(e),Int:e=>function(e){return{serialize:(t,r)=>{r.storeInt(t,e)},parse:t=>t.loadInt(e)}}(e),BigVarInt:e=>function(e){return{serialize:(t,r)=>{r.storeVarInt(t,e)},parse:t=>t.loadVarIntBig(e)}}(e),BigUint:e=>function(e){return{serialize:(t,r)=>{r.storeUint(t,e)},parse:t=>t.loadUintBig(e)}}(e),Uint:e=>function(e){return{serialize:(t,r)=>{r.storeUint(t,e)},parse:t=>t.loadUint(e)}}(e),BigVarUint:e=>function(e){return{serialize:(t,r)=>{r.storeVarUint(t,e)},parse:t=>t.loadVarUintBig(e)}}(e),Bool:()=>({serialize:(e,t)=>{t.storeBit(e)},parse:e=>e.loadBit()}),Address:()=>({serialize:(e,t)=>{t.storeAddress(e)},parse:e=>e.loadAddress()}),Cell:()=>({serialize:(e,t)=>{t.storeRef(e)},parse:e=>e.loadRef()}),Buffer:e=>{return t=e,{serialize:(e,r)=>{if(e.length!==t)throw Error("Invalid buffer size");r.storeBuffer(e)},parse:e=>e.loadBuffer(t)};var t},BitString:e=>function(e){return{serialize:(t,r)=>{if(t.length!==e)throw Error("Invalid BitString size");r.storeBits(t)},parse:t=>t.loadBits(e)}}(e),Dictionary:(e,t)=>function(e,t){return{serialize:(e,t)=>{e.store(t)},parse:r=>$u.load(e,t,r)}}(e,t)};const Fu=e=>document.querySelector(e),Ku=(e,t)=>{e.style.display=t?"flex":"none"},Hu='
Это вы
',Vu=(e,t)=>{let r=e;void 0!==t&&(r+="/"+t),window.history.state!==r&&window.history.pushState(r,"TON Multisig - "+r,"#"+r)},qu=(navigator.language,window.location.href.indexOf("testnet=true")>-1);qu&&(Fu(".testnet-badge").style.display="block",document.body.classList.add("testnet-padding"));const Zu=e=>e.toString({bounceable:!0,testOnly:qu});let Wu="startScreen";const Gu=e=>{const t=["startScreen","importScreen","multisigScreen","newOrderScreen","orderScreen","newMultisigScreen","loadingScreen"];Wu=e;for(const r of t)Ku(Fu("#"+r),r===e);switch(Wu){case"startScreen":nh(),dh(),""!==window.history.state&&window.history.pushState("","Мультикошелек","#");break;case"importScreen":Fu("#import_input").value="";break;case"newOrderScreen":Bh();break;case"newMultisigScreen":Nh()}};let Yu;const Qu=new class{constructor(e){if(Ie(this,"walletInfoStorage",new Fr),Ie(this,"preferredWalletStorage",new Kr),Ie(this,"walletInfo",null),Ie(this,"systemThemeChangeUnsubscribe",null),Ie(this,"actionsConfiguration"),Ie(this,"walletsList"),Ie(this,"connectRequestParametersCallback"),Ie(this,"connector"),Ie(this,"modal"),Ie(this,"transactionModal"),Ie(this,"connectionRestored",Promise.resolve(!1)),e&&"connector"in e&&e.connector)this.connector=e.connector;else{if(!(e&&"manifestUrl"in e&&e.manifestUrl))throw new Mr("You have to specify a `manifestUrl` or a `connector` in the options.");this.connector=new oe({manifestUrl:e.manifestUrl})}this.modal=new Fc({connector:this.connector,setConnectRequestParametersCallback:e=>{this.connectRequestParametersCallback=e}}),this.transactionModal=new Kc({connector:this.connector}),this.walletsList=this.getWallets(),this.walletsList.then((e=>{return jr((t=e.map((e=>e.imageUrl)),[...new Set(t)]));var t}));const t=this.normalizeWidgetRoot(null==e?void 0:e.widgetRootId);this.subscribeToWalletChange(),!1!==(null==e?void 0:e.restoreConnection)&&(this.connectionRestored=new Promise((e=>Pe(this,null,(function*(){yield this.connector.restoreConnection(),this.connector.connected||this.walletInfoStorage.removeWalletInfo(),e(this.connector.connected)}))))),this.uiOptions=_n(e,{uiPreferences:{theme:"SYSTEM"}});const r=this.preferredWalletStorage.getPreferredWalletAppName();Ya({connector:this.connector,preferredWalletAppName:r}),((e,t)=>{(function(e,t,r,n={}){let i;qe((n=>{i=n,t===document?e():qt(t,e(),t.firstChild?null:void 0,r)}),n.owner)})((()=>kt(Nc,{tonConnectUI:t})),document.getElementById(e))})(t,this)}static getWallets(){return oe.getWallets()}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?Be(Be({},this.connector.wallet),this.walletInfo):null}set uiOptions(e){var t,r,n,i,o,s,a;this.checkButtonRootExist(e.buttonRootId),this.actionsConfiguration=e.actionsConfiguration,(null==(t=e.uiPreferences)?void 0:t.theme)?"SYSTEM"!==(null==(r=e.uiPreferences)?void 0:r.theme)?(null==(n=this.systemThemeChangeUnsubscribe)||n.call(this),Bn(e.uiPreferences.theme,e.uiPreferences.colorsSet)):(Bn(window.matchMedia&&window.matchMedia("(prefers-color-scheme: light)").matches?ir.LIGHT:ir.DARK,e.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=function(e){const t=t=>e(t.matches?ir.DARK:ir.LIGHT);return window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t),()=>window.matchMedia("(prefers-color-scheme: dark)").removeEventListener("change",t)}(Bn))):(null==(i=e.uiPreferences)?void 0:i.colorsSet)&&(s=e.uiPreferences.colorsSet,Sn[ir.DARK]=_n(s[ir.DARK],Sn[ir.DARK]),Sn[ir.LIGHT]=_n(s[ir.LIGHT],Sn[ir.LIGHT]),xn((e=>({colors:_n(Sn[e.theme],An[e.theme])})))),(null==(o=e.uiPreferences)?void 0:o.borderRadius)&&(a=e.uiPreferences.borderRadius,xn({borderRadius:a})),Ya((t=>{var r,n;const i=_n(Be(Be(Be(Be({},e.language&&{language:e.language}),!!(null==(r=e.actionsConfiguration)?void 0:r.returnStrategy)&&{returnStrategy:e.actionsConfiguration.returnStrategy}),!!(null==(n=e.actionsConfiguration)?void 0:n.twaReturnUrl)&&{twaReturnUrl:e.actionsConfiguration.twaReturnUrl}),!!e.walletsListConfiguration&&{walletsListConfiguration:e.walletsListConfiguration}),cn(t));return void 0!==e.buttonRootId&&(i.buttonRootId=e.buttonRootId),void 0!==e.enableAndroidBackHandler&&(i.enableAndroidBackHandler=e.enableAndroidBackHandler),i}))}setConnectRequestParameters(e){var t;Ya({connectRequestParameters:e}),"ready"!==(null==e?void 0:e.state)&&e||null==(t=this.connectRequestParametersCallback)||t.call(this,null==e?void 0:e.value)}getWallets(){return Pe(this,null,(function*(){return this.connector.getWallets()}))}onStatusChange(e,t){return this.connector.onStatusChange((t=>Pe(this,null,(function*(){if(t){const r=yield this.getSelectedWalletInfo(t);e(Be(Be({},t),r||this.walletInfoStorage.getWalletInfo()))}else e(t)}))),t)}openModal(){return Pe(this,null,(function*(){return this.modal.open()}))}closeModal(){this.modal.close()}onModalStateChange(e){return this.modal.onStateChange(e)}get modalState(){return this.modal.state}connectWallet(){return Pe(this,null,(function*(){const e=(yield this.getWallets()).find(ee);return e?yield this.connectEmbeddedWallet(e):yield this.connectExternalWallet()}))}disconnect(){return setTimeout((()=>Xr(null))),Qr(null),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect()}sendTransaction(e,t){return Pe(this,null,(function*(){if(!this.connected)throw new Mr("Connect wallet to send a transaction.");On()&&Rn();const{notifications:r,modals:n,returnStrategy:i,twaReturnUrl:o,skipRedirectToWallet:s}=this.getModalsAndNotificationsConfiguration(t);$c({name:"confirm-transaction",showNotification:r.includes("before"),openModal:n.includes("before")});const a=()=>{const e="ios"===Nr().os,t="ios"===s&&e||"always"===s;this.walletInfo&&"universalLink"in this.walletInfo&&"universal-link"===this.walletInfo.openMethod&&!t&&(L(this.walletInfo.universalLink)?El(this.walletInfo.universalLink,{returnStrategy:i,twaReturnUrl:o||Ga.twaReturnUrl,forceRedirect:!1}):Tr(Bl(this.walletInfo.universalLink,i)))},l=new AbortController,c=this.onTransactionModalStateChange((e=>{(null==e?void 0:e.openModal)||(c(),e||l.abort())}));try{const t=yield this.waitForSendTransaction({transaction:e,abortSignal:l.signal},a);return $c({name:"transaction-sent",showNotification:r.includes("success"),openModal:n.includes("success")}),t}catch(e){throw $c({name:"transaction-canceled",showNotification:r.includes("error"),openModal:n.includes("error")}),e instanceof m?e:(console.error(e),new Mr("Unhandled error:"+e))}finally{c()}}))}connectEmbeddedWallet(e){return Pe(this,null,(function*(){const t=t=>{Qr(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},t)},r=Ga.connectRequestParameters;return"loading"===(null==r?void 0:r.state)?this.connectRequestParametersCallback=t:t(null==r?void 0:r.value),yield this.waitForWalletConnection({ignoreErrors:!1})}))}connectExternalWallet(){return Pe(this,null,(function*(){const e=new AbortController;Dc();const t=this.onModalStateChange((r=>{const{status:n,closeReason:i}=r;"opened"!==n&&(t(),"action-cancelled"===i&&e.abort())}));return yield this.waitForWalletConnection({ignoreErrors:!0,abortSignal:e.signal})}))}waitForWalletConnection(e){return Pe(this,null,(function*(){return new Promise(((t,r)=>{const{ignoreErrors:n=!1,abortSignal:i=null}=e;if(i&&i.aborted)return r(new Mr("Wallet was not connected"));const o=e=>Pe(this,null,(function*(){if(e)s(),t(e);else{if(n)return;s(),r(new Mr("Wallet was not connected"))}})),s=this.onStatusChange((e=>o(e)),(e=>(e=>{n||(s(),r(e))})(e)));i&&i.addEventListener("abort",(()=>{s(),r(new Mr("Wallet was not connected"))}))}))}))}waitForSendTransaction(e,t){return Pe(this,null,(function*(){return new Promise(((r,n)=>{const{transaction:i,abortSignal:o}=e;if(o.aborted)return n(new Mr("Transaction was not sent"));const s=e=>Pe(this,null,(function*(){r(e)}));this.connector.sendTransaction(i,t).then((e=>s(e))).catch((e=>(e=>{n(e)})(e))),o.addEventListener("abort",(()=>{n(new Mr("Transaction was not sent"))}))}))}))}onTransactionModalStateChange(e){return this.transactionModal.onStateChange(e)}subscribeToWalletChange(){this.connector.onStatusChange((e=>Pe(this,null,(function*(){var t;e?(yield this.updateWalletInfo(e),this.setPreferredWalletAppName((null==(t=this.walletInfo)?void 0:t.appName)||e.device.appName)):this.walletInfoStorage.removeWalletInfo()}))))}setPreferredWalletAppName(e){this.preferredWalletStorage.setPreferredWalletAppName(e),Ya({preferredWalletAppName:e})}getSelectedWalletInfo(e){return Pe(this,null,(function*(){let t,r=Gr();if(!r)return null;if("name"in r)t=r;else{const n=Ja(yield this.walletsList,Ga.walletsListConfiguration).find((t=>rl(t,e.device.appName)));if(!n)throw new Mr(`Cannot find WalletInfo for the '${e.device.appName}' wallet`);t=Be(Be({},n),r)}return t}))}updateWalletInfo(e){return Pe(this,null,(function*(){const t=yield this.getSelectedWalletInfo(e);if(t)return this.walletInfo=t,void this.walletInfoStorage.setWalletInfo(t);const r=this.walletInfoStorage.getWalletInfo();this.walletInfo=r||(yield this.walletsList).find((t=>rl(t,e.device.appName)))||null}))}normalizeWidgetRoot(e){if(!e||!document.getElementById(e)){e="tc-widget-root";const t=document.createElement("div");t.id=e,document.body.appendChild(t)}return e}checkButtonRootExist(e){if(null!=e&&!document.getElementById(e))throw new Mr(`${e} element not found in the document.`)}getModalsAndNotificationsConfiguration(e){var t,r,n,i,o,s;const a=["before","success","error"];let l=a;(null==(t=this.actionsConfiguration)?void 0:t.notifications)&&"all"!==(null==(r=this.actionsConfiguration)?void 0:r.notifications)&&(l=this.actionsConfiguration.notifications),(null==e?void 0:e.notifications)&&(l="all"===e.notifications?a:e.notifications);let c=["before"];(null==(n=this.actionsConfiguration)?void 0:n.modals)&&(c="all"===this.actionsConfiguration.modals?a:this.actionsConfiguration.modals),(null==e?void 0:e.modals)&&(c="all"===e.modals?a:e.modals);const d=(null==e?void 0:e.returnStrategy)||(null==(i=this.actionsConfiguration)?void 0:i.returnStrategy)||"back",u=(null==e?void 0:e.twaReturnUrl)||(null==(o=this.actionsConfiguration)?void 0:o.twaReturnUrl);let h=(null==e?void 0:e.skipRedirectToWallet)||(null==(s=this.actionsConfiguration)?void 0:s.skipRedirectToWallet)||"ios";return On()&&(h="never"),{notifications:l,modals:c,returnStrategy:d,twaReturnUrl:u,skipRedirectToWallet:h}}}({manifestUrl:"https://multisig.ton.org/tonconnect-manifest.json",buttonRootId:"tonConnectButton"});Qu.uiOptions={uiPreferences:{theme:ir.LIGHT}},Qu.onStatusChange((e=>{null===e?Yu=null:e.account&&(Yu=a.Address.parseRaw(e.account.address)),eh&&th&&ih(),ah&&lh&&hh()})),Fu("#createMultisigButton").addEventListener("click",(()=>{zh("create")})),Fu("#importMultisigButton").addEventListener("click",(()=>{Gu("importScreen")})),Fu("#import_okButton").addEventListener("click",(()=>{const e=Fu("#import_input").value,t=Gc(e,qu);t?alert(t):sh(e)})),Fu("#import_backButton").addEventListener("click",(()=>{Gu("startScreen")}));const Ju=a.Cell.fromBase64("te6cckECEgEABJUAART/APSkE/S88sgLAQIBYgIDAsrQM9DTAwFxsJJfA+D6QDAi10nAAJJfA+AC0x8BIMAAkl8E4AHTPwHtRNDT/wEB0wcBAdTTBwEB9ATSAAEB0SiCEPcYUQ+64w8FREPIUAYBy/9QBAHLBxLMAQHLB/QAAQHKAMntVAQFAgEgDA0BnjgG0/8BKLOOEiCE/7qSMCSWUwW68uPw4gWkBd4B0gABAdMHAQHTLwEB1NEjkSaRKuJSMHj0Dm+h8uPvHscF8uPvIPgjvvLgbyD4I6FUbXAGApo2OCaCEHUJf126jroGghCjLFm/uo6p+CgYxwXy4GUD1NEQNBA2RlD4AH+OjSF49HxvpSCRMuMNAbPmWxA1UDSSNDbiUFQT4w1AFVAzBAoJAdT4BwODDPlBMAODCPlBMPgHUAahgSf4AaBw+DaBEgZw+DaggSvscPg2oIEdmHD4NqAipgYioIEFOSagJ6Bw+DgjpIECmCegcPg4oAOmBliggQbgUAWgUAWgQwNw+DdZoAGgHL7y4GT4KFADBwK4AXACyFjPFgEBy//JiCLIywH0APQAywDJcCH5AHTIywISygfL/8nQyIIQnHP7olgKAssfyz8mAcsHUlDMUAsByy8bzCoBygAKlRkBywcIkTDiECRwQImAGIBQ2zwRCACSjkXIWAHLBVAFzxZQA/oCVHEjI+1E7UXtR59byFADzxfJE3dQA8trzMztZ+1l7WR0f+0RmHYBy2vMAc8X7UHt8QHy/8kB+wDbBgLiNgTT/wEB0y8BAdMHAQHT/wEB1NH4KFAFAXACyFjPFgEBy//JiCLIywH0APQAywDJcAH5AHTIywISygfL/8nQG8cF8uBlJvkAGrpRk74ZsPLgZgf4I77y4G9EFFBW+AB/jo0hePR8b6UgkTLjDQGz5lsRCgH6AtdM0NMfASCCEPE4Hlu6jmqCEB0M+9O6jl5sRNMHAQHUIX9wjhdREnj0fG+lMiGZUwK68uBnAqQC3gGzEuZsISDCAPLgbiPCAPLgbVMwu/LgbQH0BCF/cI4XURJ49HxvpTIhmVMCuvLgZwKkAt4BsxLmbCEw0VUjkTDi4w0LABAw0wfUAvsA0QFDv3T/aiaGn/gIDpg4CA6mmDgID6AmkAAIDoiBqvgoD8EdDA4CAWYPEADC+AcDgwz5QTADgwj5QTD4B1AGoYEn+AGgcPg2gRIGcPg2oIEr7HD4NqCBHZhw+DagIqYGIqCBBTkmoCegcPg4I6SBApgnoHD4OKADpgZYoIEG4FAFoFAFoEMDcPg3WaABoADxsMr7UTQ0/8BAdMHAQHU0wcBAfQE0gABAdEjf3COF1ESePR8b6UyIZlTArry4GcCpALeAbMS5mwhUjC68uBsIX9wjhdREnj0fG+lMiGZUwK68uBnAqQC3gGzEuZsITAiwgDy4G4kwgDy4G1SQ7vy4G0BkjN/kQPiA4AFZsMn+CgBAXACyFjPFgEBy//JiCLIywH0APQAywDJcAH5AHTIywISygfL/8nQgEQhCAmMFqAYchWwszwXcsN9YFccUdYcFZ8q18EnjQLz1klHzYNH/nQ=="),Xu=a.Cell.fromBase64("te6cckEBAQEAIwAIQgJjBagGHIVsLM8F3LDfWBXHFHWHBWfKtfBJ40C89ZJR80AoJo0=");let eh,th,rh=-1;const nh=()=>{eh=void 0,th=void 0,clearTimeout(rh)},ih=()=>{const{tonBalance:e,threshold:t,signers:r,proposers:n,allowArbitraryOrderSeqno:i,nextOderSeqno:o,lastOrders:s}=th;Fu("#multisig_tonBalance").innerText=(0,a.fromNano)(e)+" TON",Fu("#multisig_threshold").innerText=t+"/"+r.length,Fu("#multisig_orderId").innerText=i?"Произвольная":o.toString();let l="";for(let e=0;e#${e+1} — ${Xc(t)}${td(t.address,Yu)?Hu:""}`}if(Fu("#multisig_signersList").innerHTML=l,n.length>0){let e="";for(let t=0;t#${t+1} — ${Xc(r)}${td(r.address,Yu)?Hu:""}`}Fu("#multisig_proposersList").innerHTML=e}else Fu("#multisig_proposersList").innerHTML="No proposers";const c=e=>{if(e.errorMessage)return e.errorMessage.startsWith("Контракт не активен")?"":e.errorMessage.startsWith("Ошибка")?`
Ошибка в заявке #${e.order.id} — Execution error
`:`
Недействительная заявка #${e.order.id} — ${e.errorMessage}
`;{const t=!!e.orderInfo&&(new Date).getTime()>e.orderInfo.expiresAt.getTime(),r=t?"Истекший срок заявки ":(e=>{switch(e.type){case"new":return"Новая заяввка";case"execute":return"Execute order";case"pending":return"Ожидаемая заявка";case"executed":return"Выполненная заявка"}throw new Error("unknown order type "+e.type)})(e);let n=`${r} #${e.order.id}`;if("pending"!==e.type||t||(n+=` — ${e.orderInfo.approvalsNum}/${e.orderInfo.threshold}`),"pending"===e.type&&Yu){const t=e.orderInfo.signers.findIndex((e=>e.address.equals(Yu)));if(t>-1){const r=1<${n}`}};let d="",u=!1,h=!1;for(const e of s)"executed"==e.type?h||(d+='
Старые заявки:
',h=!0):"pending"===e.type&&(u||(d+='
Ожидаемые заявки:
',u=!0)),d+=c(e);Fu("#mainScreen_ordersList").innerHTML=d,(".multisig_lastOrder",document.querySelectorAll(".multisig_lastOrder")).forEach((e=>{e.addEventListener("click",(e=>{const t=e.currentTarget.attributes,r=t.getNamedItem("order-address").value,n=BigInt(t.getNamedItem("order-id").value);ph(n,r)}))}))},oh=async(e,t)=>{try{const r=await(async(e,t,r,n,i,o)=>{const s=await qc("account",{address:ed(e)},n);nd("active"===s.status,"Contract not active. If you have just created a multisig it should appear within ~30 seconds."),nd(a.Cell.fromBase64(s.code).equals(t),"The contract code DOES NOT match the multisig code from this repository");const l=s.balance,c=function(e){const t=e.beginParse(),r=t.loadUintBig(256),n=t.loadUint(8),i=cd(t.loadRef()),o=t.loadUint(8),s=cd(t.loadMaybeRef()),a=t.loadBit();return dd(t),{nextOderSeqno:r,threshold:n,signers:i,signersCount:o,proposers:s,allowArbitraryOrderSeqno:a}}(a.Cell.fromBase64(s.data));c.allowArbitraryOrderSeqno&&nd(c.nextOderSeqno===BigInt(0),"invalid nextOrderSeqno for allowArbitraryOrderSeqno");const d=c.signers,u=c.proposers;nd(d.length===c.signersCount,"invalid signersCount"),nd(c.threshold>0,"threshold <= 0"),nd(c.threshold<=c.signersCount,"invalid threshold");const h=[];for(const e of d)h.push(await Qc(e,n));const f=[];for(const e of u)f.push(await Qc(e,n));const p=ud.createFromAddress(e.address),g=new Wc(e.address,n);if(o){const e=await p.getMultisigData(g);c.allowArbitraryOrderSeqno?nd(e.nextOrderSeqno===BigInt(-1),"nextOderSeqno doesn't match"):nd(e.nextOrderSeqno===c.nextOderSeqno,"nextOderSeqno doesn't match"),nd(e.threshold===BigInt(c.threshold),"threshold doesn't match"),nd(rd(e.signers,c.signers),"invalid signers"),nd(rd(e.proposers,c.proposers),"invalid proposers")}const m=ud.createFromConfig({threshold:c.threshold,signers:c.signers,proposers:c.proposers,allowArbitrarySeqno:c.allowArbitraryOrderSeqno},t).address.equals(e.address),y={address:e,multisigContract:p,provider:g,signers:h,proposers:f,threshold:c.threshold,allowArbitraryOrderSeqno:c.allowArbitraryOrderSeqno,nextOderSeqno:c.nextOderSeqno,tonBalance:l,lastOrders:[],stateInitMatches:m};let b=[];if("none"!==i){const t=await qc("transactions",{account:ed(e),limit:256},n);for(const i of t.transactions){if(!i.in_msg.message_content)continue;if(!i.in_msg.message_content.body)continue;const t=a.Cell.fromBase64(i.in_msg.message_content.body).beginParse();if(t.remainingBits<32)continue;const o=t.loadUint(32);if(1963556701===o)try{t.loadUintBig(64);const o=t.loadUintBig(256),s=a.Address.parse(i.in_msg.source),l=fd.createFromConfig({multisig:e.address,orderSeqno:o},r);if(!s.equals(l.address))throw new Error("fake order");b.push({utime:i.now,transactionHash:i.hash,type:"execute",order:{address:{address:s,isBounceable:!0,isTestOnly:n},id:o}})}catch(e){b.push({utime:i.now,transactionHash:i.hash,type:"execute",errorMessage:e.message})}else if(4145565967===o)try{if(1!==i.out_msgs.length)throw new Error("invalid out messages");const o=i.out_msgs[0],{orderAddress:s,orderId:l}=Sd(o),c=fd.createFromConfig({multisig:e.address,orderSeqno:l},r);if(!s.equals(c.address))throw new Error("fake order");const d=t.loadUint(64),u=(t.loadUint(256),t.loadUint(1)),h=t.loadUint(8),f=t.loadUint(48),p=t.loadRef().beginParse().loadDictDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell());dd(t),console.log("IN",{queryId:d,orderId:l,orderAddress:s.toString(),isSigner:u,index:h,expiredAt:f,order:p}),b.push({utime:i.now,transactionHash:i.hash,type:"new",order:{address:{address:s,isBounceable:!0,isTestOnly:n},id:l}})}catch(e){console.log(e),b.push({utime:i.now,transactionHash:i.hash,type:"new",errorMessage:"Invalid new order: "+e.message})}}if("aggregate"===i){const e={};for(let t of b){if(t.errorMessage)continue;const r=t.order.id.toString();e[r]?"executed"!==e[r].type&&"execute"===t.type&&(e[r].utime=t.utime,e[r].type="executed"):e[r]={utime:t.utime,transactionHash:t.transactionHash,type:"new"===t.type?"pending":"executed",order:t.order}}b=Object.values(e);const t=e=>{if(e.transaction&&!1===e.transaction.success&&"excess"!==e.transaction.in_msg.decoded_op_name)return!0;if(e.children)for(let r of e.children)if(t(r))return!0;return!1};for(const e of b)if("executed"===e.type){const r=xd.from(e.transactionHash,"base64").toString("hex"),i=await Zc("traces/"+r,{},n);t(i)&&(e.errorMessage="Ошибка")}for(const e of b)if("pending"===e.type)try{const t=await kd(e.order.address,r,y,n,!1);e.orderInfo=t,(new Date).getTime()>t.expiresAt.getTime()&&(e.type="executed")}catch(t){e.type="executed",e.errorMessage=t.message}b=b.sort(((e,t)=>e.type===t.type?t.utime-e.utime:"pending"===e.type?-1:1))}}return y.lastOrders=b,y})(a.Address.parseFriendly(e),Ju,Xu,qu,"aggregate",t);if(eh!==e)return;th=r,ih(),Ku(Fu("#multisig_content"),!0),Ku(Fu("#multisig_error"),!1)}catch(r){if(console.error(r),eh!==e)return;!t&&r?.message?.startsWith("Timeout")||(Ku(Fu("#multisig_content"),!1),Ku(Fu("#multisig_error"),!0),Fu("#multisig_error").innerText=r.message)}clearTimeout(rh),rh=setTimeout((()=>oh(e,!1)),5e3),t&&Gu("multisigScreen")},sh=async(e,t)=>{Gu("loadingScreen"),nh(),eh=e,localStorage.setItem("multisigAddress",e),Vu(e,t);const r=a.Address.parseFriendly(eh);r.isBounceable=!0,r.isTestOnly=qu,Fu("#mulisig_address").innerHTML=Xc(r),await oh(e,!0)};let ah,lh;Fu("#multisig_logoutButton").addEventListener("click",(()=>{localStorage.removeItem("multisigAddress"),nh(),Gu("startScreen")})),Fu("#multisig_createNewOrderButton").addEventListener("click",(()=>{Gu("newOrderScreen")})),Fu("#multisig_updateButton").addEventListener("click",(()=>{zh("update")}));let ch=-1;const dh=()=>{ah=void 0,lh=void 0,clearTimeout(ch)},uh=(e,t)=>{Fu("#order_approveButton").innerText=t?e?"Executing..":"Execute":e?"Approving..":"Approve",Fu("#order_approveButton").disabled=e},hh=()=>{const{tonBalance:e,actions:t,isExecuted:r,approvalsNum:n,approvalsMask:i,threshold:o,signers:s,expiresAt:l}=lh,c=(new Date).getTime()>l.getTime();Fu("#order_tonBalance").innerText=(0,a.fromNano)(e)+" TON",Fu("#order_executed").innerText=r?"Да":"Нет",Fu("#order_approvals").innerText=n+"/"+o,Fu("#order_expiresAt").innerText=(c?"❌ ИСТЕКЛО - ":"")+l.toString();let d=!1,u="";for(let e=0;e#${e+1} — ${r} — ${n?"✅":"❌"}${td(t.address,Yu)?Hu:""}`}Fu("#order_signersList").innerHTML=u;let h="";for(const e of t)h+=e;0===t.length?Fu("#order_actionsTitle").innerText="Нет заявок":1===t.length?Fu("#order_actionsTitle").innerText="Заявка:":Fu("#order_actionsTitle").innerText=t.length+" действия:",Fu("#order_actions").innerHTML=h;let f=Number(localStorage.getItem(eh+"_"+ah+"_approve"));Date.now()-f>12e4&&!d&&(f=0,localStorage.removeItem(eh+"_"+ah+"_approve")),uh(!!f,n===o-1),Ku(Fu("#order_approveButton"),!r&&!c&&!d),Ku(Fu("#order_approveNote"),!r&&!c&&!d)},fh=async(e,t,r)=>{try{const n=await kd(e,Xu,th,qu,r);if(ah!==t)return;lh=n,hh(),Ku(Fu("#order_content"),!0),Ku(Fu("#order_error"),!1)}catch(e){if(console.error(e),ah!==t)return;!r&&e?.message?.startsWith("Время истекло")||(Ku(Fu("#order_content"),!1),Ku(Fu("#order_error"),!0),Fu("#order_error").innerText=e.message)}clearTimeout(ch),ch=setTimeout((()=>fh(e,t,!1)),5e3),r&&Gu("orderScreen")},ph=async(e,t)=>{if(!th)throw new Error("setOrderId: нет информации о мультикошельке");if(Gu("loadingScreen"),dh(),ah=e,Vu(eh,e),void 0===t){const r=fd.createFromConfig({multisig:a.Address.parseFriendly(eh).address,orderSeqno:e},Xu);t=Zu(r.address)}Fu("#order_id").innerText="#"+ah;const r=a.Address.parseFriendly(t);r.isBounceable=!0,r.isTestOnly=qu,Fu("#order_address").innerHTML=Xc(r),await fh(r,e,!0)};Fu("#order_backButton").addEventListener("click",(()=>{Vu(eh),dh(),Gu("multisigScreen")})),Fu("#order_approveButton").addEventListener("click",(async()=>{if(!eh)throw new Error("approve !currentMultisigAddress");if(!lh)throw new Error("approve !currentOrderInfo");const e=eh,t=lh;if(!Yu)return void alert("Please connect wallet");if(-1==t.signers.findIndex((e=>e.address.equals(Yu))))return void alert("Вы не можете подтверждать");const r=ed(t.address),n=yh.toString(),i=(0,a.beginCell)().storeUint(0,32).storeStringTail("approve").endCell().toBoc().toString("base64");console.log({orderAddressString:r,amount:n});const o={validUntil:Math.floor(Date.now()/1e3)+60,messages:[{address:r,amount:n,payload:i}]};uh(!0,t.approvalsNum===t.threshold-1),localStorage.setItem(e+"_"+t.orderId+"_approve",Date.now().toString());try{await Qu.sendTransaction(o)}catch(r){console.error(r),localStorage.removeItem(e+"_"+t.orderId+"_approve"),eh===e&&ah===t.orderId&&uh(!1,t.approvalsNum===t.threshold-1)}}));const gh=(e,t,r)=>{const n=t=>({error:e+": "+t}),i=e=>({value:e});if(null==t||""===t)return n("Empty");switch(r){case"TON":return((e,t)=>{try{const r=function(e,t){const r=function(e){let t=1n;for(let r=0;r2)throw Error("Invalid number");let o=i[0],s=i[1];if(o||(o="0"),s||(s="0"),s.length>t)throw Error("Invalid number");for(;s.length{try{const t=BigInt(e);return t<=0?n("Enter positive amount"):i(t)}catch(e){return n("Invalid amount")}})(t);case"Address":if(!a.Address.isFriendly(t))return n("Invalid Address");const e=a.Address.parseFriendly(t);return e.isTestOnly&&!qu?n("Please enter mainnet address"):i(e);case"URL":return t.startsWith("https://")?i(t):n("Invalid URL");case"Status":return yd.indexOf(t)>-1?i(t):n("Invalid status. Please use: "+yd.join(", "))}},mh=(0,a.toNano)("0.2"),yh=(0,a.toNano)("0.1"),bh=(0,a.toNano)("0.05"),wh=async e=>{try{const t=th,r=await Pd(e.jettonMinterAddress,qu,!1);return t.address.address.equals(r.adminAddress)?{value:r}:{error:"Multisig is not admin of this jetton"}}catch(e){return console.error(e),{error:"Jetton-minter check error"}}},vh=async e=>{try{const t=await th.multisigContract.getOrderAddress(th.provider,e);return"uninit"===(await qc("account",{address:t.toRawString()},qu)).status?{value:!0}:{error:`Заявка ${e} уже существует`}}catch(e){return console.error(e),{error:"Possibly connectivity error"}}},Ch=[{name:"Отправить TON",fields:{amount:{name:"Количество TON",type:"TON"},toAddress:{name:"Адрес получения",type:"Address"}},makeMessage:async e=>({toAddress:e.toAddress,tonAmount:e.amount,body:(0,a.beginCell)().endCell()})},{name:"Отправить жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},toAddress:{name:"На адрес",type:"Address"}},makeMessage:async e=>{const t=e.jettonMinterAddress.address,r=th.address.address,n=Cd.createFromAddress(t),i=new Wc(t,qu);return{toAddress:{address:await n.getWalletAddress(i,r),isBounceable:!0,isTestOnly:qu},tonAmount:yh,body:md.transferMessage(e.amount,e.toAddress.address,r,null,0n,null)}}},{name:"Выпустить жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},toAddress:{name:"На адрес",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.mintMessage(e.toAddress.address,e.amount,e.jettonMinterAddress.address,th.address.address,null,0n,bh)})},{name:"Сменить администратора жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},newAdminAddress:{name:"Новый адрес администратора",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.changeAdminMessage(e.newAdminAddress.address)})},{name:"Запросить адрес администратора",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"}},check:async e=>{try{const t=th,r=await Pd(e.jettonMinterAddress,qu,!0);return r.nextAdminAddress&&t.address.address.equals(r.nextAdminAddress)?{value:r}:{error:"Multisig is not next-admin of this jetton"}}catch(e){return console.error(e),{error:"Jetton-minter check error"}}},makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.claimAdminMessage()})},{name:"Пополнить контракт жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество TON",type:"TON"}},makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:e.amount,body:Cd.topUpMessage()})},{name:"Сменить метаданные жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},newMetadataUrl:{name:"Новая URL ссылка с метаданными",type:"URL"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.changeContentMessage({uri:e.newMetadataUrl})})},{name:"Принудительно сжечь жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},fromAddress:{name:"Адрес пользователя",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.forceBurnMessage(e.amount,e.fromAddress.address,th.address.address,bh)})},{name:"Принудительно отправить жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},fromAddress:{name:"С адреса",type:"Address"},toAddress:{name:"На адрес",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.forceTransferMessage(e.amount,e.toAddress.address,e.fromAddress.address,e.jettonMinterAddress.address,null,0n,null,bh)})},{name:"Сменить состояние контракта жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},userAddress:{name:"Адрес пользователя",type:"Address"},newStatus:{name:"Новое состояние (Разблокировать, исх., вход., полная блокировка)",type:"Status"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.lockWalletMessage(e.userAddress.address,bd(e.newStatus),bh)})}],_h=Fu("#newOrder_typeInput");_h.innerHTML=(()=>{let e="";for(let t=0;t${Ch[t].name}`;return e})();const kh=e=>{const t=Ch[e];let r="";for(let n in t.fields)if(t.fields.hasOwnProperty(n)){const i=t.fields[n];if(r+=`
${i.name}:
`,"Status"===i.type){r+=`"}else r+=``}Fu("#newOrder_fieldsContainer").innerHTML=r};_h.addEventListener("change",(e=>{kh(_h.selectedIndex)})),kh(0);let xh,Ah="fill";const Sh=()=>{if(!th)return"";let e=-1n;return th.lastOrders.forEach((t=>{t.order.id>e&&(e=t.order.id)})),-1n===e?"":(e+1n).toString()},Bh=()=>{Ph("fill"),xh=void 0,_h.selectedIndex=0,kh(0),Fu("#newOrder_orderId").value=Sh()},Eh=e=>{Fu("#newOrder_createButton").disabled=e,Fu("#newOrder_backButton").disabled=e},Ih=e=>{const t=_h.selectedIndex,r=Ch[t];_h.disabled=e,Fu("#newOrder_orderId").disabled=e;for(let n in r.fields)r.fields.hasOwnProperty(n)&&(Fu(`#newOrder_${t}_${n}`).disabled=e);Eh(e)},Ph=e=>{"fill"==e?(Ih(!1),Fu("#newOrder_createButton").innerHTML="Создать",Fu("#newOrder_backButton").innerHTML="Назад"):(Ih(!0),Fu("#newOrder_createButton").innerHTML="Отправить транзакцию",Fu("#newOrder_backButton").innerHTML="Отменить"),Ah=e};Fu("#newOrder_createButton").addEventListener("click",(async()=>{if(!Yu)return void alert("Please connect wallet");if("confirm"===Ah){if(!xh)throw new Error("");try{await Qu.sendTransaction({validUntil:Math.floor(Date.now()/1e3)+60,messages:[xh.message]}),eh===Zu(xh.multisigAddress)&&ph(xh.orderId)}catch(e){console.error(e)}return}const e=Mh(Fu("#newOrder_orderId"));if(null==e||e<0)return void alert("Invalid Order ID");const t=_h.selectedIndex,r=Ch[t],n={};for(let e in r.fields)if(r.fields.hasOwnProperty(e)){const i=r.fields[e],o=Fu(`#newOrder_${t}_${e}`).value,s=gh(i.name,o,i.type);if(s.error)return void alert(s.error);n[e]=s.value}Ih(!0);const i=await vh(e);if(i.error)return alert(i.error),void Ph("fill");if(r.check){const e=await r.check(n);if(e.error)return alert(e.error),void Ph("fill")}const o=await r.makeMessage(n),s=th.proposers.findIndex((e=>e.address.equals(Yu))),l=th.signers.findIndex((e=>e.address.equals(Yu)));if(-1===s&&-1===l)return alert("Error: you are not proposer and not signer"),void Ph("fill");const c=l>-1,d=o.toAddress,u=o.tonAmount,h=o.body,f=Math.floor(Date.now()/1e3)+2592e3,p=ud.packOrder([{type:"transfer",sendMode:a.SendMode.PAY_GAS_SEPARATELY,message:{info:{type:"internal",ihrDisabled:!1,bounce:!0,bounced:!1,dest:d.address,value:{coins:u},ihrFee:0n,forwardFee:0n,createdLt:0n,createdAt:0},body:h}}]),g=ud.newOrderMessage(p,f,c,c?l:s,e,0n),m=g.toBoc().toString("base64");console.log({toAddress:d,tonAmount:u,payloadCell:h,message:g,orderId:e});const y=eh,b=mh.toString();xh={multisigAddress:a.Address.parseFriendly(y).address,orderId:e,message:{address:y,amount:b,payload:m}},Ph("confirm"),Eh(!1)})),Fu("#newOrder_backButton").addEventListener("click",(()=>{"fill"==Ah?Gu("multisigScreen"):Ph("fill")}));const Mh=e=>{if(""===e.value)return null;try{return BigInt(e.value)}catch(e){return null}},Uh=Fu("#newMultisig_threshold"),Th=Fu("#newMultisig_orderId");let Oh,Rh,jh="create",Lh="fill";const zh=e=>{jh=e,Gu("newMultisigScreen")},Nh=()=>{if(Lh="fill",Oh={signersCount:0,proposersCount:0},Rh=void 0,Fu("#newMultisig_signersContainer").innerHTML="",Fu("#newMultisig_proposersContainer").innerHTML="",Th.value=Sh(),Uh.value="",Ku(Fu("#newMultisig_orderIdLabel"),"update"===jh),Ku(Fu("#newMultisig_orderId"),"update"===jh),"create"===jh)$h(0),Oh.signersCount=1;else{Oh.signersCount=th.signers.length;for(let e=0;e{const e=Fu("#newMultisig_deleteSigner0");Ku(e,Oh.signersCount>1)},$h=(e,t)=>{const r=document.createElement("div");r.classList.add("address-input"),r.innerHTML=`
#${e+1}.
`,Fu("#newMultisig_signersContainer").appendChild(r),Fu(`#newMultisig_signer${e}`).value=void 0===t?"":t,r.querySelector(`#newMultisig_deleteSigner${e}`).addEventListener("click",Kh)},Fh=(e,t)=>{const r=document.createElement("div");r.classList.add("address-input"),r.innerHTML=`
#${e+1}.
`,Fu("#newMultisig_proposersContainer").appendChild(r),Fu(`#newMultisig_proposer${e}`).value=void 0===t?"":t,r.querySelector(`#newMultisig_deleteProposer${e}`).addEventListener("click",Hh)},Kh=e=>{const t=e.target,r=Number(t.id.slice(24));if(isNaN(r))throw new Error;const n=[];for(let e=0;e{const t=e.target,r=Number(t.id.slice(26));if(isNaN(r))throw new Error;const n=[];for(let e=0;e{$h(Oh.signersCount),Oh.signersCount++,Dh()})),Fu("#newMultisig_addProposerButton").addEventListener("click",(async()=>{Fh(Oh.proposersCount),Oh.proposersCount++}));const Vh=()=>{const e="confirm"===Lh;Th.disabled=e,Uh.disabled=e,Ku(Fu("#newMultisig_addSignerButton"),!e),Ku(Fu("#newMultisig_addProposerButton"),!e);for(let t=0;t1)}for(let t=0;t{"fill"===Lh?Gu("create"===jh?"startScreen":"multisigScreen"):(Lh="fill",Vh())}));const qh=e=>{Fu("#newMultisig_createButton").disabled=e,Fu("#newMultisig_createButton").innerText=e?"Проверка..":"confirm"===Lh?"Подтвердить":"update"===jh?"Обновить":"Создать",Fu("#newMultisigScreen").style.pointerEvents=e?"none":"auto"};Fu("#newMultisig_createButton").addEventListener("click",(async()=>{if(!Yu)return void alert("Пожалуйста подключите кошелек");if("confirm"===Lh){try{const e=Rh.orderId,t=Rh.multisigAddress;await Qu.sendTransaction({validUntil:Math.floor(Date.now()/1e3)+60,messages:[Rh.message]}),"update"===jh?eh===Zu(t)&&ph(e):sh(Zu(t))}catch(e){console.error(e)}return}const e=(e=>{if(""===e.value)return null;try{const t=parseInt(e.value);return isNaN(t)?null:t}catch(e){return null}})(Uh);if(null==e||e<=0||e>Oh.signersCount)return void alert("Порог голосования: недопустимое число");let t;if("update"===jh){if(t=Mh(Th),null==t||t<0)return void alert("Invalid order Id");qh(!0);const e=await vh(t);if(qh(!1),e.error)return void alert(e.error)}const r={},n=[];for(let e=0;e{null!=o.splitDepth?(e.storeBit(!0),e.storeUint(o.splitDepth,5)):e.storeBit(!1),null!=o.special?(e.storeBit(!0),e.store(function(e){return t=>{t.storeBit(e.tick),t.storeBit(e.tock)}}(o.special))):e.storeBit(!1),e.storeMaybeRef(o.code),e.storeMaybeRef(o.data),e.storeDict(o.libraries)})(l),Rh={multisigAddress:r,message:{address:r.toString({urlSafe:!0,bounceable:!0,testOnly:qu}),amount:s,stateInit:l.endCell().toBoc().toString("base64")}},Lh="confirm",Vh()}else{const r=th.proposers.findIndex((e=>e.address.equals(Yu))),o=th.signers.findIndex((e=>e.address.equals(Yu)));if(-1===r&&-1===o)return void alert("Error: you are not proposer and not signer");const s=o>-1,l=Math.floor(Date.now()/1e3)+2592e3,c=ud.packOrder([{type:"update",threshold:e,signers:n,proposers:i}]),d=ud.newOrderMessage(c,l,s,s?o:r,t,0n).toBoc().toString("base64"),u=eh,h=yh.toString();Rh={multisigAddress:a.Address.parseFriendly(u).address,orderId:t,message:{address:u,amount:h,payload:d}},Lh="confirm",Vh()}var o}));const Zh=e=>{if(a.Address.isFriendly(e))return a.Address.parseFriendly(e)},Wh=async()=>{nh(),dh();const e=window.location.hash.substring(1);if(e){const{multisigAddress:t,orderId:r}=(e=>{if(e.indexOf("/")>-1){const t=e.split("/");if(2!==t.length)return{};const r=Zh(t[0]);if(void 0===r)return{};const n=(e=>{try{const t=BigInt(e);if(t<0)return;return t}catch(e){return}})(t[1]);return void 0===n?{}:{multisigAddress:r,orderId:n}}return{multisigAddress:Zh(e)}})(e);if(console.log(t,r),void 0===t)alert("Invalid URL"),Gu("startScreen");else{const e=Zu(t.address);await sh(e,r),void 0!==r&&eh===e&&await ph(r,void 0)}}else(()=>{const e=localStorage.getItem("multisigAddress");e?sh(e):Gu("startScreen")})()};Wh(),window.onpopstate=()=>Wh()})()})(); \ No newline at end of file +`,Oc=e=>{const t=Gn(e),r=nt(Bs),[n,i]=Ze(!0);let o;(null==r?void 0:r.wallet)&&"universalLink"in r.wallet&&("universal-link"===r.wallet.openMethod||L(r.wallet.universalLink)&&On())&&(o=r.wallet.universalLink);const s=()=>{const e=Jr(),t="returnStrategy"in e?e.returnStrategy:Ga.returnStrategy;if(L(o)){const r=!n();i(!1),El(o,{returnStrategy:t,twaReturnUrl:"twaReturnUrl"in e?e.twaReturnUrl:Ga.twaReturnUrl,forceRedirect:r})}else Tr(Bl(o,t))};return kt(Pc,Bt(t,{get children(){return[Qe((()=>e.icon)),kt(Mc,{get translationKey(){return e.headerTranslationKey},get translationValues(){return e.headerTranslationValues}}),kt(Uc,{get translationKey(){return e.textTranslationKey},get translationValues(){return e.textTranslationValues}}),kt(Pt,{get when(){return"open-wallet"!==e.showButton},get children(){return kt(Tc,{onClick:()=>e.onClose(),get children(){return kt(Sl,{translationKey:"common.close",children:"Close"})}})}}),kt(Pt,{get when(){return"open-wallet"===e.showButton&&o},get children(){return kt(Tc,{onClick:s,get children(){return kt(Sl,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}}))},Rc=e=>{const t=nt(Bs),[r]=Gi();return kt(Oc,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:t.wallet&&"name"in t.wallet?t.wallet.name:r("common.yourWallet",{},"Your wallet")}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return kt(Mo,{size:"m"})},onClose:()=>e.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},jc=e=>kt(Oc,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return kt(Bo,{size:"m"})},onClose:()=>e.onClose(),"data-tc-transaction-canceled-modal":"true"}),Lc=e=>kt(Oc,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return kt(ko,{size:"m"})},onClose:()=>e.onClose(),"data-tc-transaction-sent-modal":"true"}),zc=()=>kt(Ai,{get opened(){var e;return Qe((()=>null!==Jr()))()&&!0===(null==(e=Jr())?void 0:e.openModal)},get enableAndroidBackHandler(){return Ga.enableAndroidBackHandler},onClose:()=>Xr(null),"data-tc-actions-modal-container":"true",get children(){return kt(Mt,{get children(){return[kt(Ut,{get when(){return"transaction-sent"===Jr().name},get children(){return kt(Lc,{onClose:()=>Xr(null)})}}),kt(Ut,{get when(){return"transaction-canceled"===Jr().name},get children(){return kt(jc,{onClose:()=>Xr(null)})}}),kt(Ut,{get when(){return"confirm-transaction"===Jr().name},get children(){return kt(Rc,{onClose:()=>Xr(null)})}})]}})}}),Nc=e=>{const t=((e={},t=(navigator.language in e?navigator.language:Object.keys(e)[0]))=>{const[r,n]=Ze(t),[i,o]=bn(e);return[(e,t,n)=>{const o=Zi(i[r()],e,n||"");return"function"==typeof o?o(t):"string"==typeof o?((e,t,r=/{{(.*?)}}/g)=>e.replace(r,((e,r)=>Zi(t,r,""))))(o,t||{}):o},{add(e,t){o(e,(e=>Object.assign(e||{},t)))},locale:e=>e?n(e):r(),dict:e=>Zi(i,e)}]})(en,Ga.language);return customElements.define(kr,class extends HTMLElement{}),document.body.hasAttribute("ontouchstart")||document.body.setAttribute("ontouchstart",""),kt(Wi.Provider,{value:t,get children(){return kt(Bs.Provider,{get value(){return e.tonConnectUI},get children(){return kt(rn.Provider,{get value(){return Ga.connector},get children(){return[kt(Sr,{}),kt(br,{theme:kn,get children(){return[kt(Pt,{get when(){return Ga.buttonRootId},get children(){return kt(rr,{get mount(){return document.getElementById(Ga.buttonRootId)},get children(){return kt(Va,{})}})}}),kt(nr,{component:kr,get children(){return[kt(Ic,{}),kt(zc,{})]}})]}})]}})}})}})},Dc=()=>{setTimeout((()=>qr({status:"opened",closeReason:null})))},$c=e=>{setTimeout((()=>Xr(e)))};class Fc{constructor(e){Ie(this,"connector"),Ie(this,"setConnectRequestParametersCallback"),Ie(this,"consumers",[]),Ie(this,"state",Vr()),this.connector=e.connector,this.setConnectRequestParametersCallback=e.setConnectRequestParametersCallback,Ye((()=>{const e=Vr();this.state=e,this.consumers.forEach((t=>t(e)))}))}open(){return Pe(this,null,(function*(){const e=(yield this.connector.getWallets()).find(ee);return e?this.connectEmbeddedWallet(e):this.connectExternalWallet()}))}close(){var e;e="action-cancelled",setTimeout((()=>qr({status:"closed",closeReason:e})))}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter((t=>t!==e))}}connectEmbeddedWallet(e){const t=t=>{Qr(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},t)},r=Ga.connectRequestParameters;"loading"===(null==r?void 0:r.state)?this.setConnectRequestParametersCallback(t):t(null==r?void 0:r.value)}connectExternalWallet(){return Pe(this,null,(function*(){return On()&&Rn(),Dc(),new Promise((e=>{const t=this.onStateChange((r=>{const{status:n}=r;"opened"===n&&(t(),e())}))}))}))}}class Kc{constructor(e){Ie(this,"connector"),Ie(this,"consumers",[]),this.connector=e.connector,Ye((()=>{const e=Jr();this.consumers.forEach((t=>t(e)))}))}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter((t=>t!==e))}}}var Hc=r(3515);const Vc="d843619b379084d133f061606beecbf72ae2bf60e0622e808f2a3f631673599b",qc=async(e,t,r)=>{const n=r?"https://testnet.toncenter.com/api/v3/":"https://toncenter.com/api/v3/",i={"Content-Type":"application/json","X-API-Key":Vc},o=await fetch(n+e+"?"+new URLSearchParams(t),{method:"GET",headers:i}),s=await o.json();if(s.error)throw new Error(s.error);return s},Zc=async(e,t,r)=>{const n=r?"https://testnet.tonapi.io/v2/":"https://tonapi.io/v2/",i=await fetch(n+e+"?"+new URLSearchParams(t),{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer AHIQH4F4Y4XR6UIAAAAOGYUHWOWLUS6ZIPEXSCLAPOMMD6FSNMPUKHCIJHIP52YTU4VKURA"}}),o=await i.json();if(o.error)throw new Error(o.error);return o};class Wc{constructor(e,t){this.contractAddress=e,this.isTestnet=t,this.tonClient=new Hc.TonClient({endpoint:t?"https://testnet.toncenter.com/api/v2/jsonRPC":"https://toncenter.com/api/v2/jsonRPC",apiKey:Vc})}getState(){throw new Error("Method not implemented.")}get(e,t){return this.tonClient.runMethod(this.contractAddress,e,t)}external(e){throw new Error("Method not implemented.")}internal(e,t){throw new Error("Method not implemented.")}open(e){throw new Error("Method not implemented.")}getTransactions(e,t,r,n){throw new Error("Method not implemented.")}}const Gc=(e,t)=>a.Address.isFriendly(e)?a.Address.parseFriendly(e).isTestOnly&&!t?"Please enter mainnet address":null:"Invalid address",Yc={},Qc=async(e,t)=>{const r=e.toRawString();let n=Yc[r];return n||(n=(await qc("addressBook",{address:r},t))[r].user_friendly,Yc[r]=n),a.Address.parseFriendly(n)},Jc=async(e,t)=>{const r=await Qc(e,t);return Xc(r)},Xc=e=>{const t=ed(e),r=((e,t)=>(a.Address.parseFriendly(e),(t?"https://testnet.tonviewer.com/":"https://tonviewer.com/")+e))(t,e.isTestOnly);return`${t}`},ed=e=>e.address.toString({bounceable:e.isBounceable,testOnly:e.isTestOnly}),td=(e,t)=>e?t?e.equals(t):!e:!t,rd=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r{if(!e)throw console.error(t),new Error(t)},id=e=>{const t=document.createElement("div");return t.innerText=e,t.innerHTML};class od{}od.multisig={new_order:4145565967,execute:1963556701,execute_internal:2737592767},od.order={approve:2808226575,expired:6,approve_rejected:2947491902,approved:2187369462,init:2624846754},od.actions={send_message:4046986843,update_multisig_params:487390163};class sd{}sd.multisig={unauthorized_new_order:1007,invalid_new_order:1008,not_enough_ton:100,unauthorized_execute:101,singers_outdated:102,invalid_dictionary_sequence:103,expired:111},sd.order={unauthorized_init:104,already_approved:107,already_inited:105,unauthorized_sign:106,expired:111,unknown_op:65535,already_executed:112};class ad{}function ld(e){let t=a.Dictionary.empty(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Address());for(let r=0;r0||e.remainingRefs>0)throw new Error("remaining bits in data")}ad.bitsize={op:32,queryId:64,orderSeqno:256,signerIndex:8,actionIndex:8,time:48};class ud{constructor(e,t,r){this.address=e,this.init=t,this.configuration=r,this.orderSeqno=0n}static createFromAddress(e){let t=new ud(e);return t.orderSeqno=0n,t}static createFromConfig(e,t,r=0){const n=function(e){return(0,a.beginCell)().storeUint(0,ad.bitsize.orderSeqno).storeUint(e.threshold,ad.bitsize.signerIndex).storeRef((0,a.beginCell)().storeDictDirect(ld(e.signers))).storeUint(e.signers.length,ad.bitsize.signerIndex).storeDict(ld(e.proposers)).storeBit(e.allowArbitrarySeqno).endCell()}(e),i={code:t,data:n};return new ud((0,a.contractAddress)(r,i),i,e)}async sendDeploy(e,t,r){await e.internal(t,{value:r,sendMode:a.SendMode.PAY_GAS_SEPARATELY,body:(0,a.beginCell)().storeUint(0,ad.bitsize.op).storeUint(0,ad.bitsize.queryId).endCell()})}static packTransferRequest(e){let t=(0,a.beginCell)().store((0,a.storeMessageRelaxed)(e.message)).endCell();return(0,a.beginCell)().storeUint(od.actions.send_message,ad.bitsize.op).storeUint(e.sendMode,8).storeRef(t).endCell()}static packUpdateRequest(e){return(0,a.beginCell)().storeUint(od.actions.update_multisig_params,ad.bitsize.op).storeUint(e.threshold,ad.bitsize.signerIndex).storeRef((0,a.beginCell)().storeDictDirect(ld(e.signers))).storeDict(ld(e.proposers)).endCell()}static packOrder(e){let t=a.Dictionary.empty(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell());if(e.length>255)throw new Error("For action chains above 255, use packLarge method");for(let r=0;r{switch(e){case"unlock":return 0;case"out":return 1;case"in":return 2;case"full":return 3;default:throw new Error("Неправильное значение!")}},wd=e=>{switch(e){case"unlock":return"Разблокировать";case"out":return"Исходящие транзакции заблокированы";case"in":return"Входящие транзакции заблокированы";case"full":return"Исходящие и входящие транзакции заблокированы"}};function vd(e){if(e.remainingBits>0||e.remainingRefs>0)throw new Error("remaining bits in data")}class Cd{constructor(e,t){this.address=e,this.init=t}static createFromAddress(e){return new Cd(e)}static createFromConfig(e,t,r=0){const n=function(e){const t=e.jetton_content instanceof a.Cell?e.jetton_content:function(e){return(0,a.beginCell)().storeStringTail(e.uri).endCell()}(e.jetton_content);return(0,a.beginCell)().storeCoins(0).storeAddress(e.admin).storeAddress(null).storeRef(e.wallet_code).storeRef(t).endCell()}(e),i={code:t,data:n};return new Cd((0,a.contractAddress)(r,i),i)}async sendDeploy(e,t,r){await e.internal(t,{value:r,sendMode:a.SendMode.PAY_GAS_SEPARATELY,body:(0,a.beginCell)().storeUint(pd.top_up,32).storeUint(0,64).endCell()})}static mintMessage(e,t,r,n,i,o,s){const l=(0,a.beginCell)().storeUint(pd.internal_transfer,32).storeUint(0,64).storeCoins(t).storeAddress(r).storeAddress(n).storeCoins(o).storeMaybeRef(i).endCell();return(0,a.beginCell)().storeUint(pd.mint,32).storeUint(0,64).storeAddress(e).storeCoins(s).storeRef(l).endCell()}static parseMintInternalMessage(e){if(e.loadUint(32)!==pd.internal_transfer)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadCoins(),n=e.loadAddress(),i=e.loadAddress(),o=e.loadCoins(),s=e.loadBit()?e.loadRef().beginParse():e;return vd(e),{queryId:t,jettonAmount:r,fromAddress:n,responseAddress:i,forwardTonAmount:o,forwardPayload:s}}static parseMintMessage(e){if(e.loadUint(32)!==pd.mint)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadAddress(),n=e.loadCoins(),i=e.loadRef();return vd(e),{queryId:t,toAddress:r,tonAmount:n,internalMessage:this.parseMintInternalMessage(i.beginParse())}}static topUpMessage(){return(0,a.beginCell)().storeUint(pd.top_up,32).storeUint(0,64).endCell()}static parseTopUp(e){if(e.loadUint(32)!==pd.top_up)throw new Error("Invalid op");const t=e.loadUint(64);return vd(e),{queryId:t}}static changeAdminMessage(e){return(0,a.beginCell)().storeUint(pd.change_admin,32).storeUint(0,64).storeAddress(e).endCell()}static parseChangeAdmin(e){if(e.loadUint(32)!==pd.change_admin)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadAddress();return vd(e),{queryId:t,newAdminAddress:r}}static claimAdminMessage(e=0n){return(0,a.beginCell)().storeUint(pd.claim_admin,32).storeUint(e,64).endCell()}static parseClaimAdmin(e){if(e.loadUint(32)!==pd.claim_admin)throw new Error("Invalid op");const t=e.loadUint(64);return vd(e),{queryId:t}}static changeContentMessage(e){const t=e.uri;return(0,a.beginCell)().storeUint(pd.change_metadata_url,32).storeUint(0,64).storeStringTail(t).endCell()}static parseChangeContent(e){if(e.loadUint(32)!==pd.change_metadata_url)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadStringTail();return vd(e),{queryId:t,newMetadataUrl:r}}static lockWalletMessage(e,t,r,n=0){return(0,a.beginCell)().storeUint(pd.call_to,32).storeUint(n,64).storeAddress(e).storeCoins(r).storeRef((0,a.beginCell)().storeUint(pd.set_status,32).storeUint(n,64).storeUint(t,4).endCell()).endCell()}static parseSetStatus(e){if(e.loadUint(32)!==pd.set_status)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadUint(4);return vd(e),{queryId:t,newStatus:r}}static parseCallTo(e,t){if(e.loadUint(32)!==pd.call_to)throw new Error("Invalid op");const r=e.loadUint(64),n=e.loadAddress(),i=e.loadCoins(),o=e.loadRef();return vd(e),{queryId:r,toAddress:n,tonAmount:i,action:t(o.beginParse())}}static forceTransferMessage(e,t,r,n,i,o,s,l,c=0n){const d=md.transferMessage(e,t,n,i,o,s);return(0,a.beginCell)().storeUint(pd.call_to,32).storeUint(c,64).storeAddress(r).storeCoins(l).storeRef(d).endCell()}static parseTransfer(e){if(e.loadUint(32)!==pd.transfer)throw new Error("Invalid op");return{queryId:e.loadUint(64),jettonAmount:e.loadCoins(),toAddress:e.loadAddress(),responseAddress:e.loadAddress(),customPayload:e.loadMaybeRef(),forwardTonAmount:e.loadCoins(),forwardPayload:e.loadBit()?e.loadRef().beginParse():e}}static forceBurnMessage(e,t,r,n,i=0){return(0,a.beginCell)().storeUint(pd.call_to,32).storeUint(i,64).storeAddress(t).storeCoins(n).storeRef(md.burnMessage(e,r,null)).endCell()}static parseBurn(e){if(e.loadUint(32)!==pd.burn)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadCoins(),n=e.loadAddress(),i=e.loadMaybeRef();return vd(e),{queryId:t,jettonAmount:r,responseAddress:n,customPayload:i}}static upgradeMessage(e,t,r=0){return(0,a.beginCell)().storeUint(pd.upgrade,32).storeUint(r,64).storeRef(t).storeRef(e).endCell()}static parseUpgrade(e){if(e.loadUint(32)!==pd.upgrade)throw new Error("Invalid op");const t=e.loadUint(64),r=e.loadRef(),n=e.loadRef();return vd(e),{queryId:t,newData:r,newCode:n}}async getWalletAddress(e,t){const r=await e.get("get_wallet_address",[{type:"slice",cell:(0,a.beginCell)().storeAddress(t).endCell()}]);return nd(1===r.stack.remaining,"invalid get_wallet_address result"),r.stack.readAddress()}async getJettonData(e){let t=await e.get("get_jetton_data",[]);return nd(5===t.stack.remaining,"invalid get_jetton_data result"),{totalSupply:t.stack.readBigNumber(),mintable:t.stack.readBoolean(),adminAddress:t.stack.readAddress(),content:t.stack.readCell(),walletCode:t.stack.readCell()}}async getNextAdminAddress(e){const t=await e.get("get_next_admin_address",[]);return nd(1===t.stack.remaining,"invalid get_next_admin_address result"),t.stack.readAddressOpt()}}const _d=e=>{if(null===e)throw new Error("Invalid number");if(void 0===e)throw new Error("Invalid number");if(isNaN(e))throw new Error("Invalid number");if(e<0)throw new Error("Invalid number")},kd=async(e,t,r,n,i)=>{const o=await qc("account",{address:ed(e)},n);nd("active"===o.status,"Контракт не активен. Если вы только что создали заявку, она должна появиться в течение ~30 секунд."),nd(a.Cell.fromBase64(o.code).equals(t),"Код контракта НЕ совпадает с кодом мультикошелька заявки из этого хранилища");const s=o.balance,l=function(e){const t=e.beginParse(),r=t.loadAddress(),n=t.loadUintBig(256);if(0===t.remainingBits)throw new Error("Order not initialized");const i=t.loadUint(8),o=t.loadBoolean(),s=hd(t.loadRef()),a=t.loadUint(256),l=t.loadUint(8),c=t.loadUint(48),d=t.loadRef();return dd(t),{multisigAddress:r,orderSeqno:n,threshold:i,isExecuted:o,signers:s,approvalsMask:a,approvalsNum:l,expirationDate:c,order:d}}(a.Cell.fromBase64(o.data));_d(l.threshold),nd(l.threshold>0,"Порог голосующих не является положительным"),nd(l.threshold<=l.signers.length,"Недопустимый порог"),_d(l.approvalsMask),_d(l.approvalsNum),nd(l.approvalsNum<=l.signers.length,"Неправильное количество"),_d(l.expirationDate);const c=[];for(const e of l.signers)c.push(await Qc(e,n));nd(l.multisigAddress.equals(r.address.address),"Адрес мультикошелька не найден");const d=fd.createFromConfig({multisig:r.address.address,orderSeqno:l.orderSeqno},t);if(nd(d.address.equals(e.address),"Неправильный адрес заявки"),l.isExecuted||(nd(r.threshold<=l.threshold,"Количество подтверждающих не соответствует порогу заявки"),nd(rd(r.signers.map((e=>e.address)),l.signers),"Количество подтверждающих не совпадает с количествои в заявке")),i){const t=new Wc(e.address,n),r=fd.createFromAddress(e.address),i=await r.getOrderDataStrict(t);nd(i.multisig.equals(l.multisigAddress),"Invalid multisigAddress"),nd(i.order_seqno===l.orderSeqno,"Invalid orderSeqno"),nd(i.threshold===l.threshold,"Invalid threshold"),nd(i.executed===l.isExecuted,"Invalid isExecuted"),nd(rd(i.signers,l.signers),"Invalid signers"),nd(i._approvals===BigInt(l.approvalsMask),"Invalid approvalsMask"),nd(i.approvals_num===l.approvalsNum,"Invalid approvalsNum"),nd(i.expiration_date===BigInt(l.expirationDate),"Invalid expirationDate"),nd(i.order.hash().equals(l.order.hash()),"Invalid order")}const u=fd.createFromConfig({multisig:l.multisigAddress,orderSeqno:l.orderSeqno},t).address.equals(e.address),h=a.Dictionary.loadDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell(),l.order),f=async e=>{try{const t=e.beginParse();if(0===t.remainingBits&&0==t.remainingRefs)return"Отправьте TON с помощью мультикошелька без комментариев"}catch(e){}try{const t=e.beginParse();if(0==t.loadUint(32)){const e=t.loadStringTail();return`Отправьте TON с помощью мультикошелька с комментарием "${id(e)}"`}}catch(e){}try{const t=e.beginParse(),r=Cd.parseMintMessage(t);nd(0===r.internalMessage.forwardPayload.remainingBits&&0===r.internalMessage.forwardPayload.remainingRefs,"Полезная нагрузка выпуска не поддерживается");const i=await Jc(r.toAddress,n);return`Выпустить ${r.internalMessage.jettonAmount} жетонов (в единицах измерения) на адрес ${i}; ${(0,a.fromNano)(r.tonAmount)} TON для оплаты газа`}catch(e){}try{const t=e.beginParse();return Cd.parseTopUp(t),"Пополнить"}catch(e){}try{const t=e.beginParse(),r=Cd.parseChangeAdmin(t);return`Смена адреса администратора на ${await Jc(r.newAdminAddress,n)}`}catch(e){}try{const t=e.beginParse();return Cd.parseClaimAdmin(t),"Запросить адрес администратора"}catch(e){}try{const t=e.beginParse(),r=Cd.parseChangeContent(t);return`Смена URL метаданных на "${id(r.newMetadataUrl)}"`}catch(e){}try{const t=e.beginParse(),r=Cd.parseTransfer(t);if(r.customPayload)throw new Error("Отправка состояния не поддерживается");nd(0===r.forwardPayload.remainingBits&&0===r.forwardPayload.remainingRefs,"Отправка не поддерживается");const i=await Jc(r.toAddress,n);return`Отправка ${r.jettonAmount} жетонов с адреса мультикошелька на адрес польщователя ${i};`}catch(e){}try{const t=e.beginParse(),r=Cd.parseCallTo(t,Cd.parseSetStatus),i=await Jc(r.toAddress,n),o=(e=>{switch(e){case 0:return"unlock";case 1:return"out";case 2:return"in";case 3:return"full";default:throw new Error("Неправильное значение!")}})(r.action.newStatus);return`Блокировка жетонов пользователя ${i}. Смена состояния "${o}" - "${wd(o)}"; ${(0,a.fromNano)(r.tonAmount)} TON для оплаты газа`}catch(e){}try{const t=e.beginParse(),r=Cd.parseCallTo(t,Cd.parseTransfer);if(r.action.customPayload)throw new Error("Принудительная отправка не поддерживается");nd(0===r.action.forwardPayload.remainingBits&&0===r.action.forwardPayload.remainingRefs,"Принудительная отправка не поддерживается");const i=await Jc(r.toAddress,n),o=await Jc(r.action.toAddress,n);return`Принудительная отправка ${r.action.jettonAmount} с адреса польщзвателя ${i} на адрес ${o}; ${(0,a.fromNano)(r.tonAmount)} TON for gas`}catch(e){}try{const t=e.beginParse(),r=Cd.parseCallTo(t,Cd.parseBurn);if(r.action.customPayload)throw new Error("Сжигание не поддерживается");const i=await Jc(r.toAddress,n);return`Принудительное сжигание ${r.action.jettonAmount} жетонов с адреса пользователя ${i}; ${(0,a.fromNano)(r.tonAmount)} TON for gas`}catch(e){}throw new Error("Неподдерживаемое действие")};let p=[];const g=h.keys();for(let e of g){let t=`
Действие №${e}:
`;const r=h.get(e).beginParse(),i=r.loadUint(32);if(4046986843===i){const e=r.loadUint(8);let i=[],o=!1;1&e&&i.push("Комиссии оплачиваются отдельно"),2&e&&i.push("Игнорировать ошибки отправки"),128&e&&(o=!0,i.push("Сохранить весь баланс")),64&e&&i.push("Перенесите все оставшееся значение входящего сообщения"),32&e&&i.push("УНИЧТОЖИТЬ УЧЕТНУЮ ЗАПИСЬ");const s=r.loadRef();dd(r);const l=(0,a.loadMessageRelaxed)(s.beginParse());console.log(l);const c=l.info,d=await Jc(c.dest,n);t+=`
Отправить ${o?"ВЕСЬ БАЛАНС":(0,a.fromNano)(c.value.coins)} TON на адрес ${d}
`,t+=`
${await f(l.body)}
`,e&&(t+=`
Метод отправки: ${i.join(", ")}.
`)}else{if(487390163!==i)throw new Error("Неправильное действие");{const e=r.loadUint(8),i=cd(r.loadRef()),o=r.loadUint(1)?cd(r.loadRef()):[];dd(r),nd(i.length>0,"Неправильный адрес подписывающего"),nd(e>0,"Неправильный новый порог"),nd(e<=i.length,"Неправильный порог"),t+="
Обновить параметры мультикошелька
",t+=`
Новый порог подписей : ${e.toString()}
`,t+="
Новые подтверждающие:
";for(let e=0;e#${e+1} - ${await Jc(r,n)}`}if(t+="
Новые предлагающие:
",o.length>0)for(let e=0;e#${e+1} - ${await Jc(r,n)}`}else t+="
Нет предлагающих
"}}p.push(t)}return{address:e,tonBalance:s,orderId:l.orderSeqno,isExecuted:l.isExecuted,approvalsNum:l.approvalsNum,approvalsMask:l.approvalsMask,threshold:l.threshold,signers:c,expiresAt:new Date(1e3*l.expirationDate),actions:p,stateInitMatches:u}};var xd=r(8287).hp;const Ad=e=>{const t=e.beginParse(),r=t.loadAddress(),n=t.loadUintBig(256);return dd(t),{multisigAddress:r,orderId:n}},Sd=e=>{const t=a.Address.parse(e.destination),r=(e=>{const t=e.beginParse();if(0!==t.loadUint(2))throw new Error("invalid init state prefix");const r=t.loadMaybeRef(),n=t.loadMaybeRef();if(t.loadBoolean())throw new Error("invalid init state empty libraries");return dd(t),{code:r,body:Ad(n)}})(a.Cell.fromBase64(e.init_state.body)),n=a.Cell.fromBase64(e.message_content.body).beginParse();nd(n.loadUint(32)===od.order.init,"invalid op");const i=n.loadUint(64),o=n.loadUint(8),s=n.loadRef().beginParse().loadDictDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Address()),l=n.loadUint(48),c=n.loadRef().beginParse().loadDictDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell()),d=n.loadUint(1);let u;return d&&(u=n.loadUint(8)),console.log("OUT",{queryId:i,threshold:o,signers:s,expiredAt:l,order:c,isSigner:d,signerIndex:u}),dd(n),{orderAddress:t,orderId:r.body.orderId}};var Bd=r(5269);const Ed=["uri","name","description","image","image_data","symbol","decimals","amount_style"],Id={serialize:(e,t)=>{t.storeRef((0,a.beginCell)().storeUint(0,8).storeStringTail(e).endCell())},parse:e=>{const t=e.loadRef().beginParse(),r=t.loadUint(8);if(0==r)return t.loadStringTail();if(1==r)return a.Dictionary.loadDirect(a.Dictionary.Keys.Uint(32),a.Dictionary.Values.Cell(),t).values().map((e=>e.beginParse().loadStringTail())).join("");throw Error(`Prefix ${r} is not supported yet`)}},Pd=async(e,t,r)=>{const n=await qc("account",{address:ed(e)},t);nd("active"===n.status,"Contract not active");const i=n.balance,o=new Wc(e.address,t),s=Cd.createFromAddress(e.address),l=await s.getJettonData(o);let c,d;const u=await(async e=>{const t=e.beginParse(),r=t.loadUint(8);if(1==r){const e=0==t.remainingBits;if(e&&0==t.remainingRefs)throw new Error("No data in content cell!");return e?t.loadStringRefTail():t.loadStringTail()}if(0==r){const e=a.Dictionary.load(a.Dictionary.Keys.BigUint(256),Id,t),r={};for(const t of Ed){const n=BigInt("0x"+(await(0,Bd.sha256)(t)).toString("hex")),i=e.get(n);void 0!==i&&(r[t]=i)}return r}throw new Error(`Unknown content format indicator:${r}`)})(l.content);if(u instanceof String)d=u;else{const e=u;d=e.uri;const t=e.decimals;if(void 0!==t&&(c=parseInt(t),isNaN(c)))throw new Error("invalid decimals")}let h;return r&&(h=await s.getNextAdminAddress(o)),{tonBalance:i,jettonMinterContract:s,adminAddress:l.adminAddress,nextAdminAddress:h,decimals:c,metadataUrl:d}};var Md=r(9107),Ud=r.n(Md),Td=r(8287).hp;function Od(e){let t=0;const r=Td.alloc(e.length+2);r.set(e);for(let e of r){let r=128;for(;r>0;)t<<=1,e&r&&(t+=1),r>>=1,t>65535&&(t&=65535,t^=4129)}return Td.from([Math.floor(t/256),t%256])}var Rd,jd,Ld=r(8287).hp;function zd(e){if("string"==typeof e&&!Nd.isFriendly(e))throw new Error("Unknown address type");const t=Ld.isBuffer(e)?e:Ld.from(e,"base64");if(36!==t.length)throw new Error("Unknown address type: byte length is not equal to 36");const r=t.subarray(0,34),n=t.subarray(34,36),i=Od(r);if(i[0]!==n[0]||i[1]!==n[1])throw new Error("Invalid checksum: "+e);let o=r[0],s=!1,a=!1;if(128&o&&(s=!0,o^=128),17!==o&&81!==o)throw"Unknown address tag";a=17===o;let l=null;return l=255===r[1]?-1:r[1],{isTestOnly:s,isBounceable:a,workchain:l,hashPart:r.subarray(2,34)}}class Nd{static isAddress(e){return e instanceof Nd}static isFriendly(e){return 48===e.length&&!!/[A-Za-z0-9+/_-]+/.test(e)}static isRaw(e){if(-1===e.indexOf(":"))return!1;let[t,r]=e.split(":");return!!Number.isInteger(parseFloat(t))&&!!/[a-f0-9]+/.test(r.toLowerCase())&&64===r.length}static normalize(e){return"string"==typeof e?Nd.parse(e).toString():e.toString()}static parse(e){if(Nd.isFriendly(e))return this.parseFriendly(e).address;if(Nd.isRaw(e))return this.parseRaw(e);throw new Error("Unknown address type: "+e)}static parseRaw(e){let t=parseInt(e.split(":")[0]),r=Ld.from(e.split(":")[1],"hex");return new Nd(t,r)}static parseFriendly(e){if(Ld.isBuffer(e)){let t=zd(e);return{isBounceable:t.isBounceable,isTestOnly:t.isTestOnly,address:new Nd(t.workchain,t.hashPart)}}{let t=zd(e.replace(/\-/g,"+").replace(/_/g,"/"));return{isBounceable:t.isBounceable,isTestOnly:t.isTestOnly,address:new Nd(t.workchain,t.hashPart)}}}constructor(e,t){if(this.toRawString=()=>this.workChain+":"+this.hash.toString("hex"),this.toRaw=()=>{const e=Ld.alloc(36);return e.set(this.hash),e.set([this.workChain,this.workChain,this.workChain,this.workChain],32),e},this.toStringBuffer=e=>{let t=!(!e||void 0===e.testOnly)&&e.testOnly,r=!e||void 0===e.bounceable||e.bounceable?17:81;t&&(r|=128);const n=Ld.alloc(34);n[0]=r,n[1]=this.workChain,n.set(this.hash,2);const i=Ld.alloc(36);return i.set(n),i.set(Od(n),34),i},this.toString=e=>{let t=!e||void 0===e.urlSafe||e.urlSafe,r=this.toStringBuffer(e);return t?r.toString("base64").replace(/\+/g,"-").replace(/\//g,"_"):r.toString("base64")},this[Rd]=()=>this.toString(),32!==t.length)throw new Error("Invalid address hash length: "+t.length);this.workChain=e,this.hash=t,Object.freeze(this)}equals(e){return e.workChain===this.workChain&&e.hash.equals(this.hash)}}Rd=Ud();class Dd{static isAddress(e){return e instanceof Dd}constructor(e,t){this[jd]=()=>this.toString(),this.value=e,this.bits=t}toString(){return`External<${this.bits}:${this.value}>`}}function $d(e){let t=new Zd(8*Math.ceil(e.length/8));t.writeBits(e);let r=8*Math.ceil(e.length/8)-e.length;for(let e=0;ethis.toString(),r<0)throw new Error(`Length ${r} is out of bounds`);this._length=r,this._data=e,this._offset=t}get length(){return this._length}at(e){if(e>=this._length)throw new Error(`Index ${e} > ${this._length} is out of bounds`);if(e<0)throw new Error(`Index ${e} < 0 is out of bounds`);let t=this._offset+e>>3,r=7-(this._offset+e)%8;return!!(this._data[t]&1<this._length)throw new Error(`Offset(${e}) > ${this._length} is out of bounds`);if(e<0)throw new Error(`Offset(${e}) < 0 is out of bounds`);if(0===t)return Hd.EMPTY;if(e+t>this._length)throw new Error(`Offset ${e} + Length ${t} > ${this._length} is out of bounds`);return new Hd(this._data,this._offset+e,t)}subbuffer(e,t){if(e>this._length)throw new Error(`Offset ${e} is out of bounds`);if(e<0)throw new Error(`Offset ${e} is out of bounds`);if(e+t>this._length)throw new Error(`Offset + Lenght = ${e+t} is out of bounds`);if(t%8!=0)return null;if((this._offset+e)%8!=0)return null;let r=this._offset+e>>3,n=r+(t>>3);return this._data.subarray(r,n)}equals(e){if(this._length!==e._length)return!1;for(let t=0;t8*this._buffer.length)throw new Error("BitBuilder overflow");("boolean"==typeof e&&!0===e||"number"==typeof e&&e>0)&&(this._buffer[t/8|0]|=1<<7-t%8),this._length++}writeBits(e){for(let t=0;t8*this._buffer.length)throw new Error("BitBuilder overflow");e.copy(this._buffer,this._length/8),this._length+=8*e.length}else for(let t=0;t=n)throw Error(`bitLength is too small for a value ${e}. Got ${t}`);if(this._length+t>8*this._buffer.length)throw new Error("BitBuilder overflow");const i=8-this._length%8;if(i>0){const e=Math.floor(this._length/8);if(t>BigInt(t-i));this._buffer[e]|=n,this._length+=i}}for(t-=i;t>0;)t>=8?(this._buffer[this._length/8]=Number(r>>BigInt(t-8)&0xffn),this._length+=8,t-=8):(this._buffer[this._length/8]=Number(r<=n)throw Error(`value is out of range for ${t} bits. Got ${e}`);r<0?(this.writeBit(!0),r=n+r):this.writeBit(!1),this.writeUint(r,t-1)}writeVarUint(e,t){let r=BigInt(e);if(t<0||!Number.isSafeInteger(t))throw Error(`invalid bit length. Got ${t}`);if(r<0)throw Error(`value is negative. Got ${e}`);if(0n===r)return void this.writeUint(0,t);const n=Math.ceil(r.toString(2).length/8),i=8*n;this.writeUint(n,t),this.writeUint(r,i)}writeVarInt(e,t){let r=BigInt(e);if(t<0||!Number.isSafeInteger(t))throw Error(`invalid bit length. Got ${t}`);if(0n===r)return void this.writeUint(0,t);let n=r>0?r:-r;const i=1+Math.ceil(n.toString(2).length/8),o=8*i;this.writeUint(i,t),this.writeInt(r,o)}writeCoins(e){this.writeVarUint(e,4)}writeAddress(e){if(null!=e){if(Nd.isAddress(e))return this.writeUint(2,2),this.writeUint(0,1),this.writeInt(e.workChain,8),void this.writeBuffer(e.hash);if(Dd.isAddress(e))return this.writeUint(1,2),this.writeUint(e.bits,9),void this.writeUint(e.value,e.bits);throw Error(`Invalid address. Got ${e}`)}this.writeUint(0,2)}build(){return new Hd(this._buffer,0,this._length)}buffer(){if(this._length%8!=0)throw new Error("BitBuilder buffer is not byte aligned");return this._buffer.subarray(0,this._length/8)}}!function(e){e[e.Ordinary=-1]="Ordinary",e[e.PrunedBranch=1]="PrunedBranch",e[e.Library=2]="Library",e[e.MerkleProof=3]="MerkleProof",e[e.MerkleUpdate=4]="MerkleUpdate"}(Vd||(Vd={}));var Wd,Gd=r(8287).hp;function Yd(e){if(e.remainingBits%8!=0)throw new Error(`Invalid string length: ${e.remainingBits}`);if(0!==e.remainingRefs&&1!==e.remainingRefs)throw new Error(`invalid number of refs: ${e.remainingRefs}`);let t;return t=0===e.remainingBits?Gd.alloc(0):e.loadBuffer(e.remainingBits/8),1===e.remainingRefs&&(t=Gd.concat([t,Yd(e.loadRef().beginParse())])),t}function Qd(e){return Yd(e).toString()}function Jd(e,t){if(e.length>0){let r=Math.floor(t.availableBits/8);if(e.length>r){let n=e.subarray(0,r),i=e.subarray(r);t=t.storeBuffer(n);let o=xu();Jd(i,o),t=t.storeRef(o.endCell())}else t=t.storeBuffer(e)}}function Xd(e,t){Jd(Gd.from(e),t)}class eu{constructor(e,t){this[Wd]=()=>this.toString(),this._reader=e.clone(),this._refs=[...t],this._refsOffset=0}get remainingBits(){return this._reader.remaining}get offsetBits(){return this._reader.offset}get remainingRefs(){return this._refs.length-this._refsOffset}get offsetRefs(){return this._refsOffset}skip(e){return this._reader.skip(e),this}loadBit(){return this._reader.loadBit()}preloadBit(){return this._reader.preloadBit()}loadBoolean(){return this.loadBit()}loadMaybeBoolean(){return this.loadBit()?this.loadBoolean():null}loadBits(e){return this._reader.loadBits(e)}preloadBits(e){return this._reader.preloadBits(e)}loadUint(e){return this._reader.loadUint(e)}loadUintBig(e){return this._reader.loadUintBig(e)}preloadUint(e){return this._reader.preloadUint(e)}preloadUintBig(e){return this._reader.preloadUintBig(e)}loadMaybeUint(e){return this.loadBit()?this.loadUint(e):null}loadMaybeUintBig(e){return this.loadBit()?this.loadUintBig(e):null}loadInt(e){return this._reader.loadInt(e)}loadIntBig(e){return this._reader.loadIntBig(e)}preloadInt(e){return this._reader.preloadInt(e)}preloadIntBig(e){return this._reader.preloadIntBig(e)}loadMaybeInt(e){return this.loadBit()?this.loadInt(e):null}loadMaybeIntBig(e){return this.loadBit()?this.loadIntBig(e):null}loadVarUint(e){return this._reader.loadVarUint(e)}loadVarUintBig(e){return this._reader.loadVarUintBig(e)}preloadVarUint(e){return this._reader.preloadVarUint(e)}preloadVarUintBig(e){return this._reader.preloadVarUintBig(e)}loadVarInt(e){return this._reader.loadVarInt(e)}loadVarIntBig(e){return this._reader.loadVarIntBig(e)}preloadVarInt(e){return this._reader.preloadVarInt(e)}preloadVarIntBig(e){return this._reader.preloadVarIntBig(e)}loadCoins(){return this._reader.loadCoins()}preloadCoins(){return this._reader.preloadCoins()}loadMaybeCoins(){return this._reader.loadBit()?this._reader.loadCoins():null}loadAddress(){return this._reader.loadAddress()}loadMaybeAddress(){return this._reader.loadMaybeAddress()}loadExternalAddress(){return this._reader.loadExternalAddress()}loadMaybeExternalAddress(){return this._reader.loadMaybeExternalAddress()}loadAddressAny(){return this._reader.loadAddressAny()}loadRef(){if(this._refsOffset>=this._refs.length)throw new Error("No more references");return this._refs[this._refsOffset++]}preloadRef(){if(this._refsOffset>=this._refs.length)throw new Error("No more references");return this._refs[this._refsOffset]}loadMaybeRef(){return this.loadBit()?this.loadRef():null}preloadMaybeRef(){return this.preloadBit()?this.preloadRef():null}loadBuffer(e){return this._reader.loadBuffer(e)}preloadBuffer(e){return this._reader.preloadBuffer(e)}loadStringTail(){return Qd(this)}loadMaybeStringTail(){return this.loadBit()?Qd(this):null}loadStringRefTail(){return Qd(this.loadRef().beginParse())}loadMaybeStringRefTail(){const e=this.loadMaybeRef();return e?Qd(e.beginParse()):null}loadDict(e,t){return $u.load(e,t,this)}loadDictDirect(e,t){return $u.loadDirect(e,t,this)}endParse(){if(this.remainingBits>0||this.remainingRefs>0)throw new Error("Slice is not empty")}asCell(){return xu().storeSlice(this).endCell()}asBuilder(){return xu().storeSlice(this)}clone(e=!1){if(e){let e=this._reader.clone();return e.reset(),new eu(e,this._refs)}{let e=new eu(this._reader,this._refs);return e._refsOffset=this._refsOffset,e}}toString(){return this.asCell().toString()}}Wd=Ud();var tu=r(8287).hp;class ru{constructor(e,t=0){this._checkpoints=[],this._bits=e,this._offset=t}get offset(){return this._offset}get remaining(){return this._bits.length-this._offset}skip(e){if(e<0||this._offset+e>this._bits.length)throw new Error(`Index ${this._offset+e} is out of bounds`);this._offset+=e}reset(){this._checkpoints.length>0?this._offset=this._checkpoints.pop():this._offset=0}save(){this._checkpoints.push(this._offset)}loadBit(){let e=this._bits.at(this._offset);return this._offset++,e}preloadBit(){return this._bits.at(this._offset)}loadBits(e){let t=this._bits.substring(this._offset,e);return this._offset+=e,t}preloadBits(e){return this._bits.substring(this._offset,e)}loadBuffer(e){let t=this._preloadBuffer(e,this._offset);return this._offset+=8*e,t}preloadBuffer(e){return this._preloadBuffer(e,this._offset)}loadUint(e){return Number(this.loadUintBig(e))}loadUintBig(e){let t=this.preloadUintBig(e);return this._offset+=e,t}preloadUint(e){return Number(this._preloadUint(e,this._offset))}preloadUintBig(e){return this._preloadUint(e,this._offset)}loadInt(e){let t=this._preloadInt(e,this._offset);return this._offset+=e,Number(t)}loadIntBig(e){let t=this._preloadInt(e,this._offset);return this._offset+=e,t}preloadInt(e){return Number(this._preloadInt(e,this._offset))}preloadIntBig(e){return this._preloadInt(e,this._offset)}loadVarUint(e){let t=Number(this.loadUint(e));return Number(this.loadUintBig(8*t))}loadVarUintBig(e){let t=Number(this.loadUint(e));return this.loadUintBig(8*t)}preloadVarUint(e){let t=Number(this._preloadUint(e,this._offset));return Number(this._preloadUint(8*t,this._offset+e))}preloadVarUintBig(e){let t=Number(this._preloadUint(e,this._offset));return this._preloadUint(8*t,this._offset+e)}loadVarInt(e){let t=Number(this.loadUint(e));return Number(this.loadIntBig(8*t))}loadVarIntBig(e){let t=Number(this.loadUint(e));return this.loadIntBig(8*t)}preloadVarInt(e){let t=Number(this._preloadUint(e,this._offset));return Number(this._preloadInt(8*t,this._offset+e))}preloadVarIntBig(e){let t=Number(this._preloadUint(e,this._offset));return this._preloadInt(8*t,this._offset+e)}loadCoins(){return this.loadVarUintBig(4)}preloadCoins(){return this.preloadVarUintBig(4)}loadAddress(){let e=Number(this._preloadUint(2,this._offset));if(2===e)return this._loadInternalAddress();throw new Error("Invalid address: "+e)}loadMaybeAddress(){let e=Number(this._preloadUint(2,this._offset));if(0===e)return this._offset+=2,null;if(2===e)return this._loadInternalAddress();throw new Error("Invalid address")}loadExternalAddress(){if(1===Number(this._preloadUint(2,this._offset)))return this._loadExternalAddress();throw new Error("Invalid address")}loadMaybeExternalAddress(){let e=Number(this._preloadUint(2,this._offset));if(0===e)return this._offset+=2,null;if(1===e)return this._loadExternalAddress();throw new Error("Invalid address")}loadAddressAny(){let e=Number(this._preloadUint(2,this._offset));if(0===e)return this._offset+=2,null;if(2===e)return this._loadInternalAddress();if(1===e)return this._loadExternalAddress();throw 3===e?Error("Unsupported"):Error("Unreachable")}loadPaddedBits(e){if(e%8!=0)throw new Error("Invalid number of bits");let t=e;for(;;){if(this._bits.at(this._offset+t-1)){t--;break}t--}let r=this._bits.substring(this._offset,t);return this._offset+=e,r}clone(){return new ru(this._bits,this._offset)}_preloadInt(e,t){if(0==e)return 0n;let r=this._bits.at(t),n=0n;for(let r=0;r>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135)>>24}(this._mask),this._hashCount=this._hashIndex+1}get value(){return this._mask}get level(){return 32-Math.clz32(this._mask)}get hashIndex(){return this._hashIndex}get hashCount(){return this._hashCount}apply(e){return new su(this._mask&(1<>e-1)%2!=0}}function au(e,t){let r,n=new ru(e),i=n.loadUint(8);if(1!==i)throw new Error(`Pruned branch cell must have type 1, got "${i}"`);if(0!==t.length)throw new Error(`Pruned Branch cell can't has refs, got "${t.length}"`);if(280===e.length)r=new su(1);else{if(r=new su(n.loadUint(8)),r.level<1||r.level>3)throw new Error(`Pruned Branch cell level must be >= 1 and <= 3, got "${r.level}/${r.value}"`);const t=16+272*r.apply(r.level-1).hashCount;if(e.length!==t)throw new Error(`Pruned branch cell must have exactly ${t} bits, got "${e.length}"`)}let o=[],s=[],a=[];for(let e=0;e>1);else if(e===Vd.MerkleUpdate)ou(t,r),n=new su((r[0].mask.value|r[1].mask.value)>>1);else{if(e!==Vd.Library)throw new Error("Unsupported exotic type");nu(t),n=new su}let o=[],s=[],a=e===Vd.PrunedBranch?1:n.hashCount,l=n.hashCount-a;for(let i=0,a=0;i<=n.level;i++){if(!n.isSignificant(i))continue;if(a0&&d++;let u=uu(t,c,r,i,n.apply(i).value,e),h=(0,Bd.sha256_sync)(u),f=a-l;o[f]=d,s[f]=h,a++}let c=[],d=[];if(i)for(let e=0;e<4;e++){const{hashIndex:t}=n.apply(e),{hashIndex:r}=n;t!==r?(c.push(i.pruned[t].hash),d.push(i.pruned[t].depth)):(c.push(s[0]),d.push(o[0]))}else for(let e=0;e<4;e++)c.push(s[n.apply(e).hashIndex]),d.push(o[n.apply(e).hashIndex]);return{mask:n,hashes:c,depths:d}}function fu(e,t){let r=BigInt(e);if("int"===t)return 0n===r||-1n===r?1:(r>0?r:-r).toString(2).length+1;if("uint"===t){if(r<0)throw Error(`value is negative. Got ${e}`);return r.toString(2).length}throw Error(`invalid mode. Got ${t}`)}var pu=r(8287).hp;const gu=2197175160;function mu(e){let t=-1;for(let r=0;r>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1,t=1&t?t>>>1^gu:t>>>1;t^=4294967295;let r=pu.alloc(4);return r.writeInt32LE(t),r}function yu(e){return function(e){let t=0;for(let r=0;r<3;r++)t+=1&e,e>>=1;return t+1}(7&e)}function bu(e,t){const r=e.loadUint(8),n=r%8,i=!!(8&r),o=e.loadUint(8),s=Math.ceil(o/2),a=!!(o%2),l=r>>5,c=!!(16&r),d=c?32*yu(l):0,u=c?2*yu(l):0;e.skip(8*d),e.skip(8*u);let h=Hd.EMPTY;s>0&&(h=a?e.loadPaddedBits(8*s):e.loadBits(8*s));let f=[];for(let r=0;r=0;e--){if(n[e].result)throw Error("Impossible");let t=[];for(let r of n[e].refs){if(!n[r].result)throw Error("Invalid BOC file");t.push(n[r].result)}n[e].result=new ku({bits:n[e].bits,refs:t,exotic:n[e].exotic})}let i=[];for(let e=0;e{if(this.isExotic&&!e)throw new Error("Exotic cells cannot be parsed");return new eu(new ru(this.bits),this.refs)},this.hash=(e=3)=>this._hashes[Math.min(this._hashes.length-1,e)],this.depth=(e=3)=>this._depths[Math.min(this._depths.length-1,e)],this.level=()=>this.mask.level,this.equals=e=>this.hash().equals(e.hash()),this[Cu]=()=>this.toString();let t=Hd.EMPTY;e&&e.bits&&(t=e.bits);let r,n,i,o=[];e&&e.refs&&(o=[...e.refs]);let s=Vd.Ordinary;if(e&&e.exotic){let e=function(e,t){let r=new ru(e).preloadUint(8);if(1===r)return function(e,t){let r=au(e,t),n=[],i=[],o=new su(r.mask);for(let e=0;e>1);return{type:Vd.MerkleProof,depths:[],hashes:[],mask:r}}(e,t);if(4===r)return function(e,t){ou(e,t);let r=new su((t[0].level()|t[1].level())>>1);return{type:Vd.MerkleUpdate,depths:[],hashes:[],mask:r}}(e,t);throw Error("Invalid exotic cell type: "+r)}(t,o),a=hu(e.type,t,o);i=a.mask,n=a.depths,r=a.hashes,s=e.type}else{if(o.length>4)throw new Error("Invalid number of references");if(t.length>1023)throw new Error(`Bits overflow: ${t.length} > 1023`);let e=hu(Vd.Ordinary,t,o);i=e.mask,n=e.depths,r=e.hashes,s=Vd.Ordinary}this.type=s,this.bits=t,this.refs=o,this.mask=i,this._depths=n,this._hashes=r,Object.freeze(this),Object.freeze(this.refs),Object.freeze(this.bits),Object.freeze(this.mask),Object.freeze(this._depths),Object.freeze(this._hashes)}get isExotic(){return this.type!==Vd.Ordinary}toBoc(e){return function(e,t){let r=function(e){let t=[e],r=new Map,n=new Set,i=[];for(;t.length>0;){const e=[...t];t=[];for(let i of e){const e=i.hash().toString("hex");if(!r.has(e)){n.add(e),r.set(e,{cell:i,refs:i.refs.map((e=>e.hash().toString("hex")))});for(let e of i.refs)t.push(e)}}}let o=new Set;function s(e){if(!n.has(e))return;if(o.has(e))throw Error("Not a DAG");o.add(e);let t=r.get(e).refs;for(let e=t.length-1;e>=0;e--)s(t[e]);i.push(e),o.delete(e),n.delete(e)}for(;n.size>0;)s(Array.from(n)[0]);let a=new Map;for(let e=0;e=0;e--){let t=i[e];const n=r.get(t);l.push({cell:n.cell,refs:n.refs.map((e=>a.get(e)))})}return l}(e),n=r.length,i=t.idx,o=t.crc32,s=Math.max(Math.ceil(fu(n,"uint")/8),1),a=0,l=[];for(let e of r)a+=wu(e.cell,s),l.push(a);let c=Math.max(Math.ceil(fu(a,"uint")/8),1),d=8*(6+3*s+c+1*s+(i?n*c:0)+a+(o?4:0)),u=new Zd(d);if(u.writeUint(3052313714,32),u.writeBit(i),u.writeBit(o),u.writeBit(!1),u.writeUint(0,2),u.writeUint(s,3),u.writeUint(c,8),u.writeUint(n,8*s),u.writeUint(1,8*s),u.writeUint(0,8*s),u.writeUint(a,8*c),u.writeUint(0,8*s),i)for(let e=0;e=4)throw new Error("Too many references");if(e instanceof ku)this._refs.push(e);else{if(!(e instanceof Au))throw new Error("Invalid argument");this._refs.push(e.endCell())}return this}storeMaybeRef(e){return e?(this.storeBit(1),this.storeRef(e)):this.storeBit(0),this}storeSlice(e){let t=e.clone();for(t.remainingBits>0&&this.storeBits(t.loadBits(t.remainingBits));t.remainingRefs>0;)this.storeRef(t.loadRef());return this}storeMaybeSlice(e){return e?(this.storeBit(1),this.storeSlice(e)):this.storeBit(0),this}storeBuilder(e){return this.storeSlice(e.endCell().beginParse())}storeMaybeBuilder(e){return e?(this.storeBit(1),this.storeBuilder(e)):this.storeBit(0),this}storeWritable(e){return"object"==typeof e?e.writeTo(this):e(this),this}storeMaybeWritable(e){return e?(this.storeBit(1),this.storeWritable(e)):this.storeBit(0),this}store(e){return this.storeWritable(e),this}storeStringTail(e){return Xd(e,this),this}storeMaybeStringTail(e){return null!=e?(this.storeBit(1),Xd(e,this)):this.storeBit(0),this}storeStringRefTail(e){return this.storeRef(xu().storeStringTail(e)),this}storeMaybeStringRefTail(e){return null!=e?(this.storeBit(1),this.storeStringRefTail(e)):this.storeBit(0),this}storeDict(e,t,r){return e?e.store(this,t,r):this.storeBit(0),this}storeDictDirect(e,t,r){return e.storeDirect(this,t,r),this}endCell(e){return new ku({bits:this._bits.build(),refs:this._refs,exotic:e?.exotic})}asCell(){return this.endCell()}asSlice(){return this.endCell().beginParse()}}function Su(e){return xu().storeUint(1,8).storeUint(1,8).storeBuffer(e.hash(0)).storeUint(e.depth(0),16).endCell({exotic:!0})}function Bu(e,t,r,n){const i=t.asCell();let o=0,s=e;if(0==(t.loadBit()?1:0)){o=function(e){let t=0;for(;e.loadBit();)t++;return t}(t);for(let e=0;e0&&t.storeUint(BigInt("0b"+e),e.length)}(e,r):"long"===n?function(e,t,r){r.storeBit(1),r.storeBit(0);let n=Math.ceil(Math.log2(t+1));r.storeUint(e.length,n),e.length>0&&r.storeUint(BigInt("0b"+e),e.length)}(e,t,r):"same"===n&&function(e,t,r,n){n.storeBit(1),n.storeBit(1),n.storeBit(e);let i=Math.ceil(Math.log2(r+1));n.storeUint(t,i)}("1"===e[0],e.length,t,r)}function Ru(e,t,r,n){Ou(e.label,t,n),function(e,t,r,n){if("leaf"===e.type&&r(e.value,n),"fork"===e.type){const i=xu(),o=xu();Ru(e.left,t-1,r,i),Ru(e.right,t-1,r,o),n.storeRef(i),n.storeRef(o)}}(e.node,t-e.label.length,r,n)}function ju(e,t,r,n){const i=function(e,t){let r=new Map;for(let n of Array.from(e.keys())){const i=Mu(n.toString(2),t);r.set(i,e.get(n))}return Tu(r)}(e,t);Ru(i,t,r,n)}var Lu=r(8287).hp;function zu(e){if("number"==typeof e){if(!Number.isSafeInteger(e))throw Error("Invalid key type: not a safe integer: "+e);return"n:"+e.toString(10)}if("bigint"==typeof e)return"b:"+e.toString(10);if(Nd.isAddress(e))return"a:"+e.toString();if(Lu.isBuffer(e))return"f:"+e.toString("hex");if(Hd.isBitString(e))return"B:"+e.toString();throw Error("Invalid key type")}function Nu(e){let t=e.slice(0,2),r=e.slice(2);if("n:"===t)return parseInt(r,10);if("b:"===t)return BigInt(r);if("a:"===t)return Nd.parse(r);if("f:"===t)return Lu.from(r,"hex");if("B:"===t){const e="_"==r.slice(-1);if(e||r.length%2!=0){let t=e?r.length-1:r.length;const n=r.substr(0,t)+"0";return!e&&1&t?new Hd(Lu.from(n,"hex"),0,t<<2):function(e){let t=0;for(let r=e.length-1;r>=0;r--)if(0!==e[r]){const n=e[r];let i=n&-n;1&i||(i=Math.log2(i)+1),r>0&&(t=r<<3),t+=8-i;break}return new Hd(e,0,t)}(Lu.from(n,"hex"))}return new Hd(Lu.from(r,"hex"),0,r.length<<2)}throw Error("Invalid key type: "+t)}var Du=r(8287).hp;class $u{static empty(e,t){return e&&t?new $u(new Map,e,t):new $u(new Map,null,null)}static load(e,t,r){let n;if(r instanceof ku){if(r.isExotic)return $u.empty(e,t);n=r.beginParse()}else n=r;let i=n.loadMaybeRef();return i&&!i.isExotic?$u.loadDirect(e,t,i.beginParse()):$u.empty(e,t)}static loadDirect(e,t,r){if(!r)return $u.empty(e,t);let n;n=r instanceof ku?r.beginParse():r;let i=Pu(n,e.bits,t.parse),o=new Map;for(let[t,r]of i)o.set(zu(e.parse(t)),r);return new $u(o,e,t)}constructor(e,t,r){this._key=t,this._value=r,this._map=e}get size(){return this._map.size}get(e){return this._map.get(zu(e))}has(e){return this._map.has(zu(e))}set(e,t){return this._map.set(zu(e),t),this}delete(e){const t=zu(e);return this._map.delete(t)}clear(){this._map.clear()}*[Symbol.iterator](){for(const[e,t]of this._map){const r=Nu(e);yield[r,t]}}keys(){return Array.from(this._map.keys()).map((e=>Nu(e)))}values(){return Array.from(this._map.values())}store(e,t,r){if(0===this._map.size)e.storeBit(0);else{let n=this._key;null!=t&&(n=t);let i=this._value;if(null!=r&&(i=r),!n)throw Error("Key serializer is not defined");if(!i)throw Error("Value serializer is not defined");let o=new Map;for(const[e,t]of this._map)o.set(n.serialize(Nu(e)),t);e.storeBit(1);let s=xu();ju(o,n.bits,i.serialize,s),e.storeRef(s.endCell())}}storeDirect(e,t,r){if(0===this._map.size)throw Error("Cannot store empty dictionary directly");let n=this._key;null!=t&&(n=t);let i=this._value;if(null!=r&&(i=r),!n)throw Error("Key serializer is not defined");if(!i)throw Error("Value serializer is not defined");let o=new Map;for(const[e,t]of this._map)o.set(n.serialize(Nu(e)),t);ju(o,n.bits,i.serialize,e)}generateMerkleProof(e){return Eu(this,e,this._key)}generateMerkleUpdate(e,t){return function(e,t,r,n){const i=Eu(e,t,r).refs[0];return e.set(t,n),o=i,s=Eu(e,t,r).refs[0],xu().storeUint(4,8).storeBuffer(o.hash(0)).storeBuffer(s.hash(0)).storeUint(o.depth(0),16).storeUint(s.depth(0),16).storeRef(o).storeRef(s).endCell({exotic:!0});var o,s}(this,e,this._key,t)}}$u.Keys={Address:()=>({bits:267,serialize:e=>{if(!Nd.isAddress(e))throw Error("Key is not an address");return xu().storeAddress(e).endCell().beginParse().preloadUintBig(267)},parse:e=>xu().storeUint(e,267).endCell().beginParse().loadAddress()}),BigInt:e=>function(e){return{bits:e,serialize:t=>{if("bigint"!=typeof t)throw Error("Key is not a bigint");return xu().storeInt(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadIntBig(e)}}(e),Int:e=>function(e){return{bits:e,serialize:t=>{if("number"!=typeof t)throw Error("Key is not a number");if(!Number.isSafeInteger(t))throw Error("Key is not a safe integer: "+t);return xu().storeInt(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadInt(e)}}(e),BigUint:e=>function(e){return{bits:e,serialize:t=>{if("bigint"!=typeof t)throw Error("Key is not a bigint");if(t<0)throw Error("Key is negative: "+t);return xu().storeUint(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadUintBig(e)}}(e),Uint:e=>function(e){return{bits:e,serialize:t=>{if("number"!=typeof t)throw Error("Key is not a number");if(!Number.isSafeInteger(t))throw Error("Key is not a safe integer: "+t);if(t<0)throw Error("Key is negative: "+t);return xu().storeUint(t,e).endCell().beginParse().loadUintBig(e)},parse:t=>Number(xu().storeUint(t,e).endCell().beginParse().loadUint(e))}}(e),Buffer:e=>function(e){return{bits:8*e,serialize:t=>{if(!Du.isBuffer(t))throw Error("Key is not a buffer");return xu().storeBuffer(t).endCell().beginParse().loadUintBig(8*e)},parse:t=>xu().storeUint(t,8*e).endCell().beginParse().loadBuffer(e)}}(e),BitString:e=>function(e){return{bits:e,serialize:t=>{if(!Hd.isBitString(t))throw Error("Key is not a BitString");return xu().storeBits(t).endCell().beginParse().loadUintBig(e)},parse:t=>xu().storeUint(t,e).endCell().beginParse().loadBits(e)}}(e)},$u.Values={BigInt:e=>function(e){return{serialize:(t,r)=>{r.storeInt(t,e)},parse:t=>t.loadIntBig(e)}}(e),Int:e=>function(e){return{serialize:(t,r)=>{r.storeInt(t,e)},parse:t=>t.loadInt(e)}}(e),BigVarInt:e=>function(e){return{serialize:(t,r)=>{r.storeVarInt(t,e)},parse:t=>t.loadVarIntBig(e)}}(e),BigUint:e=>function(e){return{serialize:(t,r)=>{r.storeUint(t,e)},parse:t=>t.loadUintBig(e)}}(e),Uint:e=>function(e){return{serialize:(t,r)=>{r.storeUint(t,e)},parse:t=>t.loadUint(e)}}(e),BigVarUint:e=>function(e){return{serialize:(t,r)=>{r.storeVarUint(t,e)},parse:t=>t.loadVarUintBig(e)}}(e),Bool:()=>({serialize:(e,t)=>{t.storeBit(e)},parse:e=>e.loadBit()}),Address:()=>({serialize:(e,t)=>{t.storeAddress(e)},parse:e=>e.loadAddress()}),Cell:()=>({serialize:(e,t)=>{t.storeRef(e)},parse:e=>e.loadRef()}),Buffer:e=>{return t=e,{serialize:(e,r)=>{if(e.length!==t)throw Error("Invalid buffer size");r.storeBuffer(e)},parse:e=>e.loadBuffer(t)};var t},BitString:e=>function(e){return{serialize:(t,r)=>{if(t.length!==e)throw Error("Invalid BitString size");r.storeBits(t)},parse:t=>t.loadBits(e)}}(e),Dictionary:(e,t)=>function(e,t){return{serialize:(e,t)=>{e.store(t)},parse:r=>$u.load(e,t,r)}}(e,t)};const Fu=e=>document.querySelector(e),Ku=(e,t)=>{e.style.display=t?"flex":"none"},Hu='
Это вы
',Vu=(e,t)=>{let r=e;void 0!==t&&(r+="/"+t),window.history.state!==r&&window.history.pushState(r,"TON Multisig - "+r,"#"+r)},qu=(navigator.language,window.location.href.indexOf("testnet=true")>-1);qu&&(Fu(".testnet-badge").style.display="block",document.body.classList.add("testnet-padding"));const Zu=e=>e.toString({bounceable:!0,testOnly:qu});let Wu="startScreen";const Gu=e=>{const t=["startScreen","importScreen","multisigScreen","newOrderScreen","orderScreen","newMultisigScreen","loadingScreen"];Wu=e;for(const r of t)Ku(Fu("#"+r),r===e);switch(Wu){case"startScreen":nh(),dh(),""!==window.history.state&&window.history.pushState("","Мультикошелек","#");break;case"importScreen":Fu("#import_input").value="";break;case"newOrderScreen":Bh();break;case"newMultisigScreen":Nh()}};let Yu;const Qu=new class{constructor(e){if(Ie(this,"walletInfoStorage",new Fr),Ie(this,"preferredWalletStorage",new Kr),Ie(this,"walletInfo",null),Ie(this,"systemThemeChangeUnsubscribe",null),Ie(this,"actionsConfiguration"),Ie(this,"walletsList"),Ie(this,"connectRequestParametersCallback"),Ie(this,"connector"),Ie(this,"modal"),Ie(this,"transactionModal"),Ie(this,"connectionRestored",Promise.resolve(!1)),e&&"connector"in e&&e.connector)this.connector=e.connector;else{if(!(e&&"manifestUrl"in e&&e.manifestUrl))throw new Mr("You have to specify a `manifestUrl` or a `connector` in the options.");this.connector=new oe({manifestUrl:e.manifestUrl})}this.modal=new Fc({connector:this.connector,setConnectRequestParametersCallback:e=>{this.connectRequestParametersCallback=e}}),this.transactionModal=new Kc({connector:this.connector}),this.walletsList=this.getWallets(),this.walletsList.then((e=>{return jr((t=e.map((e=>e.imageUrl)),[...new Set(t)]));var t}));const t=this.normalizeWidgetRoot(null==e?void 0:e.widgetRootId);this.subscribeToWalletChange(),!1!==(null==e?void 0:e.restoreConnection)&&(this.connectionRestored=new Promise((e=>Pe(this,null,(function*(){yield this.connector.restoreConnection(),this.connector.connected||this.walletInfoStorage.removeWalletInfo(),e(this.connector.connected)}))))),this.uiOptions=_n(e,{uiPreferences:{theme:"SYSTEM"}});const r=this.preferredWalletStorage.getPreferredWalletAppName();Ya({connector:this.connector,preferredWalletAppName:r}),((e,t)=>{(function(e,t,r,n={}){let i;qe((n=>{i=n,t===document?e():qt(t,e(),t.firstChild?null:void 0,r)}),n.owner)})((()=>kt(Nc,{tonConnectUI:t})),document.getElementById(e))})(t,this)}static getWallets(){return oe.getWallets()}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?Be(Be({},this.connector.wallet),this.walletInfo):null}set uiOptions(e){var t,r,n,i,o,s,a;this.checkButtonRootExist(e.buttonRootId),this.actionsConfiguration=e.actionsConfiguration,(null==(t=e.uiPreferences)?void 0:t.theme)?"SYSTEM"!==(null==(r=e.uiPreferences)?void 0:r.theme)?(null==(n=this.systemThemeChangeUnsubscribe)||n.call(this),Bn(e.uiPreferences.theme,e.uiPreferences.colorsSet)):(Bn(window.matchMedia&&window.matchMedia("(prefers-color-scheme: light)").matches?ir.LIGHT:ir.DARK,e.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=function(e){const t=t=>e(t.matches?ir.DARK:ir.LIGHT);return window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t),()=>window.matchMedia("(prefers-color-scheme: dark)").removeEventListener("change",t)}(Bn))):(null==(i=e.uiPreferences)?void 0:i.colorsSet)&&(s=e.uiPreferences.colorsSet,Sn[ir.DARK]=_n(s[ir.DARK],Sn[ir.DARK]),Sn[ir.LIGHT]=_n(s[ir.LIGHT],Sn[ir.LIGHT]),xn((e=>({colors:_n(Sn[e.theme],An[e.theme])})))),(null==(o=e.uiPreferences)?void 0:o.borderRadius)&&(a=e.uiPreferences.borderRadius,xn({borderRadius:a})),Ya((t=>{var r,n;const i=_n(Be(Be(Be(Be({},e.language&&{language:e.language}),!!(null==(r=e.actionsConfiguration)?void 0:r.returnStrategy)&&{returnStrategy:e.actionsConfiguration.returnStrategy}),!!(null==(n=e.actionsConfiguration)?void 0:n.twaReturnUrl)&&{twaReturnUrl:e.actionsConfiguration.twaReturnUrl}),!!e.walletsListConfiguration&&{walletsListConfiguration:e.walletsListConfiguration}),cn(t));return void 0!==e.buttonRootId&&(i.buttonRootId=e.buttonRootId),void 0!==e.enableAndroidBackHandler&&(i.enableAndroidBackHandler=e.enableAndroidBackHandler),i}))}setConnectRequestParameters(e){var t;Ya({connectRequestParameters:e}),"ready"!==(null==e?void 0:e.state)&&e||null==(t=this.connectRequestParametersCallback)||t.call(this,null==e?void 0:e.value)}getWallets(){return Pe(this,null,(function*(){return this.connector.getWallets()}))}onStatusChange(e,t){return this.connector.onStatusChange((t=>Pe(this,null,(function*(){if(t){const r=yield this.getSelectedWalletInfo(t);e(Be(Be({},t),r||this.walletInfoStorage.getWalletInfo()))}else e(t)}))),t)}openModal(){return Pe(this,null,(function*(){return this.modal.open()}))}closeModal(){this.modal.close()}onModalStateChange(e){return this.modal.onStateChange(e)}get modalState(){return this.modal.state}connectWallet(){return Pe(this,null,(function*(){const e=(yield this.getWallets()).find(ee);return e?yield this.connectEmbeddedWallet(e):yield this.connectExternalWallet()}))}disconnect(){return setTimeout((()=>Xr(null))),Qr(null),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect()}sendTransaction(e,t){return Pe(this,null,(function*(){if(!this.connected)throw new Mr("Connect wallet to send a transaction.");On()&&Rn();const{notifications:r,modals:n,returnStrategy:i,twaReturnUrl:o,skipRedirectToWallet:s}=this.getModalsAndNotificationsConfiguration(t);$c({name:"confirm-transaction",showNotification:r.includes("before"),openModal:n.includes("before")});const a=()=>{const e="ios"===Nr().os,t="ios"===s&&e||"always"===s;this.walletInfo&&"universalLink"in this.walletInfo&&"universal-link"===this.walletInfo.openMethod&&!t&&(L(this.walletInfo.universalLink)?El(this.walletInfo.universalLink,{returnStrategy:i,twaReturnUrl:o||Ga.twaReturnUrl,forceRedirect:!1}):Tr(Bl(this.walletInfo.universalLink,i)))},l=new AbortController,c=this.onTransactionModalStateChange((e=>{(null==e?void 0:e.openModal)||(c(),e||l.abort())}));try{const t=yield this.waitForSendTransaction({transaction:e,abortSignal:l.signal},a);return $c({name:"transaction-sent",showNotification:r.includes("success"),openModal:n.includes("success")}),t}catch(e){throw $c({name:"transaction-canceled",showNotification:r.includes("error"),openModal:n.includes("error")}),e instanceof m?e:(console.error(e),new Mr("Unhandled error:"+e))}finally{c()}}))}connectEmbeddedWallet(e){return Pe(this,null,(function*(){const t=t=>{Qr(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},t)},r=Ga.connectRequestParameters;return"loading"===(null==r?void 0:r.state)?this.connectRequestParametersCallback=t:t(null==r?void 0:r.value),yield this.waitForWalletConnection({ignoreErrors:!1})}))}connectExternalWallet(){return Pe(this,null,(function*(){const e=new AbortController;Dc();const t=this.onModalStateChange((r=>{const{status:n,closeReason:i}=r;"opened"!==n&&(t(),"action-cancelled"===i&&e.abort())}));return yield this.waitForWalletConnection({ignoreErrors:!0,abortSignal:e.signal})}))}waitForWalletConnection(e){return Pe(this,null,(function*(){return new Promise(((t,r)=>{const{ignoreErrors:n=!1,abortSignal:i=null}=e;if(i&&i.aborted)return r(new Mr("Wallet was not connected"));const o=e=>Pe(this,null,(function*(){if(e)s(),t(e);else{if(n)return;s(),r(new Mr("Wallet was not connected"))}})),s=this.onStatusChange((e=>o(e)),(e=>(e=>{n||(s(),r(e))})(e)));i&&i.addEventListener("abort",(()=>{s(),r(new Mr("Wallet was not connected"))}))}))}))}waitForSendTransaction(e,t){return Pe(this,null,(function*(){return new Promise(((r,n)=>{const{transaction:i,abortSignal:o}=e;if(o.aborted)return n(new Mr("Transaction was not sent"));const s=e=>Pe(this,null,(function*(){r(e)}));this.connector.sendTransaction(i,t).then((e=>s(e))).catch((e=>(e=>{n(e)})(e))),o.addEventListener("abort",(()=>{n(new Mr("Transaction was not sent"))}))}))}))}onTransactionModalStateChange(e){return this.transactionModal.onStateChange(e)}subscribeToWalletChange(){this.connector.onStatusChange((e=>Pe(this,null,(function*(){var t;e?(yield this.updateWalletInfo(e),this.setPreferredWalletAppName((null==(t=this.walletInfo)?void 0:t.appName)||e.device.appName)):this.walletInfoStorage.removeWalletInfo()}))))}setPreferredWalletAppName(e){this.preferredWalletStorage.setPreferredWalletAppName(e),Ya({preferredWalletAppName:e})}getSelectedWalletInfo(e){return Pe(this,null,(function*(){let t,r=Gr();if(!r)return null;if("name"in r)t=r;else{const n=Ja(yield this.walletsList,Ga.walletsListConfiguration).find((t=>rl(t,e.device.appName)));if(!n)throw new Mr(`Cannot find WalletInfo for the '${e.device.appName}' wallet`);t=Be(Be({},n),r)}return t}))}updateWalletInfo(e){return Pe(this,null,(function*(){const t=yield this.getSelectedWalletInfo(e);if(t)return this.walletInfo=t,void this.walletInfoStorage.setWalletInfo(t);const r=this.walletInfoStorage.getWalletInfo();this.walletInfo=r||(yield this.walletsList).find((t=>rl(t,e.device.appName)))||null}))}normalizeWidgetRoot(e){if(!e||!document.getElementById(e)){e="tc-widget-root";const t=document.createElement("div");t.id=e,document.body.appendChild(t)}return e}checkButtonRootExist(e){if(null!=e&&!document.getElementById(e))throw new Mr(`${e} element not found in the document.`)}getModalsAndNotificationsConfiguration(e){var t,r,n,i,o,s;const a=["before","success","error"];let l=a;(null==(t=this.actionsConfiguration)?void 0:t.notifications)&&"all"!==(null==(r=this.actionsConfiguration)?void 0:r.notifications)&&(l=this.actionsConfiguration.notifications),(null==e?void 0:e.notifications)&&(l="all"===e.notifications?a:e.notifications);let c=["before"];(null==(n=this.actionsConfiguration)?void 0:n.modals)&&(c="all"===this.actionsConfiguration.modals?a:this.actionsConfiguration.modals),(null==e?void 0:e.modals)&&(c="all"===e.modals?a:e.modals);const d=(null==e?void 0:e.returnStrategy)||(null==(i=this.actionsConfiguration)?void 0:i.returnStrategy)||"back",u=(null==e?void 0:e.twaReturnUrl)||(null==(o=this.actionsConfiguration)?void 0:o.twaReturnUrl);let h=(null==e?void 0:e.skipRedirectToWallet)||(null==(s=this.actionsConfiguration)?void 0:s.skipRedirectToWallet)||"ios";return On()&&(h="never"),{notifications:l,modals:c,returnStrategy:d,twaReturnUrl:u,skipRedirectToWallet:h}}}({manifestUrl:"https://multisig.ton.org/tonconnect-manifest.json",buttonRootId:"tonConnectButton"});Qu.uiOptions={uiPreferences:{theme:ir.LIGHT}},Qu.onStatusChange((e=>{null===e?Yu=null:e.account&&(Yu=a.Address.parseRaw(e.account.address)),eh&&th&&ih(),ah&&lh&&hh()})),Fu("#createMultisigButton").addEventListener("click",(()=>{zh("create")})),Fu("#importMultisigButton").addEventListener("click",(()=>{Gu("importScreen")})),Fu("#import_okButton").addEventListener("click",(()=>{const e=Fu("#import_input").value,t=Gc(e,qu);t?alert(t):sh(e)})),Fu("#import_backButton").addEventListener("click",(()=>{Gu("startScreen")}));const Ju=a.Cell.fromBase64("te6cckECEgEABJUAART/APSkE/S88sgLAQIBYgIDAsrQM9DTAwFxsJJfA+D6QDAi10nAAJJfA+AC0x8BIMAAkl8E4AHTPwHtRNDT/wEB0wcBAdTTBwEB9ATSAAEB0SiCEPcYUQ+64w8FREPIUAYBy/9QBAHLBxLMAQHLB/QAAQHKAMntVAQFAgEgDA0BnjgG0/8BKLOOEiCE/7qSMCSWUwW68uPw4gWkBd4B0gABAdMHAQHTLwEB1NEjkSaRKuJSMHj0Dm+h8uPvHscF8uPvIPgjvvLgbyD4I6FUbXAGApo2OCaCEHUJf126jroGghCjLFm/uo6p+CgYxwXy4GUD1NEQNBA2RlD4AH+OjSF49HxvpSCRMuMNAbPmWxA1UDSSNDbiUFQT4w1AFVAzBAoJAdT4BwODDPlBMAODCPlBMPgHUAahgSf4AaBw+DaBEgZw+DaggSvscPg2oIEdmHD4NqAipgYioIEFOSagJ6Bw+DgjpIECmCegcPg4oAOmBliggQbgUAWgUAWgQwNw+DdZoAGgHL7y4GT4KFADBwK4AXACyFjPFgEBy//JiCLIywH0APQAywDJcCH5AHTIywISygfL/8nQyIIQnHP7olgKAssfyz8mAcsHUlDMUAsByy8bzCoBygAKlRkBywcIkTDiECRwQImAGIBQ2zwRCACSjkXIWAHLBVAFzxZQA/oCVHEjI+1E7UXtR59byFADzxfJE3dQA8trzMztZ+1l7WR0f+0RmHYBy2vMAc8X7UHt8QHy/8kB+wDbBgLiNgTT/wEB0y8BAdMHAQHT/wEB1NH4KFAFAXACyFjPFgEBy//JiCLIywH0APQAywDJcAH5AHTIywISygfL/8nQG8cF8uBlJvkAGrpRk74ZsPLgZgf4I77y4G9EFFBW+AB/jo0hePR8b6UgkTLjDQGz5lsRCgH6AtdM0NMfASCCEPE4Hlu6jmqCEB0M+9O6jl5sRNMHAQHUIX9wjhdREnj0fG+lMiGZUwK68uBnAqQC3gGzEuZsISDCAPLgbiPCAPLgbVMwu/LgbQH0BCF/cI4XURJ49HxvpTIhmVMCuvLgZwKkAt4BsxLmbCEw0VUjkTDi4w0LABAw0wfUAvsA0QFDv3T/aiaGn/gIDpg4CA6mmDgID6AmkAAIDoiBqvgoD8EdDA4CAWYPEADC+AcDgwz5QTADgwj5QTD4B1AGoYEn+AGgcPg2gRIGcPg2oIEr7HD4NqCBHZhw+DagIqYGIqCBBTkmoCegcPg4I6SBApgnoHD4OKADpgZYoIEG4FAFoFAFoEMDcPg3WaABoADxsMr7UTQ0/8BAdMHAQHU0wcBAfQE0gABAdEjf3COF1ESePR8b6UyIZlTArry4GcCpALeAbMS5mwhUjC68uBsIX9wjhdREnj0fG+lMiGZUwK68uBnAqQC3gGzEuZsITAiwgDy4G4kwgDy4G1SQ7vy4G0BkjN/kQPiA4AFZsMn+CgBAXACyFjPFgEBy//JiCLIywH0APQAywDJcAH5AHTIywISygfL/8nQgEQhCAmMFqAYchWwszwXcsN9YFccUdYcFZ8q18EnjQLz1klHzYNH/nQ=="),Xu=a.Cell.fromBase64("te6cckEBAQEAIwAIQgJjBagGHIVsLM8F3LDfWBXHFHWHBWfKtfBJ40C89ZJR80AoJo0=");let eh,th,rh=-1;const nh=()=>{eh=void 0,th=void 0,clearTimeout(rh)},ih=()=>{const{tonBalance:e,threshold:t,signers:r,proposers:n,allowArbitraryOrderSeqno:i,nextOderSeqno:o,lastOrders:s}=th;Fu("#multisig_tonBalance").innerText=(0,a.fromNano)(e)+" TON",Fu("#multisig_threshold").innerText=t+"/"+r.length,Fu("#multisig_orderId").innerText=i?"Произвольная":o.toString();let l="";for(let e=0;e#${e+1} — ${Xc(t)}${td(t.address,Yu)?Hu:""}`}if(Fu("#multisig_signersList").innerHTML=l,n.length>0){let e="";for(let t=0;t#${t+1} — ${Xc(r)}${td(r.address,Yu)?Hu:""}`}Fu("#multisig_proposersList").innerHTML=e}else Fu("#multisig_proposersList").innerHTML="No proposers";const c=e=>{if(e.errorMessage)return e.errorMessage.startsWith("Контракт не активен")?"":e.errorMessage.startsWith("Ошибка")?`
Ошибка в заявке #${e.order.id} — Execution error
`:`
Недействительная заявка #${e.order.id} — ${e.errorMessage}
`;{const t=!!e.orderInfo&&(new Date).getTime()>e.orderInfo.expiresAt.getTime(),r=t?"Истекший срок заявки ":(e=>{switch(e.type){case"new":return"Новая заяввка";case"execute":return"Execute order";case"pending":return"Ожидаемая заявка";case"executed":return"Выполненная заявка"}throw new Error("unknown order type "+e.type)})(e);let n=`${r} #${e.order.id}`;if("pending"!==e.type||t||(n+=` — ${e.orderInfo.approvalsNum}/${e.orderInfo.threshold}`),"pending"===e.type&&Yu){const t=e.orderInfo.signers.findIndex((e=>e.address.equals(Yu)));if(t>-1){const r=1<${n}`}};let d="",u=!1,h=!1;for(const e of s)"executed"==e.type?h||(d+='
Старые заявки:
',h=!0):"pending"===e.type&&(u||(d+='
Ожидаемые заявки:
',u=!0)),d+=c(e);Fu("#mainScreen_ordersList").innerHTML=d,(".multisig_lastOrder",document.querySelectorAll(".multisig_lastOrder")).forEach((e=>{e.addEventListener("click",(e=>{const t=e.currentTarget.attributes,r=t.getNamedItem("order-address").value,n=BigInt(t.getNamedItem("order-id").value);ph(n,r)}))}))},oh=async(e,t)=>{try{const r=await(async(e,t,r,n,i,o)=>{const s=await qc("account",{address:ed(e)},n);nd("active"===s.status,"Contract not active. If you have just created a multisig it should appear within ~30 seconds."),nd(a.Cell.fromBase64(s.code).equals(t),"The contract code DOES NOT match the multisig code from this repository");const l=s.balance,c=function(e){const t=e.beginParse(),r=t.loadUintBig(256),n=t.loadUint(8),i=cd(t.loadRef()),o=t.loadUint(8),s=cd(t.loadMaybeRef()),a=t.loadBit();return dd(t),{nextOderSeqno:r,threshold:n,signers:i,signersCount:o,proposers:s,allowArbitraryOrderSeqno:a}}(a.Cell.fromBase64(s.data));c.allowArbitraryOrderSeqno&&nd(c.nextOderSeqno===BigInt(0),"invalid nextOrderSeqno for allowArbitraryOrderSeqno");const d=c.signers,u=c.proposers;nd(d.length===c.signersCount,"invalid signersCount"),nd(c.threshold>0,"threshold <= 0"),nd(c.threshold<=c.signersCount,"invalid threshold");const h=[];for(const e of d)h.push(await Qc(e,n));const f=[];for(const e of u)f.push(await Qc(e,n));const p=ud.createFromAddress(e.address),g=new Wc(e.address,n);if(o){const e=await p.getMultisigData(g);c.allowArbitraryOrderSeqno?nd(e.nextOrderSeqno===BigInt(-1),"nextOderSeqno doesn't match"):nd(e.nextOrderSeqno===c.nextOderSeqno,"nextOderSeqno doesn't match"),nd(e.threshold===BigInt(c.threshold),"threshold doesn't match"),nd(rd(e.signers,c.signers),"invalid signers"),nd(rd(e.proposers,c.proposers),"invalid proposers")}const m=ud.createFromConfig({threshold:c.threshold,signers:c.signers,proposers:c.proposers,allowArbitrarySeqno:c.allowArbitraryOrderSeqno},t).address.equals(e.address),y={address:e,multisigContract:p,provider:g,signers:h,proposers:f,threshold:c.threshold,allowArbitraryOrderSeqno:c.allowArbitraryOrderSeqno,nextOderSeqno:c.nextOderSeqno,tonBalance:l,lastOrders:[],stateInitMatches:m};let b=[];if("none"!==i){const t=await qc("transactions",{account:ed(e),limit:256},n);for(const i of t.transactions){if(!i.in_msg.message_content)continue;if(!i.in_msg.message_content.body)continue;const t=a.Cell.fromBase64(i.in_msg.message_content.body).beginParse();if(t.remainingBits<32)continue;const o=t.loadUint(32);if(1963556701===o)try{t.loadUintBig(64);const o=t.loadUintBig(256),s=a.Address.parse(i.in_msg.source),l=fd.createFromConfig({multisig:e.address,orderSeqno:o},r);if(!s.equals(l.address))throw new Error("fake order");b.push({utime:i.now,transactionHash:i.hash,type:"execute",order:{address:{address:s,isBounceable:!0,isTestOnly:n},id:o}})}catch(e){b.push({utime:i.now,transactionHash:i.hash,type:"execute",errorMessage:e.message})}else if(4145565967===o)try{if(1!==i.out_msgs.length)throw new Error("invalid out messages");const o=i.out_msgs[0],{orderAddress:s,orderId:l}=Sd(o),c=fd.createFromConfig({multisig:e.address,orderSeqno:l},r);if(!s.equals(c.address))throw new Error("fake order");const d=t.loadUint(64),u=(t.loadUint(256),t.loadUint(1)),h=t.loadUint(8),f=t.loadUint(48),p=t.loadRef().beginParse().loadDictDirect(a.Dictionary.Keys.Uint(8),a.Dictionary.Values.Cell());dd(t),console.log("IN",{queryId:d,orderId:l,orderAddress:s.toString(),isSigner:u,index:h,expiredAt:f,order:p}),b.push({utime:i.now,transactionHash:i.hash,type:"new",order:{address:{address:s,isBounceable:!0,isTestOnly:n},id:l}})}catch(e){console.log(e),b.push({utime:i.now,transactionHash:i.hash,type:"new",errorMessage:"Invalid new order: "+e.message})}}if("aggregate"===i){const e={};for(let t of b){if(t.errorMessage)continue;const r=t.order.id.toString();e[r]?"executed"!==e[r].type&&"execute"===t.type&&(e[r].utime=t.utime,e[r].type="executed"):e[r]={utime:t.utime,transactionHash:t.transactionHash,type:"new"===t.type?"pending":"executed",order:t.order}}b=Object.values(e);const t=e=>{if(e.transaction&&!1===e.transaction.success&&"excess"!==e.transaction.in_msg.decoded_op_name)return!0;if(e.children)for(let r of e.children)if(t(r))return!0;return!1};for(const e of b)if("executed"===e.type){const r=xd.from(e.transactionHash,"base64").toString("hex"),i=await Zc("traces/"+r,{},n);t(i)&&(e.errorMessage="Ошибка")}for(const e of b)if("pending"===e.type)try{const t=await kd(e.order.address,r,y,n,!1);e.orderInfo=t,(new Date).getTime()>t.expiresAt.getTime()&&(e.type="executed")}catch(t){e.type="executed",e.errorMessage=t.message}b=b.sort(((e,t)=>e.type===t.type?t.utime-e.utime:"pending"===e.type?-1:1))}}return y.lastOrders=b,y})(a.Address.parseFriendly(e),Ju,Xu,qu,"aggregate",t);if(eh!==e)return;th=r,ih(),Ku(Fu("#multisig_content"),!0),Ku(Fu("#multisig_error"),!1)}catch(r){if(console.error(r),eh!==e)return;!t&&r?.message?.startsWith("Timeout")||(Ku(Fu("#multisig_content"),!1),Ku(Fu("#multisig_error"),!0),Fu("#multisig_error").innerText=r.message)}clearTimeout(rh),rh=setTimeout((()=>oh(e,!1)),5e3),t&&Gu("multisigScreen")},sh=async(e,t)=>{Gu("loadingScreen"),nh(),eh=e,localStorage.setItem("multisigAddress",e),Vu(e,t);const r=a.Address.parseFriendly(eh);r.isBounceable=!0,r.isTestOnly=qu,Fu("#mulisig_address").innerHTML=Xc(r),await oh(e,!0)};let ah,lh;Fu("#multisig_logoutButton").addEventListener("click",(()=>{localStorage.removeItem("multisigAddress"),nh(),Gu("startScreen")})),Fu("#multisig_createNewOrderButton").addEventListener("click",(()=>{Gu("newOrderScreen")})),Fu("#multisig_updateButton").addEventListener("click",(()=>{zh("update")}));let ch=-1;const dh=()=>{ah=void 0,lh=void 0,clearTimeout(ch)},uh=(e,t)=>{Fu("#order_approveButton").innerText=t?e?"Executing..":"Execute":e?"Approving..":"Approve",Fu("#order_approveButton").disabled=e},hh=()=>{const{tonBalance:e,actions:t,isExecuted:r,approvalsNum:n,approvalsMask:i,threshold:o,signers:s,expiresAt:l}=lh,c=(new Date).getTime()>l.getTime();Fu("#order_tonBalance").innerText=(0,a.fromNano)(e)+" TON",Fu("#order_executed").innerText=r?"Да":"Нет",Fu("#order_approvals").innerText=n+"/"+o,Fu("#order_expiresAt").innerText=(c?"❌ ИСТЕКЛО - ":"")+l.toString();let d=!1,u="";for(let e=0;e#${e+1} — ${r} — ${n?"✅":"❌"}${td(t.address,Yu)?Hu:""}`}Fu("#order_signersList").innerHTML=u;let h="";for(const e of t)h+=e;0===t.length?Fu("#order_actionsTitle").innerText="Нет заявок":1===t.length?Fu("#order_actionsTitle").innerText="Заявка:":Fu("#order_actionsTitle").innerText=t.length+" действия:",Fu("#order_actions").innerHTML=h;let f=Number(localStorage.getItem(eh+"_"+ah+"_approve"));Date.now()-f>12e4&&!d&&(f=0,localStorage.removeItem(eh+"_"+ah+"_approve")),uh(!!f,n===o-1),Ku(Fu("#order_approveButton"),!r&&!c&&!d),Ku(Fu("#order_approveNote"),!r&&!c&&!d)},fh=async(e,t,r)=>{try{const n=await kd(e,Xu,th,qu,r);if(ah!==t)return;lh=n,hh(),Ku(Fu("#order_content"),!0),Ku(Fu("#order_error"),!1)}catch(e){if(console.error(e),ah!==t)return;!r&&e?.message?.startsWith("Время истекло")||(Ku(Fu("#order_content"),!1),Ku(Fu("#order_error"),!0),Fu("#order_error").innerText=e.message)}clearTimeout(ch),ch=setTimeout((()=>fh(e,t,!1)),5e3),r&&Gu("orderScreen")},ph=async(e,t)=>{if(!th)throw new Error("setOrderId: нет информации о мультикошельке");if(Gu("loadingScreen"),dh(),ah=e,Vu(eh,e),void 0===t){const r=fd.createFromConfig({multisig:a.Address.parseFriendly(eh).address,orderSeqno:e},Xu);t=Zu(r.address)}Fu("#order_id").innerText="#"+ah;const r=a.Address.parseFriendly(t);r.isBounceable=!0,r.isTestOnly=qu,Fu("#order_address").innerHTML=Xc(r),await fh(r,e,!0)};Fu("#order_backButton").addEventListener("click",(()=>{Vu(eh),dh(),Gu("multisigScreen")})),Fu("#order_approveButton").addEventListener("click",(async()=>{if(!eh)throw new Error("approve !currentMultisigAddress");if(!lh)throw new Error("approve !currentOrderInfo");const e=eh,t=lh;if(!Yu)return void alert("Please connect wallet");if(-1==t.signers.findIndex((e=>e.address.equals(Yu))))return void alert("Вы не можете подтверждать");const r=ed(t.address),n=yh.toString(),i=(0,a.beginCell)().storeUint(0,32).storeStringTail("approve").endCell().toBoc().toString("base64");console.log({orderAddressString:r,amount:n});const o={validUntil:Math.floor(Date.now()/1e3)+60,messages:[{address:r,amount:n,payload:i}]};uh(!0,t.approvalsNum===t.threshold-1),localStorage.setItem(e+"_"+t.orderId+"_approve",Date.now().toString());try{await Qu.sendTransaction(o)}catch(r){console.error(r),localStorage.removeItem(e+"_"+t.orderId+"_approve"),eh===e&&ah===t.orderId&&uh(!1,t.approvalsNum===t.threshold-1)}}));const gh=(e,t,r)=>{const n=t=>({error:e+": "+t}),i=e=>({value:e}),o=(e,t)=>{try{const r=function(e,t){const r=function(e){let t=1n;for(let r=0;r2)throw Error("Invalid number");let o=i[0],s=i[1];if(o||(o="0"),s||(s="0"),s.length>t)throw Error("Invalid number");for(;s.length-1?i(t):n("Неправильный статус. Пожалуйста, используйте: "+yd.join(", "))}},mh=(0,a.toNano)("0.2"),yh=(0,a.toNano)("0.1"),bh=(0,a.toNano)("0.05"),wh=async e=>{try{const t=th,r=await Pd(e.jettonMinterAddress,qu,!1);return t.address.address.equals(r.adminAddress)?{value:r}:{error:"Мультикошелек не является администратором этого жетона"}}catch(e){return console.error(e),{error:"Jetton-minter check error"}}},vh=async e=>{try{const t=await th.multisigContract.getOrderAddress(th.provider,e);return"uninit"===(await qc("account",{address:t.toRawString()},qu)).status?{value:!0}:{error:`Заявка ${e} уже существует`}}catch(e){return console.error(e),{error:"Possibly connectivity error"}}},Ch=[{name:"Отправить TON",fields:{amount:{name:"Количество TON",type:"TON"},toAddress:{name:"Адрес получения",type:"Address"}},makeMessage:async e=>({toAddress:e.toAddress,tonAmount:e.amount,body:(0,a.beginCell)().endCell()})},{name:"Отправить жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},toAddress:{name:"На адрес",type:"Address"}},makeMessage:async e=>{const t=e.jettonMinterAddress.address,r=th.address.address,n=Cd.createFromAddress(t),i=new Wc(t,qu);return{toAddress:{address:await n.getWalletAddress(i,r),isBounceable:!0,isTestOnly:qu},tonAmount:yh,body:md.transferMessage(e.amount,e.toAddress.address,r,null,0n,null)}}},{name:"Выпустить жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},toAddress:{name:"На адрес",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.mintMessage(e.toAddress.address,e.amount,e.jettonMinterAddress.address,th.address.address,null,0n,bh)})},{name:"Сменить администратора жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},newAdminAddress:{name:"Новый адрес администратора",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.changeAdminMessage(e.newAdminAddress.address)})},{name:"Запросить адрес администратора",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"}},check:async e=>{try{const t=th,r=await Pd(e.jettonMinterAddress,qu,!0);return r.nextAdminAddress&&t.address.address.equals(r.nextAdminAddress)?{value:r}:{error:"Мультикошелек не является администратором этого жетона"}}catch(e){return console.error(e),{error:"Jetton-minter check error"}}},makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.claimAdminMessage()})},{name:"Пополнить контракт жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество TON",type:"TON"}},makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:e.amount,body:Cd.topUpMessage()})},{name:"Сменить метаданные жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},newMetadataUrl:{name:"Новая URL ссылка с метаданными",type:"URL"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.changeContentMessage({uri:e.newMetadataUrl})})},{name:"Принудительно сжечь жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},fromAddress:{name:"Адрес пользователя",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.forceBurnMessage(e.amount,e.fromAddress.address,th.address.address,bh)})},{name:"Принудительно отправить жетоны",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},amount:{name:"Количество жетонов",type:"Jetton"},fromAddress:{name:"С адреса",type:"Address"},toAddress:{name:"На адрес",type:"Address"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.forceTransferMessage(e.amount,e.toAddress.address,e.fromAddress.address,e.jettonMinterAddress.address,null,0n,null,bh)})},{name:"Сменить состояние контракта жетона",fields:{jettonMinterAddress:{name:"Адрес контракта жетона",type:"Address"},userAddress:{name:"Адрес пользователя",type:"Address"},newStatus:{name:"Новое состояние (Разблокировать, исх., вход., полная блокировка)",type:"Status"}},check:wh,makeMessage:async e=>({toAddress:e.jettonMinterAddress,tonAmount:yh,body:Cd.lockWalletMessage(e.userAddress.address,bd(e.newStatus),bh)})}],_h=Fu("#newOrder_typeInput");_h.innerHTML=(()=>{let e="";for(let t=0;t${Ch[t].name}`;return e})();const kh=e=>{const t=Ch[e];let r="";for(let n in t.fields)if(t.fields.hasOwnProperty(n)){const i=t.fields[n];if(r+=`
${i.name}:
`,"Status"===i.type){r+=`"}else r+=``}Fu("#newOrder_fieldsContainer").innerHTML=r};_h.addEventListener("change",(e=>{kh(_h.selectedIndex)})),kh(0);let xh,Ah="fill";const Sh=()=>{if(!th)return"";let e=-1n;return th.lastOrders.forEach((t=>{t.order.id>e&&(e=t.order.id)})),-1n===e?"":(e+1n).toString()},Bh=()=>{Ph("fill"),xh=void 0,_h.selectedIndex=0,kh(0),Fu("#newOrder_orderId").value=Sh()},Eh=e=>{Fu("#newOrder_createButton").disabled=e,Fu("#newOrder_backButton").disabled=e},Ih=e=>{const t=_h.selectedIndex,r=Ch[t];_h.disabled=e,Fu("#newOrder_orderId").disabled=e;for(let n in r.fields)r.fields.hasOwnProperty(n)&&(Fu(`#newOrder_${t}_${n}`).disabled=e);Eh(e)},Ph=e=>{"fill"==e?(Ih(!1),Fu("#newOrder_createButton").innerHTML="Создать",Fu("#newOrder_backButton").innerHTML="Назад"):(Ih(!0),Fu("#newOrder_createButton").innerHTML="Отправить транзакцию",Fu("#newOrder_backButton").innerHTML="Отменить"),Ah=e};Fu("#newOrder_createButton").addEventListener("click",(async()=>{if(!Yu)return void alert("Please connect wallet");if("confirm"===Ah){if(!xh)throw new Error("");try{await Qu.sendTransaction({validUntil:Math.floor(Date.now()/1e3)+60,messages:[xh.message]}),eh===Zu(xh.multisigAddress)&&ph(xh.orderId)}catch(e){console.error(e)}return}const e=Mh(Fu("#newOrder_orderId"));if(null==e||e<0)return void alert("Invalid Order ID");const t=_h.selectedIndex,r=Ch[t],n={};for(let e in r.fields)if(r.fields.hasOwnProperty(e)){const i=r.fields[e],o=Fu(`#newOrder_${t}_${e}`).value,s=gh(i.name,o,i.type);if(s.error)return void alert(s.error);n[e]=s.value}Ih(!0);const i=await vh(e);if(i.error)return alert(i.error),void Ph("fill");if(r.check){const e=await r.check(n);if(e.error)return alert(e.error),void Ph("fill")}const o=await r.makeMessage(n),s=th.proposers.findIndex((e=>e.address.equals(Yu))),l=th.signers.findIndex((e=>e.address.equals(Yu)));if(-1===s&&-1===l)return alert("Error: you are not proposer and not signer"),void Ph("fill");const c=l>-1,d=o.toAddress,u=o.tonAmount,h=o.body,f=Math.floor(Date.now()/1e3)+2592e3,p=ud.packOrder([{type:"transfer",sendMode:a.SendMode.PAY_GAS_SEPARATELY,message:{info:{type:"internal",ihrDisabled:!1,bounce:!0,bounced:!1,dest:d.address,value:{coins:u},ihrFee:0n,forwardFee:0n,createdLt:0n,createdAt:0},body:h}}]),g=ud.newOrderMessage(p,f,c,c?l:s,e,0n),m=g.toBoc().toString("base64");console.log({toAddress:d,tonAmount:u,payloadCell:h,message:g,orderId:e});const y=eh,b=mh.toString();xh={multisigAddress:a.Address.parseFriendly(y).address,orderId:e,message:{address:y,amount:b,payload:m}},Ph("confirm"),Eh(!1)})),Fu("#newOrder_backButton").addEventListener("click",(()=>{"fill"==Ah?Gu("multisigScreen"):Ph("fill")}));const Mh=e=>{if(""===e.value)return null;try{return BigInt(e.value)}catch(e){return null}},Uh=Fu("#newMultisig_threshold"),Th=Fu("#newMultisig_orderId");let Oh,Rh,jh="create",Lh="fill";const zh=e=>{jh=e,Gu("newMultisigScreen")},Nh=()=>{if(Lh="fill",Oh={signersCount:0,proposersCount:0},Rh=void 0,Fu("#newMultisig_signersContainer").innerHTML="",Fu("#newMultisig_proposersContainer").innerHTML="",Th.value=Sh(),Uh.value="",Ku(Fu("#newMultisig_orderIdLabel"),"update"===jh),Ku(Fu("#newMultisig_orderId"),"update"===jh),"create"===jh)$h(0),Oh.signersCount=1;else{Oh.signersCount=th.signers.length;for(let e=0;e{const e=Fu("#newMultisig_deleteSigner0");Ku(e,Oh.signersCount>1)},$h=(e,t)=>{const r=document.createElement("div");r.classList.add("address-input"),r.innerHTML=`
#${e+1}.
`,Fu("#newMultisig_signersContainer").appendChild(r),Fu(`#newMultisig_signer${e}`).value=void 0===t?"":t,r.querySelector(`#newMultisig_deleteSigner${e}`).addEventListener("click",Kh)},Fh=(e,t)=>{const r=document.createElement("div");r.classList.add("address-input"),r.innerHTML=`
#${e+1}.
`,Fu("#newMultisig_proposersContainer").appendChild(r),Fu(`#newMultisig_proposer${e}`).value=void 0===t?"":t,r.querySelector(`#newMultisig_deleteProposer${e}`).addEventListener("click",Hh)},Kh=e=>{const t=e.target,r=Number(t.id.slice(24));if(isNaN(r))throw new Error;const n=[];for(let e=0;e{const t=e.target,r=Number(t.id.slice(26));if(isNaN(r))throw new Error;const n=[];for(let e=0;e{$h(Oh.signersCount),Oh.signersCount++,Dh()})),Fu("#newMultisig_addProposerButton").addEventListener("click",(async()=>{Fh(Oh.proposersCount),Oh.proposersCount++}));const Vh=()=>{const e="confirm"===Lh;Th.disabled=e,Uh.disabled=e,Ku(Fu("#newMultisig_addSignerButton"),!e),Ku(Fu("#newMultisig_addProposerButton"),!e);for(let t=0;t1)}for(let t=0;t{"fill"===Lh?Gu("create"===jh?"startScreen":"multisigScreen"):(Lh="fill",Vh())}));const qh=e=>{Fu("#newMultisig_createButton").disabled=e,Fu("#newMultisig_createButton").innerText=e?"Проверка..":"confirm"===Lh?"Подтвердить":"update"===jh?"Обновить":"Создать",Fu("#newMultisigScreen").style.pointerEvents=e?"none":"auto"};Fu("#newMultisig_createButton").addEventListener("click",(async()=>{if(!Yu)return void alert("Пожалуйста подключите кошелек");if("confirm"===Lh){try{const e=Rh.orderId,t=Rh.multisigAddress;await Qu.sendTransaction({validUntil:Math.floor(Date.now()/1e3)+60,messages:[Rh.message]}),"update"===jh?eh===Zu(t)&&ph(e):sh(Zu(t))}catch(e){console.error(e)}return}const e=(e=>{if(""===e.value)return null;try{const t=parseInt(e.value);return isNaN(t)?null:t}catch(e){return null}})(Uh);if(null==e||e<=0||e>Oh.signersCount)return void alert("Порог голосования: недопустимое число");let t;if("update"===jh){if(t=Mh(Th),null==t||t<0)return void alert("Invalid order Id");qh(!0);const e=await vh(t);if(qh(!1),e.error)return void alert(e.error)}const r={},n=[];for(let e=0;e{null!=o.splitDepth?(e.storeBit(!0),e.storeUint(o.splitDepth,5)):e.storeBit(!1),null!=o.special?(e.storeBit(!0),e.store(function(e){return t=>{t.storeBit(e.tick),t.storeBit(e.tock)}}(o.special))):e.storeBit(!1),e.storeMaybeRef(o.code),e.storeMaybeRef(o.data),e.storeDict(o.libraries)})(l),Rh={multisigAddress:r,message:{address:r.toString({urlSafe:!0,bounceable:!0,testOnly:qu}),amount:s,stateInit:l.endCell().toBoc().toString("base64")}},Lh="confirm",Vh()}else{const r=th.proposers.findIndex((e=>e.address.equals(Yu))),o=th.signers.findIndex((e=>e.address.equals(Yu)));if(-1===r&&-1===o)return void alert("Error: you are not proposer and not signer");const s=o>-1,l=Math.floor(Date.now()/1e3)+2592e3,c=ud.packOrder([{type:"update",threshold:e,signers:n,proposers:i}]),d=ud.newOrderMessage(c,l,s,s?o:r,t,0n).toBoc().toString("base64"),u=eh,h=yh.toString();Rh={multisigAddress:a.Address.parseFriendly(u).address,orderId:t,message:{address:u,amount:h,payload:d}},Lh="confirm",Vh()}var o}));const Zh=e=>{if(a.Address.isFriendly(e))return a.Address.parseFriendly(e)},Wh=async()=>{nh(),dh();const e=window.location.hash.substring(1);if(e){const{multisigAddress:t,orderId:r}=(e=>{if(e.indexOf("/")>-1){const t=e.split("/");if(2!==t.length)return{};const r=Zh(t[0]);if(void 0===r)return{};const n=(e=>{try{const t=BigInt(e);if(t<0)return;return t}catch(e){return}})(t[1]);return void 0===n?{}:{multisigAddress:r,orderId:n}}return{multisigAddress:Zh(e)}})(e);if(console.log(t,r),void 0===t)alert("Invalid URL"),Gu("startScreen");else{const e=Zu(t.address);await sh(e,r),void 0!==r&&eh===e&&await ph(r,void 0)}}else(()=>{const e=localStorage.getItem("multisigAddress");e?sh(e):Gu("startScreen")})()};Wh(),window.onpopstate=()=>Wh()})()})(); \ No newline at end of file diff --git a/index.html b/index.html index 6358c0d..d4df7cb 100644 --- a/index.html +++ b/index.html @@ -3,6 +3,7 @@ + diff --git a/src/index.ts b/src/index.ts index 38e0796..2b67fc4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -728,12 +728,12 @@ const validateValue = ( const units = BigInt(inputAmount); if (units <= 0) { - return makeError("Enter positive amount"); + return makeError("Введите положительное число"); } return makeValue(units); } catch (e: any) { - return makeError("Invalid amount"); + return makeError("Неправильная сумма"); } }; @@ -745,17 +745,17 @@ const validateValue = ( const units = toUnits(inputAmount, decimals); if (units <= 0) { - return makeError("Enter positive amount"); + return makeError("Введите положительное число"); } return makeValue(units); } catch (e: any) { - return makeError("Invalid amount"); + return makeError("Неправильная сумма"); } }; if (value === null || value === undefined || value === "") { - return makeError(`Empty`); + return makeError(`Пусто`); } switch (fieldType) { @@ -763,21 +763,21 @@ const validateValue = ( return parseAmount(value, 9); case "Jetton": - return parseBigInt(value); + return parseAmount(value, 6); case "Address": if (!Address.isFriendly(value)) { - return makeError("Invalid Address"); + return makeError("Неправильный адрес"); } const address = Address.parseFriendly(value); if (address.isTestOnly && !IS_TESTNET) { - return makeError("Please enter mainnet address"); + return makeError("Пожалуйста, введите адрес из основной сети"); } return makeValue(address); case "URL": if (!value.startsWith("https://")) { - return makeError("Invalid URL"); + return makeError("Неправильный URL адрес"); } return makeValue(value); @@ -786,7 +786,8 @@ const validateValue = ( return makeValue(value); } else { return makeError( - "Invalid status. Please use: " + LOCK_TYPES.join(", ") + "Неправильный статус. Пожалуйста, используйте: " + + LOCK_TYPES.join(", ") ); } } @@ -827,7 +828,9 @@ const checkJettonMinterAdmin = async (values: { ); if (!multisigInfo.address.address.equals(jettonMinterInfo.adminAddress)) { - return { error: "Multisig is not admin of this jetton" }; + return { + error: "Мультикошелек не является администратором этого жетона", + }; } return { value: jettonMinterInfo }; @@ -853,7 +856,9 @@ const checkJettonMinterNextAdmin = async (values: { !jettonMinterInfo.nextAdminAddress || !multisigInfo.address.address.equals(jettonMinterInfo.nextAdminAddress) ) { - return { error: "Multisig is not next-admin of this jetton" }; + return { + error: "Мультикошелек не является администратором этого жетона", + }; } return { value: jettonMinterInfo }; diff --git a/src/multisig/MultisigOrderChecker.ts b/src/multisig/MultisigOrderChecker.ts index 2cee524..e957ca6 100644 --- a/src/multisig/MultisigOrderChecker.ts +++ b/src/multisig/MultisigOrderChecker.ts @@ -310,7 +310,7 @@ export const checkMultisigOrder = async ( ); return `Принудительная отправка ${ parsed.action.jettonAmount - } с адреса польщователя ${fromAddress} на адрес ${toAddress}; ${fromNano( + } с адреса польщзвателя ${fromAddress} на адрес ${toAddress}; ${fromNano( parsed.tonAmount )} TON for gas`; } catch (e) {} @@ -351,22 +351,22 @@ export const checkMultisigOrder = async ( let allBalance = false; if (sendMode & 1) { - sendModeString.push("Pays fees separately"); + sendModeString.push("Комиссии оплачиваются отдельно"); } if (sendMode & 2) { - sendModeString.push("Ignore sending errors"); + sendModeString.push("Игнорировать ошибки отправки"); } if (sendMode & 128) { allBalance = true; - sendModeString.push("CARRY ALL BALANCE"); + sendModeString.push("Сохранить весь баланс"); } if (sendMode & 64) { sendModeString.push( - "Carry all the remaining value of the inbound message" + "Перенесите все оставшееся значение входящего сообщения" ); } if (sendMode & 32) { - sendModeString.push("DESTROY ACCOUNT"); + sendModeString.push("УНИЧТОЖИТЬ УЧЕТНУЮ ЗАПИСЬ"); } const actionBody = slice.loadRef(); @@ -377,14 +377,16 @@ export const checkMultisigOrder = async ( const info: CommonMessageInfoRelaxedInternal = messageRelaxed.info as any; const destAddress = await formatAddressAndUrl(info.dest, isTestnet); - actionString += `
Send ${ - allBalance ? "ALL BALANCE" : fromNano(info.value.coins) - } TON to ${destAddress}
`; + actionString += `
Отправить ${ + allBalance ? "ВЕСЬ БАЛАНС" : fromNano(info.value.coins) + } TON на адрес ${destAddress}
`; actionString += `
${await parseActionBody( messageRelaxed.body )}
`; if (sendMode) { - actionString += `
Send mode: ${sendModeString.join(", ")}.
`; + actionString += `
Метод отправки: ${sendModeString.join( + ", " + )}.
`; } } else if (actionOp === 0x1d0cfbd3) { // update_multisig_params @@ -395,9 +397,9 @@ export const checkMultisigOrder = async ( : []; endParse(slice); - assert(newSigners.length > 0, "Invalid new signers"); - assert(newThreshold > 0, "Invalid new threshold"); - assert(newThreshold <= newSigners.length, "Invalid new threshold"); + assert(newSigners.length > 0, "Неправильный адрес подписывающего"); + assert(newThreshold > 0, "Неправильный новый порог"); + assert(newThreshold <= newSigners.length, "Неправильный порог"); actionString += `
Обновить параметры мультикошелька
`; actionString += `
Новый порог подписей : ${newThreshold.toString()}
`;