@dojoengine/sdk
Version:
Dojo SDK: Build onchain and provable apps faster
2 lines • 10.3 kB
JavaScript
import*as j from"@dojoengine/torii-wasm/node";import{err as y,ok as V}from"neverthrow";var b="No signer configured in sdk.init()",l="No identity configured in sdk.init()";var B="Clause has not been defined yet. Use `.withClause()` to do so";import{err as F,ok as L}from"neverthrow";var M=()=>({pagination:{limit:100,cursor:void 0,direction:"Forward",order_by:[]},clause:void 0,no_hashed_keys:!0,models:[],historical:!1}),S=class e{query;constructor(t){this.query={...M(),...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,n){return this.query.pagination.order_by.push({model:t,member:r,direction:n}),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,n){return new e().withLimit(r).withCursor(t).withDirection(n)}getClause(){return this.query.clause?L(this.query.clause):F(B)}getPagination(){return this.query.pagination}},P=class extends S{constructor(t){super({...M(),...t,historical:!0})}};function T(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=>T(r,t))};throw new Error(`Unsupported primitive type: ${typeof e}`)}import{shortString as E}from"starknet";function se(e,t,r="VariableLen"){return new d().keys(e,t,r)}function oe(e){return new d().hashed_keys(e)}function ae(e,t,r,n){return new d().where(e,t,r,n)}function ue(e){return new d().compose().and(e)}function ce(e){return new d().compose().or(e)}var d=class{clause;constructor(){this.clause={}}keys(t,r,n="VariableLen"){return this.clause={Keys:{keys:r.length===0?[void 0]:r,pattern_matching:n,models:t}},this}hashed_keys(t){let r=t.map((n,i)=>{try{return`0x${BigInt(n).toString(16)}`}catch{throw new Error(`Invalid key value at index ${i}: ${n}. Expected a valid BigNumberish value.`)}});return this.clause={HashedKeys:r},this}where(t,r,n,i){let s=Array.isArray(i)?{List:i.map(o=>T(o,E.encodeShortString))}:T(i,E.encodeShortString);return this.clause={Member:{model:t,member:r,operator:n,value:s}},this}compose(){return new k}build(){if(Object.keys(this.clause).length===0)throw new Error("You cannot build an empty Clause");return this.clause}},k=class{orClauses=[];andClauses=[];or(t){return this.orClauses=t.map(r=>r.build()),this}and(t){return this.andClauses=t.map(r=>r.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")}};async function pe(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)})}function ye(e,t,r){let[n,i]=t.split("-");for(let s of r)if(s.entityId===e)return s.models?.[n]?.[i]}function le(e,t){let[r,n]=e.split("-");for(let i of t)return i.models?.[r]?.[n]}function R(e,t,r,n,i){return{types:{StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],...i,[e]:n!==void 0?n:Object.keys(t).map(s=>({name:s,type:typeof t[s]=="bigint"||typeof t[s]=="number"?"felt":"string"}))},primaryType:e,domain:r,message:t}}import{addAddressPadding as D}from"starknet";function f(e,t){return r=>{if(r!==t)try{e({data:r,error:void 0})}catch(n){e({data:void 0,error:n})}}}var A={balance:"0x0000000000000000000000000000000000000000000000000000000000000000",account_address:"0x0",contract_address:"0x0",token_id:"0x0000000000000000000000000000000000000000000000000000000000000000"};function g(e){return e.contractAddresses&&(e.contractAddresses=e.contractAddresses.map(t=>D(t))),e.accountAddresses&&(e.accountAddresses=e.accountAddresses.map(t=>D(t))),e}async function C(e,t){let{contractAddresses:r,tokenIds:n}=g(t);return await e.getTokens(r??[],n??[])}async function x(e,t){let{contractAddresses:r,accountAddresses:n,tokenIds:i}=g(t);return await e.getTokenBalances(r??[],n??[],i??[])}function N(e,t){let{contractAddresses:r,accountAddresses:n,tokenIds:i,callback:s}=g(t);return e.onTokenBalanceUpdated(r??[],n??[],i??[],f(s,A))}async function I(e,t){let{subscription:r,contractAddresses:n,accountAddresses:i,tokenIds:s}=t;return await e.updateTokenBalanceSubscription(r,n??[],i??[],s??[])}async function v(e,t){let{contractAddresses:r,accountAddresses:n,tokenIds:i,callback:s}=t,o=await x(e,{contractAddresses:r??[],accountAddresses:n??[],tokenIds:i??[]}),a=e.onTokenBalanceUpdated(r??[],n??[],i??[],f(s,A));return[o,a]}var O={contract_address:"0x0",token_id:"0x0000000000000000000000000000000000000000000000000000000000000000",name:"",symbol:"",decimals:0,metadata:""};function Q(e,t){let{contractAddresses:r,tokenIds:n,callback:i}=g(t);return e.onTokenUpdated(r??[],n??[],f(i,O))}async function q(e,t){let{contractAddresses:r,tokenIds:n,callback:i}=t,s=await C(e,{contractAddresses:r??[],tokenIds:n??[]}),o=e.onTokenUpdated(r??[],n??[],f(i,O));return[s,o]}import{CairoCustomEnum as z,CairoOption as K,CairoOptionVariant as U}from"starknet";function p(e,t){let r=[];for(let n of e){let i=n.hashed_keys,s=n.models,o={entityId:i,models:{}};for(let a in n.models){let[u,c]=a.split("-");if(!u||!c){t?.logging&&console.warn(`Invalid modelName format: ${a}`);continue}o.models[u]||(o.models[u]={}),o.models[u][c]=_(s[a])}r.push(o),t?.logging&&console.log("Parsed entity:",o)}return t?.logging&&console.log("Parsed result:",r),Object.values(r)}function h(e){switch(e.type){case"primitive":return W(e);case"struct":return _(e.value);case"enum":return e.value.option==="Some"?new K(U.Some,h(e.value.value)):e.value.option==="None"?new K(U.None):H(e);case"tuple":case"array":return e.value.map(h);default:return e.value}}function H(e){return e.value.value.type==="tuple"?e.value.option:new z({[e.value.option]:h(e.value.value)})}function W(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 _(e){let t=e instanceof Map?Array.from(e.entries()):Object.entries(e);return Object.fromEntries(t.map(([r,n])=>[r,h(n)]))}function w(e){return t=>{try{if(e){let r=p([t]);e({data:r,error:void 0})}}catch(r){e&&e({data:void 0,error:r instanceof Error?r:new Error(String(r))})}}}var m=class e{constructor(t,r,n){this.limit=t;this.cursor=r;this.direction=n;this.items=[],n||(this.direction="Forward")}items;static fromQuery(t,r){let n=t.getPagination();return new e(n.limit,r,n.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(Y(this.direction)),r}};function Y(e){return e==="Forward"?"Backward":"Forward"}function G({client:e,config:t,signMessage:r,signMessageBatch:n}){return{client:e,subscribeEntityQuery:async({query:i,callback:s})=>{let o=i.build(),a=await e.getEntities(o),u=p(a.items);return[m.fromQuery(i,a.next_cursor).withItems(u),e.onEntityUpdated(o.clause,w(s))]},subscribeEventQuery:async({query:i,callback:s})=>{let o=i.build(),a=await e.getEventMessages(o),u=p(a.items);return[m.fromQuery(i,a.next_cursor).withItems(u),e.onEventMessageUpdated(o.clause,w(s))]},subscribeTokenBalance:async i=>await v(e,i),getEntities:async({query:i})=>{let s=i.build(),o=await e.getEntities(s);return m.fromQuery(i,o.next_cursor).withItems(p(o.items))},getEventMessages:async({query:i})=>{let s=i.build(),o=await e.getEventMessages(s);return m.fromQuery(i,o.next_cursor).withItems(p(o.items))},generateTypedData:(i,s,o,a)=>R(i,s,t.domain,o,a),sendMessage:r,sendMessageBatch:n,getTokens:async i=>await C(e,i),getTokenBalances:async i=>await x(e,i),onTokenBalanceUpdated:i=>N(e,i),onTokenUpdated:i=>Q(e,i),updateTokenBalanceSubscription:async i=>await I(e,i),updateEntitySubscription:async(i,s)=>await e.updateEntitySubscription(i,s),updateEventMessageSubscription:async(i,s)=>await e.updateEventMessageSubscription(i,s),getControllers:async i=>await e.getControllers(i),subscribeToken:async i=>await q(e,i)}}var J={toriiUrl:"http://localhost:8080"};async function Ie(e){let t={...J,...e.client},r=await new j.ToriiClient(t);return G({client:r,config:e,signMessage:async(s,o)=>{if(!e.signer)return y(b);if(!e.identity)return y(l);if(!o)return y(l);try{let a=await o.signMessage(s),u=JSON.stringify(s);return V(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}},signMessageBatch:async(s,o)=>{if(!e.signer)return y(b);if(!e.identity)return y(l);if(!o)return y(l);try{let a=[];for(let u of s){let c=await o.signMessage(u),$=JSON.stringify(u);a.push({message:$,signature:Array.isArray(c)?c:[c.r.toString(),c.s.toString()]})}return V(await r.publishMessageBatch(a))}catch(a){throw console.error("Failed to send message batch:",a),a}}})}export{ue as AndComposeClause,d as ClauseBuilder,oe as HashedKeysClause,P as HistoricalToriiQueryBuilder,se as KeysClause,ae as MemberClause,ce as OrComposeClause,S as ToriiQueryBuilder,pe as createWorker,J as defaultClientConfig,le as getModel,ye as getModelByEntityId,Ie as init};
//# sourceMappingURL=index.js.map