@dojoengine/sdk
Version:
Dojo SDK: Build onchain and provable apps faster
2 lines • 9.7 kB
JavaScript
import*as w from"@dojoengine/torii-wasm";import{err as G,ok as V}from"neverthrow";var h="Account is undefined",B="Clause has not been defined yet. Use `.withClause()` to do so";function x(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 P}from"starknet";function y(e,t){return r=>{if(r!==t)try{e({data:r,error:void 0})}catch(n){e({data:void 0,error:n})}}}var M={balance:"0x0000000000000000000000000000000000000000000000000000000000000000",account_address:"0x0",contract_address:"0x0",token_id:"0x0000000000000000000000000000000000000000000000000000000000000000"};function m(e){return e.contractAddresses&&(e.contractAddresses=e.contractAddresses.map(t=>P(t))),e.accountAddresses&&(e.accountAddresses=e.accountAddresses.map(t=>P(t))),e}async function f(e,t){let{contractAddresses:r,tokenIds:n}=m(t);return await e.getTokens(r??[],n??[])}async function b(e,t){let{contractAddresses:r,accountAddresses:n,tokenIds:i}=m(t);return await e.getTokenBalances(r??[],n??[],i??[])}function E(e,t){let{contractAddresses:r,accountAddresses:n,tokenIds:i,callback:s}=m(t);return e.onTokenBalanceUpdated(r??[],n??[],i??[],y(s,M))}async function R(e,t){let{subscription:r,contractAddresses:n,accountAddresses:i,tokenIds:s}=t;return await e.updateTokenBalanceSubscription(r,n??[],i??[],s??[])}async function D(e,t){let{contractAddresses:r,accountAddresses:n,tokenIds:i,callback:s}=t,o=await b(e,{contractAddresses:r??[],accountAddresses:n??[],tokenIds:i??[]}),a=e.onTokenBalanceUpdated(r??[],n??[],i??[],y(s,M));return[o,a]}var A={contract_address:"0x0",token_id:"0x0000000000000000000000000000000000000000000000000000000000000000",name:"",symbol:"",decimals:0,metadata:""};function O(e,t){let{contractAddresses:r,tokenIds:n,callback:i}=m(t);return e.onTokenUpdated(r??[],n??[],y(i,A))}async function v(e,t){let{contractAddresses:r,tokenIds:n,callback:i}=t,s=await f(e,{contractAddresses:r??[],tokenIds:n??[]}),o=e.onTokenUpdated(r??[],n??[],y(i,A));return[s,o]}import{CairoCustomEnum as F,CairoOption as Q,CairoOptionVariant as I}from"starknet";function d(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]=q(s[a])}r.push(o),t?.logging&&console.log("Parsed entity:",o)}return t?.logging&&console.log("Parsed result:",r),Object.values(r)}function T(e){switch(e.type){case"primitive":return $(e);case"struct":return q(e.value);case"enum":return e.value.option==="Some"?new Q(I.Some,T(e.value.value)):e.value.option==="None"?new Q(I.None):L(e);case"tuple":case"array":return e.value.map(T);default:return e.value}}function L(e){return e.value.value.type==="tuple"?e.value.option:new F({[e.value.option]:T(e.value.value)})}function $(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 q(e){let t=e instanceof Map?Array.from(e.entries()):Object.entries(e);return Object.fromEntries(t.map(([r,n])=>[r,T(n)]))}function k(e){return t=>{try{if(e){let r=d([t]);e({data:r,error:void 0})}}catch(r){e&&e({data:void 0,error:r instanceof Error?r:new Error(String(r))})}}}var p=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(z(this.direction)),r}};function z(e){return e==="Forward"?"Backward":"Forward"}function K({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=d(a.items);return[p.fromQuery(i,a.next_cursor).withItems(u),e.onEntityUpdated(o.clause,k(s))]},subscribeEventQuery:async({query:i,callback:s})=>{let o=i.build(),a=await e.getEventMessages(o),u=d(a.items);return[p.fromQuery(i,a.next_cursor).withItems(u),e.onEventMessageUpdated(o.clause,k(s))]},subscribeTokenBalance:async i=>await D(e,i),getEntities:async({query:i})=>{let s=i.build(),o=await e.getEntities(s);return p.fromQuery(i,o.next_cursor).withItems(d(o.items))},getEventMessages:async({query:i})=>{let s=i.build(),o=await e.getEventMessages(s);return p.fromQuery(i,o.next_cursor).withItems(d(o.items))},generateTypedData:(i,s,o,a)=>x(i,s,t.domain,o,a),sendMessage:r,sendMessageBatch:n,getTokens:async i=>await f(e,i),getTokenBalances:async i=>await b(e,i),onTokenBalanceUpdated:i=>E(e,i),onTokenUpdated:i=>O(e,i),updateTokenBalanceSubscription:async i=>await R(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 v(e,i)}}function g(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=>g(r,t))};throw new Error(`Unsupported primitive type: ${typeof e}`)}import{shortString as U}from"starknet";function Te(e,t,r="VariableLen"){return new l().keys(e,t,r)}function ge(e){return new l().hashed_keys(e)}function he(e,t,r,n){return new l().where(e,t,r,n)}function fe(e){return new l().compose().and(e)}function be(e){return new l().compose().or(e)}var l=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=>g(o,U.encodeShortString))}:g(i,U.encodeShortString);return this.clause={Member:{model:t,member:r,operator:n,value:s}},this}compose(){return new C}build(){if(Object.keys(this.clause).length===0)throw new Error("You cannot build an empty Clause");return this.clause}},C=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")}};import{err as H,ok as J}from"neverthrow";var _=()=>({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={..._(),...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?J(this.query.clause):H(B)}getPagination(){return this.query.pagination}},N=class extends S{constructor(t){super({..._(),...t,historical:!0})}};async function Me(e){return await new w.ToriiClient(e)}var Y={toriiUrl:"http://localhost:8080"};async function Ee(e){let t={...Y,...e.client},r=await new w.ToriiClient(t);return K({client:r,config:e,signMessage:async(s,o)=>{if(!o)return G(h);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(!o)return G(h);try{let a=[];for(let u of s){let c=await o.signMessage(u),j=JSON.stringify(u);a.push({message:j,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{d as a,Te as b,ge as c,he as d,fe as e,be as f,l as g,S as h,N as i,Me as j,Y as k,Ee as l};
//# sourceMappingURL=chunk-7M7I5ZKC.js.map