`;{const t=!!e.orderInfo&&(new Date).getTime()>e.orderInfo.expiresAt.getTime(),r=t?"Истекший срок заявки ":(e=>{switch(e.type){case"new":return"Новая заявка";case"execute":return"Выполнить заявку";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,"Контракт не активен. Если вы только что создали мультиподпись, она должна появиться в течение ~30 секунд."),nd(a.Cell.fromBase64(s.code).equals(t),"Код контракта НЕ совпадает с кодом мультиподписи из этого репозитория");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("Подключите кошелек");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("Неверная сумма");let o=i[0],s=i[1];if(o||(o="0"),s||(s="0"),s.length>t)throw Error("Неверная сумма");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 Id(e.jettonMinterAddress,qu,!1);return t.address.address.equals(r.adminAddress)?{value:r}:{error:"Мультикошелек не является администратором этого жетона"}}catch(e){return console.error(e),{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:"Возможная ошибка подключения"}}},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 Id(e.jettonMinterAddress,qu,!0);return r.nextAdminAddress&&t.address.address.equals(r.nextAdminAddress)?{value:r}:{error:"Мультикошелек не является администратором этого жетона"}}catch(e){return console.error(e),{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=()=>{Ih("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},Ph=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)},Ih=e=>{"fill"==e?(Ph(!1),Fu("#newOrder_createButton").innerHTML="Создать",Fu("#newOrder_backButton").innerHTML="Назад"):(Ph(!0),Fu("#newOrder_createButton").innerHTML="Отправить транзакцию",Fu("#newOrder_backButton").innerHTML="Отменить"),Ah=e};Fu("#newOrder_createButton").addEventListener("click",(async()=>{if(!Yu)return void alert("Пожалуйста, подключите кошелек");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("Неверный идентификатор заявки");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}Ph(!0);const i=await vh(e);if(i.error)return alert(i.error),void Ih("fill");if(r.check){const e=await r.check(n);if(e.error)return alert(e.error),void Ih("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("Ошибка:вы не предлагающий и не подтверждающий"),void Ih("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}},Ih("confirm"),Eh(!1)})),Fu("#newOrder_backButton").addEventListener("click",(()=>{"fill"==Ah?Gu("multisigScreen"):Ih("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=`
`;{const t=!!e.orderInfo&&(new Date).getTime()>e.orderInfo.expiresAt.getTime(),r=t?"Истекший срок заявки ":(e=>{switch(e.type){case"new":return"Новая заявка";case"execute":return"Выполнить заявку";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,"Контракт не активен. Если вы только что создали мультиподпись, она должна появиться в течение ~30 секунд."),nd(a.Cell.fromBase64(s.code).equals(t),"Код контракта НЕ совпадает с кодом мультиподписи из этого репозитория");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("Подключите кошелек");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("Неверная сумма");let o=i[0],s=i[1];if(o||(o="0"),s||(s="0"),s.length>t)throw Error("Неверная сумма");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 Id(e.jettonMinterAddress,qu,!1);return t.address.address.equals(r.adminAddress)?{value:r}:{error:"Мультикошелек не является администратором этого жетона"}}catch(e){return console.error(e),{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:"Возможная ошибка подключения"}}},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 Id(e.jettonMinterAddress,qu,!0);return r.nextAdminAddress&&t.address.address.equals(r.nextAdminAddress)?{value:r}:{error:"Мультикошелек не является администратором этого жетона"}}catch(e){return console.error(e),{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=()=>{Ih("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},Ph=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)},Ih=e=>{"fill"==e?(Ph(!1),Fu("#newOrder_createButton").innerHTML="Создать",Fu("#newOrder_backButton").innerHTML="Назад"):(Ph(!0),Fu("#newOrder_createButton").innerHTML="Отправить транзакцию",Fu("#newOrder_backButton").innerHTML="Отменить"),Ah=e};Fu("#newOrder_createButton").addEventListener("click",(async()=>{if(!Yu)return void alert("Пожалуйста, подключите кошелек");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("Неверный идентификатор заявки");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}Ph(!0);const i=await vh(e);if(i.error)return alert(i.error),void Ih("fill");if(r.check){const e=await r.check(n);if(e.error)return alert(e.error),void Ih("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("Ошибка:вы не предлагающий и не подтверждающий"),void Ih("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}},Ih("confirm"),Eh(!1)})),Fu("#newOrder_backButton").addEventListener("click",(()=>{"fill"==Ah?Gu("multisigScreen"):Ih("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=`