UNPKG

@fotonjs/core

Version:
2 lines (1 loc) 15 kB
import{createClient as Tt}from"@fotonjs/api";var ht=async(t,e)=>(await t.transactionsByMessage({direction:"in",msg_hash:e})).data;async function $(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 ht(this._api,e);l?.transactions.length&&(clearInterval(c),o(l.transactions[0])),n&&s>=n&&(clearInterval(c),o(void 0))},r)})}async function J(t){let e=await this._api.account({address:t.address});return e.data?.balance?BigInt(e.data.balance):void 0}var z=t=>{let r={_api:Tt(t)};return r.waitForTransaction=$.bind(r),r.getBalance=J.bind(r),r};import{TonConnect as At}from"@tonconnect/sdk";import{isWalletInfoInjectable as Et,isWalletInfoRemote as gt}from"@tonconnect/sdk";var T=t=>t&&"closeModal"in t&&"openModal"in t&&"uiOptions"in t&&"modalState"in t,L=t=>t&&"tracker"in t&&"walletsList"in t&&"dappSettings"in t&&"bridgeConnectionStorage"in t;var h=class extends Error{constructor(e){super(e),this.name="UserError"}},E=class extends h{constructor(){super("Not authorized. Please, connect the wallet first"),this.name="UserUnauthorizedError"}},g=class extends h{constructor(){super("User rejected the connection to their wallet"),this.name="UserRejectedConnectionError"}},b=class extends h{constructor(){super("User rejected the transaction request from their wallet"),this.name="UserRejectedTransactionError"}};var p=class extends Error{constructor(e){super(e),this.name="SyntaxError"}},x=class extends p{constructor(){super("This function is not available for UI-based wallet connections. Use `createWalletClientUI` instead"),this.name="ConnectFunctionUnavailableError"}},I=class extends p{constructor(){super("This function is only available for UI-based wallet connections"),this.name="ConnectUIFunctionUnavailableError"}},u=class extends p{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"}},R=class extends p{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 p{constructor(){super("The contract is incorrect. Provide the contract class compiled from your Tact or Func files"),this.name="IncorrectContractError"}},O=class extends p{constructor(){super("The contract address is not provided to the walletClient. Call `setAddress` first"),this.name="MissingContractAddressError"}};import{TonConnectError as F}from"@tonconnect/sdk";var U=class t extends F{constructor(...e){super(...e),Object.setPrototypeOf(this,t.prototype)}},m=class extends Error{constructor(e){super(e),this.name="TonError"}},w=class extends m{constructor(){super("Wallet connection failed"),this.name="TonWalletConnectionError"}},A=class extends m{constructor(){super("Could not disconnect from the wallet"),this.name="TonWalletDisconnectError"}},D=class extends m{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"}},j=class extends m{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 _={ConnectFunctionUnavailableError:x,ConnectUIFunctionUnavailableError:I,ConnectUIFunctionUnavailableInNodeError:u,ReconnectFunctionUnavailableError:R,IncorrectContractError:W,MissingContractAddressError:O,UserUnauthorizedError:E,UserRejectedConnectionError:g,UserRejectedTransactionError:b,TonConnectError:F,TonConnectUIError:U,TonWalletConnectionError:w,TonWalletDisconnectError:A,TonReadError:D,TonRateLimitError:j};var i=t=>({data:void 0,error:new _[t]});var a=t=>({data:t,error:void 0});async function q(t){return new Promise(async e=>{if(this._wallet)return e(a(this._wallet));if(!L(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"))}),Et(t)&&t.injected)this.connection.connect({jsBridgeKey:t.jsBridgeKey});else if(gt(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 B(){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 K(){return new Promise(async t=>{if(T(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()})}import{isWalletInfoCurrentlyInjected as bt,isWalletInfoInjectable as xt,isWalletInfoRemote as It,isWalletInfoCurrentlyEmbedded as Rt}from"@tonconnect/sdk";var Wt={all:null,injected:bt,injectable:xt,remote:It,embedded:Rt},Y=(t,e)=>{let r=Wt[e];return r?t.filter(r):t};async function P(t){let{type:e="all"}=t||{};if(this.wallets?.length)return a(Y(this.wallets,e));let r=await this.connection.getWallets();return this.wallets=r,a(Y(r,e))}import{toNano as Ot}from"@ton/core";var X=Ot;import{Cell as Ut}from"@ton/core";var d=t=>Ut.fromBase64(t).hash().toString("base64");import{CHAIN as Q}from"@tonconnect/sdk";var wt={mainnet:Q.MAINNET,testnet:Q.TESTNET},f=t=>wt[t];async function v(t){if(!this.connected||!this.address)return i("UserUnauthorizedError");try{let e=await this.connection.sendTransaction({network:f(this._chain),from:this.address,validUntil:Date.now()+3e5,messages:[{address:t.to,amount:t.value.toString()}]}),r=d(e.boc);return a(r)}catch{return i("UserRejectedTransactionError")}}function N(){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 Z(t){let{chain:e,...r}=t||{},n;r.connection?n=r.connection:n=new At(r);let o={connection:n,connected:!1,address:void 0};return o.getWallets=P.bind(o),o.connect=q.bind(o),o.disconnect=B.bind(o),o.reconnect=K.bind(o),o.sendTransaction=v.bind(o),N.call(o),o}import{TonConnectUI as jt}from"@tonconnect/ui";var Dt=async(t,e)=>{let r=t.connection;e?await r.openSingleWalletModal(e.appName):await r.openModal()},V=async(t,e)=>{let r=t.connection;e?r.closeSingleWalletModal():r.closeModal()};async function tt(t){return new Promise(async e=>{if(this._wallet)return e(a(this._wallet));if(!T(this.connection))return e(i("ConnectUIFunctionUnavailableError"));this._connectionCallbacks.push(n=>n instanceof Error?(V(this,t),e({error:n,data:void 0})):n?e(a(n)):(V(this,t),e(i("TonWalletConnectionError"))));let r=this.connection.onModalStateChange(n=>{n.status==="closed"&&setTimeout(()=>{r(),e(i("UserRejectedConnectionError"))})});await Dt(this,t)})}var S;function et(t){let{chain:e,...r}=t||{};if(typeof window>"u")throw new u;if(S)return S;let n={connected:!1,address:void 0};return r.connection?n.connection=r.connection:n.connection=new jt(r),n.getWallets=P.bind(n),n.connect=tt.bind(n),n.disconnect=B.bind(n),n.sendTransaction=v.bind(n),N.call(n),S=n,n}import{Address as Bt,beginCell as rt,Cell as G}from"@ton/core";var Pt=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),[]),vt=(t,e)=>(t.types||[]).find(r=>r.name===e),Nt=(t,e)=>(e?.fields||[]).reduce((r,n)=>(r[n.name]=n.type,r),{}),Mt=(t,e)=>(t.types||[]).find(n=>n.name===e)?.header||void 0,Ft={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=Bt.parse(e);t.storeAddress(n)},cell:(t,e,r)=>{if(typeof e!="string")return new Error("Cell value must be a string");let n=G.fromBase64(e);t.storeRef(n)},slice:(t,e,r)=>{if(typeof e!="string")return new Error("Cell value must be a string");let n=G.fromBase64(e).asSlice();t.storeSlice(n)}},_t=(t,e,r)=>{let n=rt();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 M=s.type,C=Ft[M](n,c,s.format);if(C instanceof Error)throw new Error(`Payload validation failed for field "${o}": ${C.message}`)}else throw new Error("Unsupported field type")}),n.endCell().toBoc().toString("base64")},y=(t,e,r)=>{if(!t.abi)throw new Error("Contract class must have an ABI");if(!Pt(t.abi).includes(e))throw new Error(`Method ${e} is not available for this contract's ABI`);if(e==="empty")return new G().toBoc().toString("base64");let o=vt(t.abi,e);if(!o)return rt().storeUint(0,32).storeStringTail(e).endCell().toBoc().toString("base64");let s=Nt(t.abi,o),c=Mt(t.abi,e);return _t(s,r||{},c)};import{beginCell as St,storeStateInit as Gt}from"@ton/core";var nt=t=>{let e=St();return Gt({code:t.init.code,data:t.init.data})(e),e.endCell().toBoc().toString("base64")};async function ot(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=y(e,"Deploy",t.payload)}catch{n=void 0}try{let o=await this._walletClient.connection.sendTransaction({network:f(this._walletClient._chain),from:this._walletClient.address,validUntil:Date.now()+3e5,messages:[{address:r,amount:t.value.toString(),stateInit:nt(e),payload:n}]});return this.setAddress(r),a({address:r,txHash:d(o.boc)})}catch(o){return console.error("err",o),i("UserRejectedTransactionError")}}import{Address as kt}from"@ton/core";async function it(t){if(!this.address)return i("MissingContractAddressError");if(!this._walletClient.connected||!this._walletClient.address)return i("UserUnauthorizedError");try{let e=this._contract.fromAddress(kt.parse(this.address));if(!e.abi)return i("IncorrectContractError");let r=await this._walletClient.connection.sendTransaction({network:f(this._walletClient._chain),validUntil:Date.now()+5*60*1e3,from:this._walletClient.address,messages:[{address:this.address,amount:t.value.toString(),payload:y(e,t.method,t.payload)}]});return a(d(r.boc))}catch{return i("UserRejectedTransactionError")}}import{Address as $t}from"@ton/core";var at=(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}})};import{Cell as Ht}from"@ton/core";var ct=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.')},st=(t,e)=>{let r=ct(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 Ht.fromBase64(r).beginParse().loadAddress().toString();if((t.type==="cell"||t.type==="slice")&&typeof r=="string")return r},lt=(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.'),ct(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,M)=>{let C=s[M];return C&&(c[C.name]=st(C.type,l)),c},{})}return st(n,r.stack[0])};async function pt(t){if(!this.address)return i("MissingContractAddressError");let e=this._contract.fromAddress($t.parseFriendly(this.address).address);if(!e.abi)return i("IncorrectContractError");let r=at(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(lt(e.abi,t.getter,n.data))}catch{return i("TonReadError")}}function dt(t){this.address=t}var Ct=t=>{let{publicClient:e,walletClient:r,contract:n}=t,o={_publicClient:e,_walletClient:r,_contract:n,address:t.address};return o.setAddress=dt.bind(o),o.deploy=ot.bind(o),o.read=pt.bind(o),o.write=it.bind(o),o};import{beginCell as qt}from"@ton/core";import{beginCell as mt,Dictionary as k}from"@ton/core";import{sha256_sync as Jt}from"@ton/crypto";var ut=t=>BigInt("0x"+Jt(t).toString("hex")),zt=t=>mt().storeUint(0,8).storeStringTail(t).endCell(),Lt=t=>mt().storeUint(t,64).endCell(),ft=t=>{let e=k.empty(k.Keys.BigUint(256),k.Values.Cell());return Object.entries(t).forEach(([r,n])=>{if(typeof n=="bigint"){e.set(ut(r),Lt(n));return}e.set(ut(r),zt(n))}),e};var Kt=0;var H=t=>{let e=ft(t);return qt().storeInt(Kt,8).storeDict(e).endCell()};import{Address as Yt}from"@ton/core";var yt=t=>{let e=Yt.parse(t.owner),r=H(t.content),n=BigInt(t.maxSupply);return[e,r,n]};export{y as composePayload,Ct as createContractClient,z as createPublicClient,Z as createWalletClient,et as createWalletClientUI,yt as getJettonDeployArguments,X as parseTon};