UNPKG

@dojoengine/sdk

Version:

Dojo SDK: Build onchain and provable apps faster

2 lines 12.8 kB
import*as V from"@dojoengine/torii-wasm/node";import{err as g,ok as L}from"neverthrow";import{shortString as D}from"starknet";import{CairoCustomEnum as v,CairoOption as p,CairoOptionVariant as C}from"starknet";import{CairoCustomEnum as z,CairoOption as O,CairoOptionVariant as x}from"starknet";import{addAddressPadding as R}from"starknet";import{err as re,ok as se}from"neverthrow";function S(e,t){if(Object.hasOwn(e,"type")&&Object.hasOwn(e,"value"))return{Primitive:{[e.type]:e.value}};if(typeof e=="number")return{Primitive:{U32:e}};if(typeof e=="boolean")return{Primitive:{Bool:e}};if(typeof e=="bigint")return{Primitive:{Felt252:t(e.toString())}};if(typeof e=="string")return{String:e};if(Array.isArray(e))return{List:e.map(r=>S(r,t))};throw new Error(`Unsupported primitive type: ${typeof e}`)}function ce(e,t,r="VariableLen"){return new y().keys(e,t,r)}function de(e){return new y().hashed_keys(e)}function le(e,t,r,s){return new y().where(e,t,r,s)}function pe(e){return new y().compose().and(e)}function me(e){return new y().compose().or(e)}var y=class{clause;constructor(){this.clause={}}keys(e,t,r="VariableLen"){return this.clause={Keys:{keys:t.length===0?[void 0]:t,pattern_matching:r,models:e}},this}hashed_keys(e){let t=e.map((r,s)=>{try{return`0x${BigInt(r).toString(16)}`}catch{throw new Error(`Invalid key value at index ${s}: ${r}. Expected a valid BigNumberish value.`)}});return this.clause={HashedKeys:t},this}where(e,t,r,s){let o=Array.isArray(s)?{List:s.map(i=>S(i,D.encodeShortString))}:S(s,D.encodeShortString);return this.clause={Member:{model:e,member:t,operator:r,value:o}},this}compose(){return new H}build(){if(Object.keys(this.clause).length===0)throw new Error("You cannot build an empty Clause");return this.clause}},H=class{orClauses=[];andClauses=[];or(e){return this.orClauses=e.map(t=>t.build()),this}and(e){return this.andClauses=e.map(t=>t.build()),this}build(){if(this.orClauses.length===0&&this.andClauses.length===0)throw new Error("ComposeClause is empty. Add .or([clause]) or .and([clause])");if(this.orClauses&&this.andClauses.length===0)return{Composite:{operator:"Or",clauses:this.orClauses}};if(this.andClauses&&this.orClauses.length===0)return{Composite:{operator:"And",clauses:this.andClauses}};if(this.andClauses&&this.orClauses)return{Composite:{operator:"And",clauses:[...this.andClauses,{Composite:{operator:"Or",clauses:this.orClauses}}]}};throw new Error("CompositeClause is not properly build")}},A="No signer configured in sdk.init()",h="No identity configured in sdk.init()",ge="Account is undefined",W="Clause has not been defined yet. Use `.withClause()` to do so";function _(e,t,r,s,o){return{types:{StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],...o,[e]:s!==void 0?s:Object.keys(t).map(i=>({name:i,type:typeof t[i]=="bigint"||typeof t[i]=="number"?"felt":"string"}))},primaryType:e,domain:r,message:t}}function M(e){return e instanceof p}function Y(e,t){return t instanceof p&&t.isSome()?new p(C.Some,t.unwrap()):e instanceof p?e.isSome()?new p(C.Some,e.unwrap()):new p(C.None):e}function b(e){return e instanceof v}function J(e,t){if(!b(e)||!b(t))return e;let r=t.activeVariant(),s=t.unwrap();if(r&&s!==void 0){let n={};for(let a in e.variant)n[a]=void 0;return n[r]=s,new v(n)}let o=e.activeVariant(),i=e.unwrap();if(o&&i!==void 0){let n={};for(let a in e.variant)n[a]=void 0;return n[o]=i,new v(n)}return e}function X(e,t){if(M(e)&&M(t))return Y(e,t);if(b(e)&&b(t))return J(e,t);let r={...e};for(let s in t)Object.hasOwn(t,s)&&(t[s]!==null&&typeof t[s]=="object"&&!Array.isArray(t[s])&&s in e&&typeof e[s]=="object"&&!Array.isArray(e[s])?r[s]=X(e[s],t[s]):r[s]=t[s]);return r}function he(e,t,r){let[s,o]=t.split("-");for(let i of r)if(i.entityId===e)return i.models?.[s]?.[o]}function fe(e,t){let[r,s]=e.split("-");for(let o of t)return o.models?.[r]?.[s]}var B={limit:1e3,cursor:void 0,direction:"Forward",order_by:[]},f=class q{constructor(t,r,s){this.limit=t,this.cursor=r,this.direction=s,this.items=[],s||(this.direction="Forward")}items;static fromQuery(t,r){let s=t.getPagination();return new q(s.limit??1e3,r,s.direction)}withItems(t){return this.items=t,this}getItems(){return this.items}getNextQuery(t){let r=t.withLimit(this.limit);return this.cursor&&r.withCursor(this.cursor),r.getPagination().direction!==this.direction&&r.withDirection(this.direction),r}getPreviousQuery(t){let r=t.withLimit(this.limit);return this.cursor&&r.withCursor(this.cursor),r.getPagination().direction===this.direction&&r.withDirection(Z(this.direction)),r}};function Z(e){return e==="Forward"?"Backward":"Forward"}function m(e,t){let r=[];for(let s of e){let o=s.hashed_keys,i=s.models,n={entityId:o,models:{}};for(let a in s.models){let[u,c]=a.split("-");if(!u||!c){t?.logging&&console.warn(`Invalid modelName format: ${a}`);continue}n.models[u]||(n.models[u]={}),n.models[u][c]=U(i[a])}r.push(n),t?.logging&&console.log("Parsed entity:",n)}return t?.logging&&console.log("Parsed result:",r),Object.values(r)}function w(e){switch(e.type){case"primitive":return te(e);case"struct":return U(e.value);case"enum":return e.value.option==="Some"?new O(x.Some,w(e.value.value)):e.value.option==="None"?new O(x.None):ee(e);case"tuple":case"array":return e.value.map(w);default:return e.value}}function ee(e){return e.value.value.type==="tuple"?e.value.option:new z({[e.value.option]:w(e.value.value)})}function te(e){switch(e.type_name){case"u64":return Number.parseInt(e.value,16);case"i256":case"i128":case"u256":case"u128":return BigInt(e.value);default:return e.value}}function U(e){let t=e instanceof Map?Array.from(e.entries()):Object.entries(e);return Object.fromEntries(t.map(([r,s])=>[r,w(s)]))}function P(e){return t=>{try{if(e){let r=m([t]);e({data:r,error:void 0})}}catch(r){e&&e({data:void 0,error:r instanceof Error?r:new Error(String(r))})}}}function d(e,t){return r=>{if(r!==t)try{e({data:r,error:void 0})}catch(s){e({data:void 0,error:s})}}}var k={balance:"0x0000000000000000000000000000000000000000000000000000000000000000",account_address:"0x0",contract_address:"0x0",token_id:"0x0000000000000000000000000000000000000000000000000000000000000000"};function l(e){return e.contractAddresses&&(e.contractAddresses=e.contractAddresses.map(t=>R(t))),e.accountAddresses&&(e.accountAddresses=e.accountAddresses.map(t=>R(t))),{contractAddresses:e.contractAddresses??[],accountAddresses:e.accountAddresses??[],tokenIds:e.tokenIds??[],pagination:e.pagination??B}}async function E(e,t){let{contractAddresses:r,tokenIds:s,pagination:o}=l(t);return await e.getTokens({contract_addresses:r,token_ids:s,pagination:o})}async function I(e,t){let{contractAddresses:r,accountAddresses:s,tokenIds:o,pagination:i}=l(t);return await e.getTokenBalances({contract_addresses:r,account_addresses:s,token_ids:o,pagination:i})}async function ke(e,t){let{contractAddresses:r,accountAddresses:s,tokenIds:o}=l(t);return await e.onTokenBalanceUpdated(r??[],s??[],o??[],d(t.callback,k))}async function N(e,t){let{subscription:r,contractAddresses:s,accountAddresses:o,tokenIds:i}=t;return await e.updateTokenBalanceSubscription(r,s??[],o??[],i??[])}async function K(e,t){let{contractAddresses:r,accountAddresses:s,tokenIds:o,callback:i}=t,n=await I(e,{contractAddresses:r??[],accountAddresses:s??[],tokenIds:o??[]}),a=await e.onTokenBalanceUpdated(r??[],s??[],o??[],d(i,k));return[n,a]}var T={contract_address:"0x0",token_id:"0x0000000000000000000000000000000000000000000000000000000000000000",name:"",symbol:"",decimals:0,metadata:""};async function Te(e,t){let{contractAddresses:r,tokenIds:s,callback:o}=l(t);return await e.onTokenUpdated(r??[],s??[],d(o,T))}async function j(e,t){let{contractAddresses:r,tokenIds:s,callback:o}=t,i=await E(e,{contractAddresses:r??[],tokenIds:s??[]}),n=await e.onTokenUpdated(r??[],s??[],d(o,T));return[i,n]}var Q=()=>({pagination:{limit:100,cursor:void 0,direction:"Forward",order_by:[]},clause:void 0,no_hashed_keys:!0,models:[],historical:!1}),ie=class G{query;constructor(t){this.query={...Q(),...t}}withLimit(t){return this.query.pagination.limit=t,this}withOffset(){return this}withCursor(t){return this.query.pagination.cursor=t,this}withDirection(t){return this.query.pagination.direction=t,this}withClause(t){return this.query.clause=t,this}includeHashedKeys(){return this.query.no_hashed_keys=!1,this}addOrderBy(t,r){return this.query.pagination.order_by.push({field:t,direction:r}),this}withOrderBy(t){return this.query.pagination.order_by=t,this}addEntityModel(t){return this.query.models.push(t),this}withEntityModels(t){return this.query.models=t,this}build(){return this.query}static withPagination(t,r,s){return new G().withLimit(r).withCursor(t).withDirection(s)}getClause(){return this.query.clause?se(this.query.clause):re(W)}getPagination(){return this.query.pagination}isHistorical(){return this.query.historical}},Se=class extends ie{constructor(e){super({...Q(),...e,historical:!0})}};import{ok as ne}from"neverthrow";import{ToriiGrpcClient as ae}from"@dojoengine/grpc";function F({client:e,config:t,sendMessage:r,sendMessageBatch:s}){let o=new ae({toriiUrl:t.client.toriiUrl??"http://localhost:8080",worldAddress:t.client.worldAddress});return{client:e,subscribeEntityQuery:async({query:i,callback:n})=>{let a=i.build(),u=await e.getEntities(a),c=m(u.items);return[f.fromQuery(i,u.next_cursor).withItems(c),await e.onEntityUpdated(a.clause,P(n))]},subscribeEventQuery:async({query:i,callback:n})=>{let a=i.build(),u=await o.getEventMessages(a),c=m(u.items);return[f.fromQuery(i,u.next_cursor).withItems(c),await o.onEventMessageUpdated(a.clause,P(n))]},subscribeTokenBalance:async i=>await K(e,i),getEntities:async({query:i})=>{let n=i.build(),a=await e.getEntities(n);return f.fromQuery(i,a.next_cursor).withItems(m(a.items))},getEventMessages:async({query:i})=>{let n=i.build(),a=await e.getEventMessages(n);return f.fromQuery(i,a.next_cursor).withItems(m(a.items))},generateTypedData:(i,n,a,u)=>_(i,n,t.domain,a,u),sendMessage:r,sendMessageBatch:s,sendSignedMessageBatch:async i=>{try{return ne(await e.publishMessageBatch(i))}catch(n){throw console.error("Failed to send signed message batch:",n),n}},getTokens:async i=>await E(e,i),getTokenBalances:async i=>await I(e,i),onTokenBalanceUpdated:async i=>{let{contractAddresses:n,accountAddresses:a,tokenIds:u}=l(i);return await o.onTokenBalanceUpdated(n??[],a??[],u??[],d(i.callback,k))},onTokenUpdated:async i=>{let{contractAddresses:n,tokenIds:a}=l(i);return await o.onTokenUpdated(n??[],a??[],d(i.callback,T))},updateTokenBalanceSubscription:async i=>await N(e,i),updateEntitySubscription:async(i,n)=>await e.updateEntitySubscription(i,n),updateEventMessageSubscription:async(i,n)=>await e.updateEventMessageSubscription(i,n),getControllers:async(i,n,a=B)=>await e.getControllers({contract_addresses:i,usernames:n,pagination:a}),subscribeToken:async i=>await j(e,i)}}async function Oe(e){let t=await e();process.on("SIGTERM",()=>{for(let r of t)r.free();process.exit(0)}),process.on("SIGINT",()=>{for(let r of t)r.free();process.exit(0)})}var oe={toriiUrl:"http://localhost:8080"};async function Ue(e){let t={...oe,...e.client},r=await new V.ToriiClient(t);return F({client:r,config:e,sendMessage:async(i,n)=>{if(!e.signer)return g(A);if(!e.identity)return g(h);if(!n)return g(h);try{let a=await n.signMessage(i),u=JSON.stringify(i);return L(await r.publishMessage({message:u,signature:Array.isArray(a)?a:[a.r.toString(),a.s.toString()]}))}catch(a){throw console.error("Failed to send message:",a),a}},sendMessageBatch:async(i,n)=>{if(!e.signer)return g(A);if(!e.identity)return g(h);if(!n)return g(h);try{let a=[];for(let u of i){let c=await n.signMessage(u),$=JSON.stringify(u);a.push({message:$,signature:Array.isArray(c)?c:[c.r.toString(),c.s.toString()]})}return L(await r.publishMessageBatch(a))}catch(a){throw console.error("Failed to send message batch:",a),a}}})}export{pe as AndComposeClause,y as ClauseBuilder,de as HashedKeysClause,Se as HistoricalToriiQueryBuilder,ce as KeysClause,le as MemberClause,ge as NO_ACCOUNT,h as NO_IDENTITY,A as NO_SIGNER,me as OrComposeClause,f as Pagination,ie as ToriiQueryBuilder,W as UNDEFINED_CLAUSE,S as convertToPrimitive,Oe as createWorker,X as deepMerge,oe as defaultClientConfig,T as defaultToken,k as defaultTokenBalance,B as defaultToriiPagination,_ as generateTypedData,fe as getModel,he as getModelByEntityId,I as getTokenBalances,E as getTokens,Ue as init,b as isCairoCustomEnum,M as isCairoOption,J as mergeCairoCustomEnum,Y as mergeCairoOption,ke as onTokenBalanceUpdated,Te as onTokenUpdated,m as parseEntities,l as parseTokenRequest,d as safeCallback,P as subscribeQueryModelCallback,j as subscribeToken,K as subscribeTokenBalance,N as updateTokenBalanceSubscription}; //# sourceMappingURL=index.js.map