@fotonjs/core
Version:
Foton: build TON dApps with ease
2 lines (1 loc) • 15.7 kB
JavaScript
;var $=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Bt=Object.prototype.hasOwnProperty;var Pt=(t,e)=>{for(var r in e)$(t,r,{get:e[r],enumerable:!0})},vt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jt(e))!Bt.call(t,o)&&o!==r&&$(t,o,{get:()=>e[o],enumerable:!(n=Dt(e,o))||n.enumerable});return t};var Nt=t=>vt($({},"__esModule",{value:!0}),t);var Yt={};Pt(Yt,{composePayload:()=>m,createContractClient:()=>Q,createPublicClient:()=>J,createWalletClient:()=>K,createWalletClientUI:()=>X,getJettonDeployArguments:()=>V,parseTon:()=>L});module.exports=Nt(Yt);var rt=require("@fotonjs/api");var Mt=async(t,e)=>(await t.transactionsByMessage({direction:"in",msg_hash:e})).data;async function tt(t){let{hash:e,refetchInterval:r=1e3,refetchLimit:n=void 0}=t||{};return new Promise(o=>{let s=0,c=setInterval(async()=>{s+=1;let l=await Mt(this._api,e);l?.transactions.length&&(clearInterval(c),o(l.transactions[0])),n&&s>=n&&(clearInterval(c),o(void 0))},r)})}async function et(t){let e=await this._api.account({address:t.address});return e.data?.balance?BigInt(e.data.balance):void 0}var J=t=>{let r={_api:(0,rt.createClient)(t)};return r.waitForTransaction=tt.bind(r),r.getBalance=et.bind(r),r};var lt=require("@tonconnect/sdk");var M=require("@tonconnect/sdk");var b=t=>t&&"closeModal"in t&&"openModal"in t&&"uiOptions"in t&&"modalState"in t,nt=t=>t&&"tracker"in t&&"walletsList"in t&&"dappSettings"in t&&"bridgeConnectionStorage"in t;var g=class extends Error{constructor(e){super(e),this.name="UserError"}},x=class extends g{constructor(){super("Not authorized. Please, connect the wallet first"),this.name="UserUnauthorizedError"}},I=class extends g{constructor(){super("User rejected the connection to their wallet"),this.name="UserRejectedConnectionError"}},R=class extends g{constructor(){super("User rejected the transaction request from their wallet"),this.name="UserRejectedTransactionError"}};var d=class extends Error{constructor(e){super(e),this.name="SyntaxError"}},W=class extends d{constructor(){super("This function is not available for UI-based wallet connections. Use `createWalletClientUI` instead"),this.name="ConnectFunctionUnavailableError"}},O=class extends d{constructor(){super("This function is only available for UI-based wallet connections"),this.name="ConnectUIFunctionUnavailableError"}},h=class extends d{constructor(){super("This function is not available in the server environment. Please you `createWalletClient` instead or, if you use Next.js, call `createWalletClientUI` in `useEffect` hook or in the event handler, so it creates a wallet client when the `window` is available."),this.name="ConnectUIFunctionUnavailableInNodeError"}},U=class extends d{constructor(){super("The reconnect is not available for UI-based wallet connections. Pass `restoreConnection: true` to the `createWalletClientUI` function to enable it"),this.name="ReconnectFunctionUnavailableError"}},w=class extends d{constructor(){super("The contract is incorrect. Provide the contract class compiled from your Tact or Func files"),this.name="IncorrectContractError"}},A=class extends d{constructor(){super("The contract address is not provided to the walletClient. Call `setAddress` first"),this.name="MissingContractAddressError"}};var N=require("@tonconnect/sdk"),D=class t extends N.TonConnectError{constructor(...e){super(...e),Object.setPrototypeOf(this,t.prototype)}},T=class extends Error{constructor(e){super(e),this.name="TonError"}},j=class extends T{constructor(){super("Wallet connection failed"),this.name="TonWalletConnectionError"}},B=class extends T{constructor(){super("Could not disconnect from the wallet"),this.name="TonWalletDisconnectError"}},P=class extends T{constructor(){super("Cannot process the read request. Either the request returned a non-zero exit code or the data could not be parsed"),this.name="TonReadError"}},v=class extends T{constructor(){super("Rate limit is exceeded. Provide the `authKey` to the public client with a better Ton Center plan to get more requests per second"),this.name="TonRateLimitError"}};var z={ConnectFunctionUnavailableError:W,ConnectUIFunctionUnavailableError:O,ConnectUIFunctionUnavailableInNodeError:h,ReconnectFunctionUnavailableError:U,IncorrectContractError:w,MissingContractAddressError:A,UserUnauthorizedError:x,UserRejectedConnectionError:I,UserRejectedTransactionError:R,TonConnectError:N.TonConnectError,TonConnectUIError:D,TonWalletConnectionError:j,TonWalletDisconnectError:B,TonReadError:P,TonRateLimitError:v};var i=t=>({data:void 0,error:new z[t]});var a=t=>({data:t,error:void 0});async function ot(t){return new Promise(async e=>{if(this._wallet)return e(a(this._wallet));if(!nt(this.connection))return e(i("ConnectFunctionUnavailableError"));if(this._connectionCallbacks.push(r=>{if(r instanceof Error)return e({error:r,data:void 0});e(r?a(r):i("TonWalletConnectionError"))}),(0,M.isWalletInfoInjectable)(t)&&t.injected)this.connection.connect({jsBridgeKey:t.jsBridgeKey});else if((0,M.isWalletInfoRemote)(t)){let r=this.connection.connect({universalLink:t.universalLink,bridgeUrl:t.bridgeUrl});typeof window>"u"?(console.info(`Open the following link in your browser to connect with ${t.name}: ${r}`),console.info(r)):window.open(r,"_blank")}})}async function F(){return new Promise(async t=>{this._connectionCallbacks.push(e=>{if(e instanceof Error)return t({error:e,data:void 0});t(e?i("TonWalletDisconnectError"):a(!0))}),await this.connection.disconnect()})}async function it(){return new Promise(async t=>{if(b(this.connection))return t(i("ReconnectFunctionUnavailableError"));if(this._wallet)return a(this._wallet);this._connectionCallbacks.push(e=>e instanceof Error?t({error:e,data:void 0}):t(e?a(e):i("TonWalletConnectionError"))),await this.connection.restoreConnection()})}var C=require("@tonconnect/sdk");var Ft={all:null,injected:C.isWalletInfoCurrentlyInjected,injectable:C.isWalletInfoInjectable,remote:C.isWalletInfoRemote,embedded:C.isWalletInfoCurrentlyEmbedded},at=(t,e)=>{let r=Ft[e];return r?t.filter(r):t};async function _(t){let{type:e="all"}=t||{};if(this.wallets?.length)return a(at(this.wallets,e));let r=await this.connection.getWallets();return this.wallets=r,a(at(r,e))}var st=require("@ton/core"),L=st.toNano;var ct=require("@ton/core"),u=t=>ct.Cell.fromBase64(t).hash().toString("base64");var q=require("@tonconnect/sdk"),_t={mainnet:q.CHAIN.MAINNET,testnet:q.CHAIN.TESTNET},E=t=>_t[t];async function S(t){if(!this.connected||!this.address)return i("UserUnauthorizedError");try{let e=await this.connection.sendTransaction({network:E(this._chain),from:this.address,validUntil:Date.now()+3e5,messages:[{address:t.to,amount:t.value.toString()}]}),r=u(e.boc);return a(r)}catch{return i("UserRejectedTransactionError")}}function G(){this._connectionCallbacks=[],this.connection.onStatusChange(t=>{t?(this.connected=!0,this._wallet=t,this.address=t.account.address):(this.connected=!1,this._wallet=void 0,this.address=void 0),this._connectionCallbacks.forEach(e=>e(t))},t=>{this._connectionCallbacks.forEach(e=>e(t))})}function K(t){let{chain:e,...r}=t||{},n;r.connection?n=r.connection:n=new lt.TonConnect(r);let o={connection:n,connected:!1,address:void 0};return o.getWallets=_.bind(o),o.connect=ot.bind(o),o.disconnect=F.bind(o),o.reconnect=it.bind(o),o.sendTransaction=S.bind(o),G.call(o),o}var Ct=require("@tonconnect/ui");var St=async(t,e)=>{let r=t.connection;e?await r.openSingleWalletModal(e.appName):await r.openModal()},pt=async(t,e)=>{let r=t.connection;e?r.closeSingleWalletModal():r.closeModal()};async function dt(t){return new Promise(async e=>{if(this._wallet)return e(a(this._wallet));if(!b(this.connection))return e(i("ConnectUIFunctionUnavailableError"));this._connectionCallbacks.push(n=>n instanceof Error?(pt(this,t),e({error:n,data:void 0})):n?e(a(n)):(pt(this,t),e(i("TonWalletConnectionError"))));let r=this.connection.onModalStateChange(n=>{n.status==="closed"&&setTimeout(()=>{r(),e(i("UserRejectedConnectionError"))})});await St(this,t)})}var Y;function X(t){let{chain:e,...r}=t||{};if(typeof window>"u")throw new h;if(Y)return Y;let n={connected:!1,address:void 0};return r.connection?n.connection=r.connection:n.connection=new Ct.TonConnectUI(r),n.getWallets=_.bind(n),n.connect=dt.bind(n),n.disconnect=F.bind(n),n.sendTransaction=S.bind(n),G.call(n),Y=n,n}var p=require("@ton/core"),Gt=t=>(t.receivers||[]).reduce((e,r)=>(r.message.kind==="typed"?e.push(r.message.type):r.message.kind==="text"&&r.message.text&&e.push(r.message.text),e),[]),kt=(t,e)=>(t.types||[]).find(r=>r.name===e),Ht=(t,e)=>(e?.fields||[]).reduce((r,n)=>(r[n.name]=n.type,r),{}),$t=(t,e)=>(t.types||[]).find(n=>n.name===e)?.header||void 0,Jt={uint:(t,e,r)=>{if(!(typeof e=="bigint"&&e>=0n))return new Error("Uint value must be a positive bigint");t.storeUint(e,r??32)},int:(t,e,r)=>{if(typeof e!="bigint")return new Error("Int value must be a bigint");t.storeInt(e,r??32)},bool:(t,e,r)=>{if(typeof e!="boolean")return new Error("Bool value must be a boolean");t.storeBit(e)},address:(t,e,r)=>{if(typeof e!="string")return new Error("Address value must be a string");let n=p.Address.parse(e);t.storeAddress(n)},cell:(t,e,r)=>{if(typeof e!="string")return new Error("Cell value must be a string");let n=p.Cell.fromBase64(e);t.storeRef(n)},slice:(t,e,r)=>{if(typeof e!="string")return new Error("Cell value must be a string");let n=p.Cell.fromBase64(e).asSlice();t.storeSlice(n)}},zt=(t,e,r)=>{let n=(0,p.beginCell)();return r&&n.storeUint(r,32),Object.entries(t).forEach(([o,s])=>{let c=e[o];if(s.kind==="simple"){if(!(s.optional||!0)&&(typeof c>"u"||c===null))throw new Error(`Field ${o} is required`);let H=s.type,y=Jt[H](n,c,s.format);if(y instanceof Error)throw new Error(`Payload validation failed for field "${o}": ${y.message}`)}else throw new Error("Unsupported field type")}),n.endCell().toBoc().toString("base64")},m=(t,e,r)=>{if(!t.abi)throw new Error("Contract class must have an ABI");if(!Gt(t.abi).includes(e))throw new Error(`Method ${e} is not available for this contract's ABI`);if(e==="empty")return new p.Cell().toBoc().toString("base64");let o=kt(t.abi,e);if(!o)return(0,p.beginCell)().storeUint(0,32).storeStringTail(e).endCell().toBoc().toString("base64");let s=Ht(t.abi,o),c=$t(t.abi,e);return zt(s,r||{},c)};var k=require("@ton/core"),ut=t=>{let e=(0,k.beginCell)();return(0,k.storeStateInit)({code:t.init.code,data:t.init.data})(e),e.endCell().toBoc().toString("base64")};async function mt(t){if(!this._walletClient.connected||!this._walletClient.address)return i("UserUnauthorizedError");let e=await this._contract.fromInit(...t.arguments);if(!e.init?.code||!e.init?.data||!e.abi)return i("IncorrectContractError");let r=e.address.toString(),n;try{n=m(e,"Deploy",t.payload)}catch{n=void 0}try{let o=await this._walletClient.connection.sendTransaction({network:E(this._walletClient._chain),from:this._walletClient.address,validUntil:Date.now()+3e5,messages:[{address:r,amount:t.value.toString(),stateInit:ut(e),payload:n}]});return this.setAddress(r),a({address:r,txHash:u(o.boc)})}catch(o){return console.error("err",o),i("UserRejectedTransactionError")}}var ft=require("@ton/core");async function yt(t){if(!this.address)return i("MissingContractAddressError");if(!this._walletClient.connected||!this._walletClient.address)return i("UserUnauthorizedError");try{let e=this._contract.fromAddress(ft.Address.parse(this.address));if(!e.abi)return i("IncorrectContractError");let r=await this._walletClient.connection.sendTransaction({network:E(this._walletClient._chain),validUntil:Date.now()+5*60*1e3,from:this._walletClient.address,messages:[{address:this.address,amount:t.value.toString(),payload:m(e,t.method,t.payload)}]});return a(u(r.boc))}catch{return i("UserRejectedTransactionError")}}var xt=require("@ton/core");var ht=(t,e,r)=>{let n=(t.getters||[]).find(s=>s.name===e);if(!n)throw new Error(`Getter ${e} is not found in the contract's ABI`);let o=n.arguments||[];if(r.length>o.length)throw new Error(`The number of arguments provided to the "${e}" getter is more than the number of arguments in the ABI. Expected no more than ${o.length}, got ${r.length}`);return o.map((s,c)=>{let l=r[c];if(s.type.kind==="simple"){if(s.type.type==="int"){if(typeof l!="bigint")throw new Error(`"${e}" getter: Argument "${s.name}" must be a bigint`);return{type:"num",value:`0x${l.toString(16)}`}}if(typeof l!="string")throw new Error(`"${e}" getter: Argument "${s.name}" must be a string`);return{type:"cell",value:l}}return{type:"slice",value:l}})};var Et=require("@ton/core"),gt=t=>{if(t.type==="num"&&typeof t.value=="string")return t.value.startsWith("-")?-1n*BigInt(t.value.slice(1)):BigInt(t.value);if(typeof t.value=="string")return t.value;if(t.value&&Array.isArray(t.value))throw new Error('The response data is parsed incorrectly: nested array data is not yet supported. Please submit an issue to "foton" repository with the request you are trying to make.')},Tt=(t,e)=>{let r=gt(e);if(t.kind!=="simple"){console.error('The response data is parsed incorrectly. Please submit an issue to "foton" repository with the request you are trying to make.');return}if(t.type==="int"&&typeof r=="bigint")return r;if(t.type==="bool"&&typeof r=="bigint")return r!==0n;if(t.type==="address"&&typeof r=="string")return Et.Cell.fromBase64(r).beginParse().loadAddress().toString();if((t.type==="cell"||t.type==="slice")&&typeof r=="string")return r},bt=(t,e,r)=>{if(r.exit_code!==0)throw new Error(`Getter ${e} failed with exit code ${r.exit_code}`);let n=t.getters?.find(s=>s.name===e)?.returnType;if(!n)throw new Error(`Provided contract doesn't support a "${e}" getter in its ABI`);if(!r.stack.length)return;if(n.kind!=="simple")return console.error('The response data is parsed incorrectly. Please submit an issue to "foton" repository with the request you are trying to make.'),gt(r.stack[0]);let o=(t.types||[]).find(s=>s.name===n.type);if(o&&o.fields?.length){let s=o.fields;return r.stack.reduce((c,l,H)=>{let y=s[H];return y&&(c[y.name]=Tt(y.type,l)),c},{})}return Tt(n,r.stack[0])};async function It(t){if(!this.address)return i("MissingContractAddressError");let e=this._contract.fromAddress(xt.Address.parseFriendly(this.address).address);if(!e.abi)return i("IncorrectContractError");let r=ht(e.abi,t.getter,t.arguments),n=await this._publicClient._api.runGetMethod({address:this.address,method:t.getter,stack:r});if(n.error)return n.response.status===429?i("TonRateLimitError"):i("TonReadError");try{return a(bt(e.abi,t.getter,n.data))}catch{return i("TonReadError")}}function Rt(t){this.address=t}var Q=t=>{let{publicClient:e,walletClient:r,contract:n}=t,o={_publicClient:e,_walletClient:r,_contract:n,address:t.address};return o.setAddress=Rt.bind(o),o.deploy=mt.bind(o),o.read=It.bind(o),o.write=yt.bind(o),o};var wt=require("@ton/core");var f=require("@ton/core"),Ot=require("@ton/crypto"),Wt=t=>BigInt("0x"+(0,Ot.sha256_sync)(t).toString("hex")),Lt=t=>(0,f.beginCell)().storeUint(0,8).storeStringTail(t).endCell(),qt=t=>(0,f.beginCell)().storeUint(t,64).endCell(),Ut=t=>{let e=f.Dictionary.empty(f.Dictionary.Keys.BigUint(256),f.Dictionary.Values.Cell());return Object.entries(t).forEach(([r,n])=>{if(typeof n=="bigint"){e.set(Wt(r),qt(n));return}e.set(Wt(r),Lt(n))}),e};var Kt=0;var Z=t=>{let e=Ut(t);return(0,wt.beginCell)().storeInt(Kt,8).storeDict(e).endCell()};var At=require("@ton/core");var V=t=>{let e=At.Address.parse(t.owner),r=Z(t.content),n=BigInt(t.maxSupply);return[e,r,n]};0&&(module.exports={composePayload,createContractClient,createPublicClient,createWalletClient,createWalletClientUI,getJettonDeployArguments,parseTon});