@clarigen/core 4.1.4 → 4.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,901 @@
1
- const e=require(`./deployment-DN-sbX_m.cjs`);let t=require(`@stacks/transactions`),n=require(`@scure/base`),r=require(`@stacks/blockchain-api-client`),i=require(`@stacks/network`);const a=`ST000000000000000000002AMW42H`,o=`SP000000000000000000002Q6VF78`,s=(e,t)=>{let n=typeof e==`string`?e:String(e);if(/^[A-Z_]+$/.test(n))return n;let[r,...i]=n.replace(`!`,`_x`).replace(`?`,`_q`).split(`-`),a=`${t?r[0].toUpperCase():r[0].toLowerCase()}${r.slice(1)}`;return i.forEach(e=>{let t=e[0].toUpperCase()+e.slice(1);a+=t}),a};function c(e){let t=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g);return t?t.join(`-`).toLowerCase():e}function l(e,t=!0){let n=e.split(`.`)[1];return t?s(n):n}const u=e=>{let t=e.split(`/`).at(-1),[n]=(t==null?void 0:t.split(`.`))??[];return n},ee=e=>`${e.address}.${e.name}`,te=e=>{let n=u(e.contractFile);return(0,t.contractPrincipalCV)(e.address,n)};function ne(e,t){return`${t?o:a}.${e}`}function re(e){return n.hex.encode(e)}function d(e){return n.hex.decode(e)}function f(e){let t=Array.from(e);return String.fromCharCode.apply(null,t)}const p=e=>typeof e==`number`;function ie(e){let{constants:t}=e,n={};for(let e in t)if(e.toLowerCase().startsWith(`err`)){let r=t[e];typeof r==`object`&&r&&`isOk`in r&&!r.isOk&&`value`in r?n[e]=r.value:n[e]=r}return n}function ae(e){let{contracts:t}=e,n={};for(let e in t)n[e]=ie(t[e]);return n}let oe=function(e){return e.ContractEvent=`contract_event`,e.StxTransferEvent=`stx_transfer_event`,e.StxMintEvent=`stx_mint_event`,e.StxBurnEvent=`stx_burn_event`,e.StxLockEvent=`stx_lock_event`,e.NftTransferEvent=`nft_transfer_event`,e.NftMintEvent=`nft_mint_event`,e.NftBurnEvent=`nft_burn_event`,e.FtTransferEvent=`ft_transfer_event`,e.FtMintEvent=`ft_mint_event`,e.FtBurnEvent=`ft_burn_event`,e}({});function se(e,t){return e.filter(e=>e.type===t)}function ce(e,t={}){let n={};for(let r in e){let i=e[r],a=t.deployerAddress||i.address;n[r]={identifier:`${a}.${i.name}`,contract:i.contract(a,i.name)}}return n}function m(e){return{isOk:!0,value:e}}function h(e){return{isOk:!1,value:e}}function le(e){return typeof e==`object`&&!!e&&`isOk`in e}function g(e){return e.value}function _(e,n=!1){switch(e.type){case t.ClarityType.BoolTrue:return!0;case t.ClarityType.BoolFalse:return!1;case t.ClarityType.Int:case t.ClarityType.UInt:return e.value;case t.ClarityType.Buffer:return d(e.value);case t.ClarityType.OptionalNone:return null;case t.ClarityType.OptionalSome:return _(e.value,!0);case t.ClarityType.ResponseErr:return n?h(_(e.value,!0)):_(e.value,!0);case t.ClarityType.ResponseOk:return n?m(_(e.value,!0)):_(e.value,!0);case t.ClarityType.PrincipalStandard:case t.ClarityType.PrincipalContract:return g(e);case t.ClarityType.List:return e.value.map(e=>_(e,!0));case t.ClarityType.Tuple:return Object.entries(e.value).reduce((e,[t,n])=>{let r=s(t);return{...e,[r]:_(n,!0)}},{});case t.ClarityType.StringASCII:return e.value;case t.ClarityType.StringUTF8:return e.value}}function ue(e,n=!1){return _((0,t.hexToCV)(e),n)}function v(e){if(!(typeof e==`bigint`||typeof e==`number`||typeof e==`string`))throw Error(`Invalid input type for integer`);return BigInt(e)}const y=e=>typeof e==`string`,b=e=>e.buffer!==void 0,x=e=>e[`string-ascii`]!==void 0,S=e=>e[`string-utf8`]!==void 0,C=e=>e.response!==void 0,w=e=>e.optional!==void 0,T=e=>e.tuple!==void 0,E=e=>e.list!==void 0,de=e=>e===`trait_reference`;function D(e,n){if(T(n)){if(typeof e!=`object`)throw Error(`Invalid tuple input`);let r={};return n.tuple.forEach(t=>{let n=e[N(t.name,e)];r[t.name]=D(n,t.type)}),(0,t.tupleCV)(r)}if(E(n))return(0,t.listCV)(e.map(e=>D(e,n.list.type)));if(w(n))return e===null?(0,t.noneCV)():(0,t.someCV)(D(e,n.optional));if(x(n)){if(typeof e!=`string`)throw Error(`Invalid string-ascii input`);return(0,t.stringAsciiCV)(e)}if(S(n)){if(typeof e!=`string`)throw Error(`Invalid string-ascii input`);return(0,t.stringUtf8CV)(e)}if(n===`bool`)return(0,t.parseToCV)(typeof e==`boolean`?e.toString():e,n);if(n===`uint128`)return(0,t.uintCV)(v(e).toString());if(n===`int128`)return(0,t.intCV)(v(e).toString());if(n===`trait_reference`){if(typeof e!=`string`)throw Error(`Invalid input for trait_reference`);let[n,r]=e.split(`.`);return(0,t.contractPrincipalCV)(n,r)}return b(n)?(0,t.bufferCV)(e):(0,t.parseToCV)(e,n)}function O(e,n){let r=typeof n==`object`?n:{encoding:n,indent:void 0,depth:void 0},i=r.encoding??`hex`,a=r.indent,o=r.depth??0;switch(e.type){case t.ClarityType.BoolTrue:return`true`;case t.ClarityType.BoolFalse:return`false`;case t.ClarityType.Int:return e.value.toString();case t.ClarityType.UInt:return`u${e.value.toString()}`;case t.ClarityType.Buffer:if(i===`tryAscii`){let t=f(d(e.value));if(/[ -~]/.test(t))return JSON.stringify(t)}return`0x${e.value}`;case t.ClarityType.OptionalNone:return`none`;case t.ClarityType.OptionalSome:return`(some ${O(e.value,r)})`;case t.ClarityType.ResponseErr:return`(err ${O(e.value,r)})`;case t.ClarityType.ResponseOk:return`(ok ${O(e.value,r)})`;case t.ClarityType.PrincipalStandard:case t.ClarityType.PrincipalContract:return`'${g(e)}`;case t.ClarityType.List:return`(list ${e.value.map(e=>O(e,r)).join(` `)})`;case t.ClarityType.Tuple:{let t=Object.keys(e.value);if(a===void 0||t.length===0)return`{ ${t.map(t=>`${t}: ${O(e.value[t],r)}`).join(`, `)} }`;let n=` `.repeat((o+1)*a),i=` `.repeat(o*a);return`{\n${t.map(t=>`${n}${t}: ${O(e.value[t],{...r,depth:o+1})}`).join(`,
2
- `)}\n${i}}`}case t.ClarityType.StringASCII:return`"${e.value}"`;case t.ClarityType.StringUTF8:return`u"${e.value}"`}}function k(e,n=!1){switch(e.type){case t.ClarityType.BoolTrue:return!0;case t.ClarityType.BoolFalse:return!1;case t.ClarityType.Int:case t.ClarityType.UInt:return`${e.value}`;case t.ClarityType.Buffer:return e.value;case t.ClarityType.OptionalNone:return null;case t.ClarityType.OptionalSome:return k(e.value);case t.ClarityType.ResponseErr:return n?h(k(e.value)):k(e.value);case t.ClarityType.ResponseOk:return n?m(k(e.value)):k(e.value);case t.ClarityType.PrincipalStandard:case t.ClarityType.PrincipalContract:return g(e);case t.ClarityType.List:return e.value.map(e=>k(e));case t.ClarityType.Tuple:return Object.entries(e.value).reduce((e,[t,n])=>{let r=s(t);return{...e,[r]:k(n)}},{});case t.ClarityType.StringASCII:return e.value;case t.ClarityType.StringUTF8:return e.value}}function A(e,t){return e.args.map(e=>{let n=t[N(e.name,t)];return D(n,e.type)})}function j(e,t){return t.map((t,n)=>D(t,e.args[n].type))}function M(e,t){if(t.length===0)return[];let[n]=t;if(t.length===1&&e.args.length!==1)return A(e,n);if(typeof n==`object`&&!Array.isArray(n)&&n!==null)try{let t=!0;if(e.args.forEach(e=>{try{N(e.name,n)}catch{t=!1}}),t)return A(e,n)}catch{}return j(e,t)}function N(e,t){let n=Object.keys(t).find(t=>{let n=e===t,r=e===c(t);return n||r});if(!n)throw Error(`Error encoding JS tuple: ${e} not found in input.`);return n}function P(e){if(e.isOk)return e.value;throw Error(`Expected OK, received error: ${String(e.value)}`)}function F(e){if(!e.isOk)return e.value;throw Error(`Expected Err, received ok: ${String(e.value)}`)}function I(e){if(y(e))return e===`int128`?`int`:e===`uint128`?`uint`:e;if(b(e))return`(buff ${e.buffer.length})`;if(x(e))return`(string-ascii ${e[`string-ascii`].length})`;if(S(e))return`(string-utf8 ${e[`string-utf8`].length})`;if(C(e))return`(response ${I(e.response.ok)} ${I(e.response.error)})`;if(w(e))return`(optional ${I(e.optional)})`;if(T(e))return`{ ${e.tuple.map(e=>`${e.name}: ${I(e.type)}`).join(`, `)} }`;if(E(e))return`(list ${e.list.length} ${I(e.list.type)})`;throw Error(`Type string unsupported for Clarity type: ${JSON.stringify(e)}`)}const fe=[`devnet`,`simnet`,`testnet`,`mainnet`];function pe(e,t){let n=[];return Object.entries(e.contracts).forEach(([r,i])=>{let a=e.deployments[r][t];return a&&n.push([r,R(i,a)]),!1}),Object.fromEntries(n)}function me(e,t){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,R(n,`${t}.${n.contractName}`)]))}function L(e,t){return Object.fromEntries(Object.entries(e.functions).map(([n,r])=>[n,Object.assign((...n)=>{let i=M(r,n),[a,o]=t.split(`.`);return{functionArgs:i,contractAddress:a,contractName:o,function:r,functionName:r.name,nativeArgs:n,contractAbi:e}},{abi:r})]))}function R(e,t){let n={...e};return{...L(e,t),...n,identifier:t}}function he(t,n){let r={};return e.n(n.plan.batches).forEach(n=>{let i=e.a(n),[a,o]=i.split(`.`),c=s(o),l=t[c],u=t[c];if(u===void 0)throw Error(`Clarigen error: mismatch for contract '${c}'`);r[c]=u,u.contractFile=e.i(n),u.identifier=i,Object.keys(t[c].functions).forEach(e=>{let t=e;u[t]=((...e)=>{let n=l.functions[t];return{functionArgs:M(n,e),contractAddress:a,contractName:u.contractName,function:n,nativeArgs:e}})})}),r}function z(e,t){return{key:t,keyCV:D(t,e.key),map:e}}function B(e,t={}){let n={...t};return e&&(n[`x-api-key`]=e),n}function ge(e,t,n){return new r.SmartContractsApi(new r.Configuration({basePath:e,headers:B(t,n)}))}function _e(e){return`${e}/v2`}const ve=(e,t)=>{try{let n=new URL(e);return Object.keys(t).forEach(e=>{let r=t[e];if(r){if(Array.isArray(r))return r.length===0?void 0:n.searchParams.set(`${e}[]`,ye(e,r));if(typeof r==`boolean`||p(r))return n.searchParams.set(e,String(r));n.searchParams.set(e,r)}}),n.toString()}catch(t){return console.error(`generateUrl`),console.error(t),e}},ye=(e,t)=>t!=null&&t.length?`${t.map((t,n)=>`${n>0?encodeURIComponent(`${e}[]`):``}=${encodeURIComponent(t)}`).join(`&`)}`:``;function V(e){if(e.okay)return(0,t.hexToCV)(e.result);throw Error(e.cause)}async function H(e){let{contractAddress:n,functionArgs:r,senderAddress:i=n,url:a}=e;return V(await ge(a,e.apiKey,e.headers).callReadOnlyFunction({...e,readOnlyFunctionArgs:{sender:i,arguments:r.map(e=>typeof e==`string`?e:(0,t.cvToHex)(e))}}))}function U(e){return typeof e==`object`&&!!e&&`isNone`in e&&typeof e.isNone==`boolean`}function W(e){return typeof e==`object`&&!!e&&`isOk`in e&&typeof e.isOk==`boolean`}function G(e,t){if(w(t))return U(e)?e.isNone?null:G(e.value,t.optional):e;if(b(t))return typeof e==`string`?d(e.startsWith(`0x`)?e.slice(2):e):e;if(T(t)){if(typeof e!=`object`||!e)return e;let n={};for(let r of t.tuple){let t=e[r.name];n[r.name]=G(t,r.type)}return n}return E(t)&&Array.isArray(e)?e.map(e=>G(e,t.list.type)):e}function K(e,n){if(C(n)){if(!W(e))throw Error(`Response type requires { isOk: boolean, value: unknown } form value`);let r=e.isOk?n.response.ok:n.response.error,i=K(e.isOk?e.ok??e.value:e.err??e.value,r);return e.isOk?(0,t.responseOkCV)(i):(0,t.responseErrorCV)(i)}return D(G(e,n),n)}function q(e,t){if(e===void 0||e===``)return w(t)?{isNone:!0,value:null}:E(t)?[]:T(t)?{}:y(t)&&t===`bool`?!1:``;if(t===`principal`&&e.startsWith(`'`))return e.slice(1);if(w(t)||E(t)||T(t)||C(t))try{return JSON.parse(e)}catch{return e}return y(t)&&t===`bool`?e===`true`:e}function be(e,t){return t.map(t=>{let n=e[t.name];return K(q(Array.isArray(n)?n[0]:n,t.type),t.type)})}function J(e){if(e.latest!==!1)return e.latest||e.tip===void 0?`latest`:e.tip}async function Y(e,t){let n=J(t),r=await H({contractAddress:e.contractAddress,contractName:e.contractName,functionName:e.functionName,functionArgs:e.functionArgs,tip:n,url:X(t),apiKey:t.apiKey,headers:t.headers});return t.json?k(r):_(r,!0)}async function xe(e,t){return P(await Y(e,t))}async function Se(e,t){return F(await Y(e,t))}function X(e){return(0,i.networkFrom)(e.network).client.baseUrl}async function Ce(e,n,r,i){let a=z(n,r),o=JSON.stringify((0,t.cvToHex)(a.keyCV)),[s,c]=e.split(`.`),l=ve(`${_e(X(i))}/map_entry/${s}/${c}/${a.map.name}`,{proof:0,tip:J(i)});return _((0,t.hexToCV)((await(await fetch(l,{method:`POST`,body:o,headers:{"Content-Type":`application/json`,Accept:`application/json`,...B(i.apiKey,i.headers)}})).json()).data),!0)}async function we(e,n){let r=n.network,i=await(0,t.broadcastTransaction)({transaction:e,network:r});if(`error`in i)throw Error(`Error broadcasting tx: ${i.error} - ${i.reason} - ${JSON.stringify(`reason_data`in i?i.reason_data:void 0)}`);return{txId:i.txid,stacksTransaction:e}}var Te=class{network;constructor(e,t,n){this.apiKey=t,this.headers=n,this.network=e}roOptions(e){return{network:this.network,apiKey:this.apiKey,headers:this.headers,...e}}ro(e,t){return Y(e,this.roOptions(t||{}))}roOk(e,t){return xe(e,this.roOptions(t||{}))}roErr(e,t){return Se(e,this.roOptions(t||{}))}};function Z(e,t){let[n,r]=e.identifier.split(`.`);if(!(`identifier`in e))throw Error(`Invalid contract`);for(let i of e.non_fungible_tokens)if(i.name===t)return`${n}.${r}::${i.name}`;for(let i of e.fungible_tokens)if(i.name===t)return`${n}.${r}::${i.name}`;throw Error(`Invalid asset: "${t}" is not an asset in contract.`)}function Ee(e,t,n,r){let[i]=e.non_fungible_tokens,a=Z(e,i.name),o=i.type;return{type:`nft-postcondition`,address:t,condition:n,asset:a,assetId:D(r,o)}}function De(e,t,n,r){let[i,a]=t.split(`.`),[o]=e.fungible_tokens;return{type:`ft-postcondition`,address:t,condition:n,asset:Z(e,o.name),amount:r}}function Q(e,t=``){return e.slice(t.length+2,-1)}function $(e,t){if(T(t)){let n=Ae(e),r={},i=Object.entries(n).reduce((e,[t,n])=>{let r=t.trim();return{...e,[r]:n.trim()}},{});return t.tuple.forEach(({name:e,type:t})=>{let n=s(e);r[n]=$(i[e],t)}),r}if(E(t))return ke(e).map(e=>$(e,t.list.type));if(w(t))return e===`none`?null:$(Q(e,`some`),t.optional);if(x(t))return e.slice(1,-1);if(S(t))return e.slice(2,-1);if(t===`bool`)return e===`true`;if(t===`uint128`)return BigInt(e.slice(1));if(t===`int128`)return BigInt(e);if(t===`trait_reference`||t===`principal`)return e.replace(/^'/,``);if(t===`none`)return null;if(b(t))return d(e.slice(2));if(C(t))return e.startsWith(`(ok`)?m($(Q(e,`ok`),t.response.ok)):h($(Q(e,`err`),t.response.error));throw Error(`Unable to parse cv string to value: ${e} ${JSON.stringify(t,null,2)}`)}const Oe=Array(255);for(let e=0;e<=255;++e)Oe[e]=e.toString(16).padStart(2,`0`);function ke(e){if(e.charAt(0)!==`[`||e.at(-1)!==`]`)throw Error(`Expected (list ..), got ${e.toString()}`);let t=[],n=[],r=1;for(let i=0;i<e.length;i++)e.charAt(i)===`,`&&t.length===1&&(n.push(e.substring(r,i)),r=i+2),[`(`,`[`,`{`].includes(e.charAt(i))&&t.push(e.charAt(i)),e.charAt(i)===`)`&&t.at(-1)===`(`&&t.pop(),e.charAt(i)===`}`&&t.at(-1)===`{`&&t.pop(),e.charAt(i)===`]`&&t.at(-1)===`[`&&t.pop();let i=e.substring(r,e.length-1);return i.length>0&&n.push(i),n}function Ae(e){if(e.charAt(0)!==`{`||e.at(-1)!==`}`)throw Error(`Expected '(tuple ..)', got ${e.toString()}`);let t=1,n=[],r=[];for(let i=0;i<e.length;i++)e.charAt(i)===`,`&&n.length===1&&(r.push(e.substring(t,i)),t=i+2),[`(`,`[`,`{`].includes(e.charAt(i))&&n.push(e.charAt(i)),e.charAt(i)===`)`&&n.at(-1)===`(`&&n.pop(),e.charAt(i)===`}`&&n.at(-1)===`{`&&n.pop(),e.charAt(i)===`]`&&n.at(-1)===`[`&&n.pop();let i=e.substring(t,e.length-1);i.length>0&&r.push(i);let a={};for(let e of r)for(let t=0;t<e.length;t++)if(e.charAt(t)===`:`){let n=e.substring(0,t);a[n]=e.substring(t+2,e.length);break}return a}exports.ClarigenClient=Te,exports.CoreNodeEventType=oe,exports.DEPLOYMENT_NETWORKS=fe,exports.MAINNET_BURN_ADDRESS=o,exports.TESTNET_BURN_ADDRESS=a,exports.bootContractIdentifier=ne,exports.broadcast=we,exports.bytesToAscii=f,exports.bytesToHex=re,exports.callReadOnlyFunction=H,exports.contractFactory=R,exports.contractsFactory=me,exports.createAssetInfo=Z,exports.cvToHex=t.cvToHex,exports.cvToJSON=k,exports.cvToString=O,exports.cvToValue=_,exports.deploymentFactory=he,exports.err=h,exports.expectErr=F,exports.expectOk=P,exports.extractErrors=ie,exports.fetchMapGet=Ce,exports.filterEvents=se,exports.findJsTupleKey=N,exports.formValueToCV=K,exports.formValueToParseable=G,exports.functionsFactory=L,exports.getApiUrl=X,exports.getContractIdentifier=ee,exports.getContractName=l,exports.getContractNameFromPath=u,exports.getContractPrincipalCV=te,exports.getTypeString=I,exports.hexToBytes=d,exports.hexToCV=t.hexToCV,exports.hexToCvValue=ue,exports.isClarityAbiBuffer=b,exports.isClarityAbiList=E,exports.isClarityAbiOptional=w,exports.isClarityAbiPrimitive=y,exports.isClarityAbiResponse=C,exports.isClarityAbiStringAscii=x,exports.isClarityAbiStringUtf8=S,exports.isClarityAbiTraitReference=de,exports.isClarityAbiTuple=T,exports.isNumber=p,exports.isOptionalFormValue=U,exports.isResponse=le,exports.isResponseFormValue=W,exports.makeContracts=ce,exports.makeFungiblePostCondition=De,exports.makeNonFungiblePostCondition=Ee,exports.mapFactory=z,exports.ok=m,exports.parseQueryValue=q,exports.parseReadOnlyResponse=V,exports.parseToCV=D,exports.principalToString=g,exports.projectErrors=ae,exports.projectFactory=pe,exports.queryToFunctionArgs=be,exports.rawClarityToValue=$,exports.ro=Y,exports.roErr=Se,exports.roOk=xe,exports.toCamelCase=s,exports.toKebabCase=c,exports.transformArgsArray=j,exports.transformArgsToCV=M,exports.transformObjectArgs=A;
1
+ const require_deployment = require('./deployment-DRgKqqdY.cjs');
2
+ let __stacks_transactions = require("@stacks/transactions");
3
+ let __scure_base = require("@scure/base");
4
+ let __stacks_blockchain_api_client = require("@stacks/blockchain-api-client");
5
+ let __stacks_network = require("@stacks/network");
6
+
7
+ //#region src/utils.ts
8
+ /** biome-ignore-all lint/style/useTrimStartEnd: suppressed */
9
+ const TESTNET_BURN_ADDRESS = "ST000000000000000000002AMW42H";
10
+ const MAINNET_BURN_ADDRESS = "SP000000000000000000002Q6VF78";
11
+ const toCamelCase = (input, titleCase) => {
12
+ const inputStr = typeof input === "string" ? input : String(input);
13
+ if (/^[A-Z_]+$/.test(inputStr)) return inputStr;
14
+ const [first, ...parts] = inputStr.replace("!", "_x").replace("?", "_q").split("-");
15
+ let result = `${titleCase ? first[0].toUpperCase() : first[0].toLowerCase()}${first.slice(1)}`;
16
+ parts.forEach((part) => {
17
+ const capitalized = part[0].toUpperCase() + part.slice(1);
18
+ result += capitalized;
19
+ });
20
+ return result;
21
+ };
22
+ function toKebabCase(input) {
23
+ const matches = input.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g);
24
+ if (!matches) return input;
25
+ return matches.join("-").toLowerCase();
26
+ }
27
+ function getContractName(identifier, camelCase = true) {
28
+ const name = identifier.split(".")[1];
29
+ return camelCase ? toCamelCase(name) : name;
30
+ }
31
+ const getContractNameFromPath = (path) => {
32
+ const filename = path.split("/").at(-1);
33
+ const [contractName] = (filename === null || filename === void 0 ? void 0 : filename.split(".")) ?? [];
34
+ return contractName;
35
+ };
36
+ const getContractIdentifier = (contract) => `${contract.address}.${contract.name}`;
37
+ const getContractPrincipalCV = (contract) => {
38
+ const contractName = getContractNameFromPath(contract.contractFile);
39
+ return (0, __stacks_transactions.contractPrincipalCV)(contract.address, contractName);
40
+ };
41
+ function bootContractIdentifier(name, mainnet) {
42
+ return `${mainnet ? MAINNET_BURN_ADDRESS : TESTNET_BURN_ADDRESS}.${name}`;
43
+ }
44
+ function bytesToHex(bytes) {
45
+ return __scure_base.hex.encode(bytes);
46
+ }
47
+ function hexToBytes(hexString) {
48
+ return __scure_base.hex.decode(hexString);
49
+ }
50
+ function bytesToAscii(bytes) {
51
+ const bytesArray = Array.from(bytes);
52
+ return String.fromCharCode.apply(null, bytesArray);
53
+ }
54
+ const isNumber = (value) => typeof value === "number";
55
+ function extractErrors(contract) {
56
+ const { constants } = contract;
57
+ const result = {};
58
+ for (const key in constants) if (key.toLowerCase().startsWith("err")) {
59
+ const value = constants[key];
60
+ if (typeof value === "object" && value && "isOk" in value && !value.isOk && "value" in value) result[key] = value.value;
61
+ else result[key] = value;
62
+ }
63
+ return result;
64
+ }
65
+ function projectErrors(project) {
66
+ const { contracts } = project;
67
+ const result = {};
68
+ for (const key in contracts) result[key] = extractErrors(contracts[key]);
69
+ return result;
70
+ }
71
+
72
+ //#endregion
73
+ //#region src/events.ts
74
+ let CoreNodeEventType = /* @__PURE__ */ function(CoreNodeEventType$1) {
75
+ CoreNodeEventType$1["ContractEvent"] = "contract_event";
76
+ CoreNodeEventType$1["StxTransferEvent"] = "stx_transfer_event";
77
+ CoreNodeEventType$1["StxMintEvent"] = "stx_mint_event";
78
+ CoreNodeEventType$1["StxBurnEvent"] = "stx_burn_event";
79
+ CoreNodeEventType$1["StxLockEvent"] = "stx_lock_event";
80
+ CoreNodeEventType$1["NftTransferEvent"] = "nft_transfer_event";
81
+ CoreNodeEventType$1["NftMintEvent"] = "nft_mint_event";
82
+ CoreNodeEventType$1["NftBurnEvent"] = "nft_burn_event";
83
+ CoreNodeEventType$1["FtTransferEvent"] = "ft_transfer_event";
84
+ CoreNodeEventType$1["FtMintEvent"] = "ft_mint_event";
85
+ CoreNodeEventType$1["FtBurnEvent"] = "ft_burn_event";
86
+ return CoreNodeEventType$1;
87
+ }({});
88
+ function filterEvents(events, type) {
89
+ return events.filter((event) => event.type === type);
90
+ }
91
+
92
+ //#endregion
93
+ //#region src/contracts.ts
94
+ function makeContracts(contracts, options = {}) {
95
+ const instances = {};
96
+ for (const k in contracts) {
97
+ const contract = contracts[k];
98
+ const address = options.deployerAddress || contract.address;
99
+ instances[k] = {
100
+ identifier: `${address}.${contract.name}`,
101
+ contract: contract.contract(address, contract.name)
102
+ };
103
+ }
104
+ return instances;
105
+ }
106
+
107
+ //#endregion
108
+ //#region src/clarity-types.ts
109
+ /** biome-ignore-all lint/style/useTrimStartEnd: suppressed */
110
+ function ok(value) {
111
+ return {
112
+ isOk: true,
113
+ value
114
+ };
115
+ }
116
+ function err(value) {
117
+ return {
118
+ isOk: false,
119
+ value
120
+ };
121
+ }
122
+ function isResponse(value) {
123
+ return typeof value === "object" && value !== null && "isOk" in value;
124
+ }
125
+ function principalToString(principal) {
126
+ return principal.value;
127
+ }
128
+ /**
129
+ * @param val - ClarityValue
130
+ * @param returnResponse - if true, this will return a "response" object.
131
+ * Otherwise, it returns the inner value of the response (whether ok or err)
132
+ */
133
+ function cvToValue(val, returnResponse = false) {
134
+ switch (val.type) {
135
+ case __stacks_transactions.ClarityType.BoolTrue: return true;
136
+ case __stacks_transactions.ClarityType.BoolFalse: return false;
137
+ case __stacks_transactions.ClarityType.Int:
138
+ case __stacks_transactions.ClarityType.UInt: return val.value;
139
+ case __stacks_transactions.ClarityType.Buffer: return hexToBytes(val.value);
140
+ case __stacks_transactions.ClarityType.OptionalNone: return null;
141
+ case __stacks_transactions.ClarityType.OptionalSome: return cvToValue(val.value, true);
142
+ case __stacks_transactions.ClarityType.ResponseErr:
143
+ if (returnResponse) return err(cvToValue(val.value, true));
144
+ return cvToValue(val.value, true);
145
+ case __stacks_transactions.ClarityType.ResponseOk:
146
+ if (returnResponse) return ok(cvToValue(val.value, true));
147
+ return cvToValue(val.value, true);
148
+ case __stacks_transactions.ClarityType.PrincipalStandard:
149
+ case __stacks_transactions.ClarityType.PrincipalContract: return principalToString(val);
150
+ case __stacks_transactions.ClarityType.List: return val.value.map((v) => cvToValue(v, true));
151
+ case __stacks_transactions.ClarityType.Tuple: return Object.entries(val.value).reduce((acc, [key, val$1]) => {
152
+ const keyFixed = toCamelCase(key);
153
+ return {
154
+ ...acc,
155
+ [keyFixed]: cvToValue(val$1, true)
156
+ };
157
+ }, {});
158
+ case __stacks_transactions.ClarityType.StringASCII: return val.value;
159
+ case __stacks_transactions.ClarityType.StringUTF8: return val.value;
160
+ }
161
+ }
162
+ /**
163
+ * Converts a hex encoded string to the javascript clarity value object {type: string; value: any}
164
+ * @param hex - the hex encoded string with or without `0x` prefix
165
+ * @param jsonCompat - enable to serialize bigints to strings
166
+ */
167
+ function hexToCvValue(hex$1, jsonCompat = false) {
168
+ return cvToValue((0, __stacks_transactions.hexToCV)(hex$1), jsonCompat);
169
+ }
170
+ function inputToBigInt(input) {
171
+ if (!(typeof input === "bigint" || typeof input === "number" || typeof input === "string")) throw new Error("Invalid input type for integer");
172
+ return BigInt(input);
173
+ }
174
+ const isClarityAbiPrimitive = (val) => typeof val === "string";
175
+ const isClarityAbiBuffer = (val) => val.buffer !== void 0;
176
+ const isClarityAbiStringAscii = (val) => val["string-ascii"] !== void 0;
177
+ const isClarityAbiStringUtf8 = (val) => val["string-utf8"] !== void 0;
178
+ const isClarityAbiResponse = (val) => val.response !== void 0;
179
+ const isClarityAbiOptional = (val) => val.optional !== void 0;
180
+ const isClarityAbiTuple = (val) => val.tuple !== void 0;
181
+ const isClarityAbiList = (val) => val.list !== void 0;
182
+ const isClarityAbiTraitReference = (val) => val === "trait_reference";
183
+ function parseToCV(input, type) {
184
+ if (isClarityAbiTuple(type)) {
185
+ if (typeof input !== "object") throw new Error("Invalid tuple input");
186
+ const tuple = {};
187
+ type.tuple.forEach((key) => {
188
+ const val = input[findJsTupleKey(key.name, input)];
189
+ tuple[key.name] = parseToCV(val, key.type);
190
+ });
191
+ return (0, __stacks_transactions.tupleCV)(tuple);
192
+ }
193
+ if (isClarityAbiList(type)) return (0, __stacks_transactions.listCV)(input.map((input$1) => parseToCV(input$1, type.list.type)));
194
+ if (isClarityAbiOptional(type)) {
195
+ if (input === null) return (0, __stacks_transactions.noneCV)();
196
+ return (0, __stacks_transactions.someCV)(parseToCV(input, type.optional));
197
+ }
198
+ if (isClarityAbiStringAscii(type)) {
199
+ if (typeof input !== "string") throw new Error("Invalid string-ascii input");
200
+ return (0, __stacks_transactions.stringAsciiCV)(input);
201
+ }
202
+ if (isClarityAbiStringUtf8(type)) {
203
+ if (typeof input !== "string") throw new Error("Invalid string-ascii input");
204
+ return (0, __stacks_transactions.stringUtf8CV)(input);
205
+ }
206
+ if (isClarityAbiResponse(type)) {
207
+ if (!isResponse(input)) throw new Error("Invalid response input");
208
+ if (input.isOk) return (0, __stacks_transactions.responseOkCV)(parseToCV(input.value, type.response.ok));
209
+ return (0, __stacks_transactions.responseErrorCV)(parseToCV(input.value, type.response.error));
210
+ }
211
+ if (type === "bool") return (0, __stacks_transactions.parseToCV)(typeof input === "boolean" ? input.toString() : input, type);
212
+ if (type === "uint128") return (0, __stacks_transactions.uintCV)(inputToBigInt(input).toString());
213
+ if (type === "int128") return (0, __stacks_transactions.intCV)(inputToBigInt(input).toString());
214
+ if (type === "trait_reference") {
215
+ if (typeof input !== "string") throw new Error("Invalid input for trait_reference");
216
+ const [addr, name] = input.split(".");
217
+ return (0, __stacks_transactions.contractPrincipalCV)(addr, name);
218
+ }
219
+ if (isClarityAbiBuffer(type)) return (0, __stacks_transactions.bufferCV)(input);
220
+ return (0, __stacks_transactions.parseToCV)(input, type);
221
+ }
222
+ function cvToString(val, optionsOrEncoding) {
223
+ const options = typeof optionsOrEncoding === "object" ? optionsOrEncoding : {
224
+ encoding: optionsOrEncoding,
225
+ indent: void 0,
226
+ depth: void 0
227
+ };
228
+ const encoding = options.encoding ?? "hex";
229
+ const indent = options.indent;
230
+ const depth = options.depth ?? 0;
231
+ switch (val.type) {
232
+ case __stacks_transactions.ClarityType.BoolTrue: return "true";
233
+ case __stacks_transactions.ClarityType.BoolFalse: return "false";
234
+ case __stacks_transactions.ClarityType.Int: return val.value.toString();
235
+ case __stacks_transactions.ClarityType.UInt: return `u${val.value.toString()}`;
236
+ case __stacks_transactions.ClarityType.Buffer:
237
+ if (encoding === "tryAscii") {
238
+ const str = bytesToAscii(hexToBytes(val.value));
239
+ if (/[ -~]/.test(str)) return JSON.stringify(str);
240
+ }
241
+ return `0x${val.value}`;
242
+ case __stacks_transactions.ClarityType.OptionalNone: return "none";
243
+ case __stacks_transactions.ClarityType.OptionalSome: return `(some ${cvToString(val.value, options)})`;
244
+ case __stacks_transactions.ClarityType.ResponseErr: return `(err ${cvToString(val.value, options)})`;
245
+ case __stacks_transactions.ClarityType.ResponseOk: return `(ok ${cvToString(val.value, options)})`;
246
+ case __stacks_transactions.ClarityType.PrincipalStandard:
247
+ case __stacks_transactions.ClarityType.PrincipalContract: return `'${principalToString(val)}`;
248
+ case __stacks_transactions.ClarityType.List: return `(list ${val.value.map((v) => cvToString(v, options)).join(" ")})`;
249
+ case __stacks_transactions.ClarityType.Tuple: {
250
+ const keys = Object.keys(val.value);
251
+ if (indent === void 0 || keys.length === 0) return `{ ${keys.map((key) => `${key}: ${cvToString(val.value[key], options)}`).join(", ")} }`;
252
+ const padding = " ".repeat((depth + 1) * indent);
253
+ const outerPadding = " ".repeat(depth * indent);
254
+ return `{\n${keys.map((key) => `${padding}${key}: ${cvToString(val.value[key], {
255
+ ...options,
256
+ depth: depth + 1
257
+ })}`).join(",\n")}\n${outerPadding}}`;
258
+ }
259
+ case __stacks_transactions.ClarityType.StringASCII: return `"${val.value}"`;
260
+ case __stacks_transactions.ClarityType.StringUTF8: return `u"${val.value}"`;
261
+ }
262
+ }
263
+ /**
264
+ * Convert a Clarity value to valid JSON. This does this same thing as
265
+ * `cvToValue`, except that integers are returned as strings, and buffers
266
+ * are returned as hex-encoded strings.
267
+ *
268
+ * @param val - ClarityValue
269
+ */
270
+ function cvToJSON(val, returnResponse = false) {
271
+ switch (val.type) {
272
+ case __stacks_transactions.ClarityType.BoolTrue: return true;
273
+ case __stacks_transactions.ClarityType.BoolFalse: return false;
274
+ case __stacks_transactions.ClarityType.Int:
275
+ case __stacks_transactions.ClarityType.UInt: return `${val.value}`;
276
+ case __stacks_transactions.ClarityType.Buffer: return val.value;
277
+ case __stacks_transactions.ClarityType.OptionalNone: return null;
278
+ case __stacks_transactions.ClarityType.OptionalSome: return cvToJSON(val.value);
279
+ case __stacks_transactions.ClarityType.ResponseErr:
280
+ if (returnResponse) return err(cvToJSON(val.value));
281
+ return cvToJSON(val.value);
282
+ case __stacks_transactions.ClarityType.ResponseOk:
283
+ if (returnResponse) return ok(cvToJSON(val.value));
284
+ return cvToJSON(val.value);
285
+ case __stacks_transactions.ClarityType.PrincipalStandard:
286
+ case __stacks_transactions.ClarityType.PrincipalContract: return principalToString(val);
287
+ case __stacks_transactions.ClarityType.List: return val.value.map((v) => cvToJSON(v));
288
+ case __stacks_transactions.ClarityType.Tuple: return Object.entries(val.value).reduce((acc, [key, val$1]) => {
289
+ const keyFixed = toCamelCase(key);
290
+ return {
291
+ ...acc,
292
+ [keyFixed]: cvToJSON(val$1)
293
+ };
294
+ }, {});
295
+ case __stacks_transactions.ClarityType.StringASCII: return val.value;
296
+ case __stacks_transactions.ClarityType.StringUTF8: return val.value;
297
+ }
298
+ }
299
+ function transformObjectArgs(func, args) {
300
+ return func.args.map((abiArg) => {
301
+ const val = args[findJsTupleKey(abiArg.name, args)];
302
+ return parseToCV(val, abiArg.type);
303
+ });
304
+ }
305
+ function transformArgsArray(func, args) {
306
+ return args.map((arg, index) => parseToCV(arg, func.args[index].type));
307
+ }
308
+ function transformArgsToCV(func, args) {
309
+ if (args.length === 0) return [];
310
+ const [firstArg] = args;
311
+ if (args.length === 1 && func.args.length !== 1) return transformObjectArgs(func, firstArg);
312
+ if (typeof firstArg === "object" && !Array.isArray(firstArg) && firstArg !== null) try {
313
+ let hasAllArgs = true;
314
+ func.args.forEach((a) => {
315
+ try {
316
+ findJsTupleKey(a.name, firstArg);
317
+ } catch (_error) {
318
+ hasAllArgs = false;
319
+ }
320
+ });
321
+ if (hasAllArgs) return transformObjectArgs(func, firstArg);
322
+ } catch (_error) {}
323
+ return transformArgsArray(func, args);
324
+ }
325
+ function findJsTupleKey(key, input) {
326
+ const found = Object.keys(input).find((k) => {
327
+ const camelEq = key === k;
328
+ const kebabEq = key === toKebabCase(k);
329
+ return camelEq || kebabEq;
330
+ });
331
+ if (!found) throw new Error(`Error encoding JS tuple: ${key} not found in input.`);
332
+ return found;
333
+ }
334
+ function expectOk(response) {
335
+ if (response.isOk) return response.value;
336
+ throw new Error(`Expected OK, received error: ${String(response.value)}`);
337
+ }
338
+ function expectErr(response) {
339
+ if (!response.isOk) return response.value;
340
+ throw new Error(`Expected Err, received ok: ${String(response.value)}`);
341
+ }
342
+ function getTypeString(val) {
343
+ if (isClarityAbiPrimitive(val)) {
344
+ if (val === "int128") return "int";
345
+ if (val === "uint128") return "uint";
346
+ return val;
347
+ }
348
+ if (isClarityAbiBuffer(val)) return `(buff ${val.buffer.length})`;
349
+ if (isClarityAbiStringAscii(val)) return `(string-ascii ${val["string-ascii"].length})`;
350
+ if (isClarityAbiStringUtf8(val)) return `(string-utf8 ${val["string-utf8"].length})`;
351
+ if (isClarityAbiResponse(val)) return `(response ${getTypeString(val.response.ok)} ${getTypeString(val.response.error)})`;
352
+ if (isClarityAbiOptional(val)) return `(optional ${getTypeString(val.optional)})`;
353
+ if (isClarityAbiTuple(val)) return `{ ${val.tuple.map((t) => `${t.name}: ${getTypeString(t.type)}`).join(", ")} }`;
354
+ if (isClarityAbiList(val)) return `(list ${val.list.length} ${getTypeString(val.list.type)})`;
355
+ throw new Error(`Type string unsupported for Clarity type: ${JSON.stringify(val)}`);
356
+ }
357
+
358
+ //#endregion
359
+ //#region src/factory.ts
360
+ const DEPLOYMENT_NETWORKS = [
361
+ "devnet",
362
+ "simnet",
363
+ "testnet",
364
+ "mainnet"
365
+ ];
366
+ function projectFactory(project, network) {
367
+ const e = [];
368
+ Object.entries(project.contracts).forEach(([contractName, contract]) => {
369
+ const id = project.deployments[contractName][network];
370
+ if (id) e.push([contractName, contractFactory(contract, id)]);
371
+ return false;
372
+ });
373
+ return Object.fromEntries(e);
374
+ }
375
+ function contractsFactory(contracts, deployer) {
376
+ return Object.fromEntries(Object.entries(contracts).map(([contractName, contract]) => {
377
+ return [contractName, contractFactory(contract, `${deployer}.${contract.contractName}`)];
378
+ }));
379
+ }
380
+ function functionsFactory(abi, identifier) {
381
+ return Object.fromEntries(Object.entries(abi.functions).map(([fnName, foundFunction]) => {
382
+ return [fnName, Object.assign((...args) => {
383
+ const functionArgs = transformArgsToCV(foundFunction, args);
384
+ const [contractAddress, contractName] = identifier.split(".");
385
+ return {
386
+ functionArgs,
387
+ contractAddress,
388
+ contractName,
389
+ function: foundFunction,
390
+ functionName: foundFunction.name,
391
+ nativeArgs: args,
392
+ contractAbi: abi
393
+ };
394
+ }, { abi: foundFunction })];
395
+ }));
396
+ }
397
+ /**
398
+ * Provide a contract's types and it's contract identifier to generate
399
+ * a full contract object with all functions available.
400
+ *
401
+ * @param abi - The Clarigen-generated contract types
402
+ * @param identifier - The contract's identifier, like `SP000000000000000000002Q6VF78.bns`
403
+ * @returns
404
+ */
405
+ function contractFactory(abi, identifier) {
406
+ const full = { ...abi };
407
+ return {
408
+ ...functionsFactory(abi, identifier),
409
+ ...full,
410
+ identifier
411
+ };
412
+ }
413
+ function deploymentFactory(contracts, deployer) {
414
+ const result = {};
415
+ require_deployment.getContractTxs(deployer.plan.batches).forEach((tx) => {
416
+ const id = require_deployment.getIdentifierForDeploymentTx(tx);
417
+ const [contractAddress, contractFileName] = id.split(".");
418
+ const contractName = toCamelCase(contractFileName);
419
+ const def = contracts[contractName];
420
+ const final = contracts[contractName];
421
+ if (typeof final === "undefined") throw new Error(`Clarigen error: mismatch for contract '${contractName}'`);
422
+ result[contractName] = final;
423
+ final.contractFile = require_deployment.getDeploymentTxPath(tx);
424
+ final.identifier = id;
425
+ Object.keys(contracts[contractName].functions).forEach((_fnName) => {
426
+ const fnName = _fnName;
427
+ const fn = ((...args) => {
428
+ const foundFunction = def.functions[fnName];
429
+ return {
430
+ functionArgs: transformArgsToCV(foundFunction, args),
431
+ contractAddress,
432
+ contractName: final.contractName,
433
+ function: foundFunction,
434
+ nativeArgs: args
435
+ };
436
+ });
437
+ final[fnName] = fn;
438
+ });
439
+ });
440
+ return result;
441
+ }
442
+ function mapFactory(map, key) {
443
+ return {
444
+ key,
445
+ keyCV: parseToCV(key, map.key),
446
+ map
447
+ };
448
+ }
449
+
450
+ //#endregion
451
+ //#region src/api/api-helpers.ts
452
+ /** biome-ignore-all lint/style/useTrimStartEnd: suppressed */
453
+ function getHeaders(apiKey, headersOverride = {}) {
454
+ const headers = { ...headersOverride };
455
+ if (apiKey) headers["x-api-key"] = apiKey;
456
+ return headers;
457
+ }
458
+ function smartContractsApi(url, apiKey, headersOverride) {
459
+ return new __stacks_blockchain_api_client.SmartContractsApi(new __stacks_blockchain_api_client.Configuration({
460
+ basePath: url,
461
+ headers: getHeaders(apiKey, headersOverride)
462
+ }));
463
+ }
464
+ function v2Endpoint(url) {
465
+ return `${url}/v2`;
466
+ }
467
+ const generateUrl = (baseUrl, params) => {
468
+ try {
469
+ const url = new URL(baseUrl);
470
+ Object.keys(params).forEach((key) => {
471
+ const value = params[key];
472
+ if (!value) return;
473
+ if (Array.isArray(value)) {
474
+ if (value.length === 0) return;
475
+ return url.searchParams.set(`${key}[]`, generateQueryStringFromArray(key, value));
476
+ }
477
+ if (typeof value === "boolean" || isNumber(value)) return url.searchParams.set(key, String(value));
478
+ url.searchParams.set(key, value);
479
+ });
480
+ return url.toString();
481
+ } catch (e) {
482
+ console.error("generateUrl");
483
+ console.error(e);
484
+ return baseUrl;
485
+ }
486
+ };
487
+ const generateQueryStringFromArray = (key, values) => {
488
+ if (values === null || values === void 0 ? void 0 : values.length) return `${values.map((value, index) => `${index > 0 ? encodeURIComponent(`${key}[]`) : ""}=${encodeURIComponent(value)}`).join("&")}`;
489
+ return "";
490
+ };
491
+
492
+ //#endregion
493
+ //#region src/api/call-read-only.ts
494
+ /**
495
+ * Converts the response of a read-only function call into its Clarity Value
496
+ * @param response - {@link ReadOnlyFunctionResponse}
497
+ */
498
+ function parseReadOnlyResponse(response) {
499
+ if (response.okay) return (0, __stacks_transactions.hexToCV)(response.result);
500
+ throw new Error(response.cause);
501
+ }
502
+ /**
503
+ * Calls a read only function from a contract interface
504
+ *
505
+ * @param options - the options object
506
+ *
507
+ * Returns an ClarityValue
508
+ *
509
+ */
510
+ async function callReadOnlyFunction(options) {
511
+ const { contractAddress, functionArgs, senderAddress = contractAddress, url } = options;
512
+ return parseReadOnlyResponse(await smartContractsApi(url, options.apiKey, options.headers).callReadOnlyFunction({
513
+ ...options,
514
+ readOnlyFunctionArgs: {
515
+ sender: senderAddress,
516
+ arguments: functionArgs.map((arg) => typeof arg === "string" ? arg : (0, __stacks_transactions.cvToHex)(arg))
517
+ }
518
+ }));
519
+ }
520
+
521
+ //#endregion
522
+ //#region src/api/url-parsing.ts
523
+ function isOptionalFormValue(value) {
524
+ return typeof value === "object" && value !== null && "isNone" in value && typeof value.isNone === "boolean";
525
+ }
526
+ function isResponseFormValue(value) {
527
+ return typeof value === "object" && value !== null && "isOk" in value && typeof value.isOk === "boolean";
528
+ }
529
+ /**
530
+ * Converts a form value to the format expected by parseToCV.
531
+ * Handles differences between form representation and parseToCV expectations:
532
+ * - Optionals use { isNone, value } in forms but null for none in parseToCV
533
+ * - Buffers are hex strings in forms but Uint8Array in parseToCV
534
+ */
535
+ function formValueToParseable(value, type) {
536
+ if (isClarityAbiOptional(type)) {
537
+ if (isOptionalFormValue(value)) {
538
+ if (value.isNone) return null;
539
+ return formValueToParseable(value.value, type.optional);
540
+ }
541
+ return value;
542
+ }
543
+ if (isClarityAbiBuffer(type)) {
544
+ if (typeof value === "string") return hexToBytes(value.startsWith("0x") ? value.slice(2) : value);
545
+ return value;
546
+ }
547
+ if (isClarityAbiTuple(type)) {
548
+ if (typeof value !== "object" || value === null) return value;
549
+ const result = {};
550
+ for (const member of type.tuple) {
551
+ const memberValue = value[member.name];
552
+ result[member.name] = formValueToParseable(memberValue, member.type);
553
+ }
554
+ return result;
555
+ }
556
+ if (isClarityAbiList(type)) {
557
+ if (!Array.isArray(value)) return value;
558
+ return value.map((item) => formValueToParseable(item, type.list.type));
559
+ }
560
+ return value;
561
+ }
562
+ /**
563
+ * Converts a single form value to a ClarityValue using the ABI type.
564
+ */
565
+ function formValueToCV(value, type) {
566
+ if (isClarityAbiResponse(type)) {
567
+ if (!isResponseFormValue(value)) throw new Error("Response type requires { isOk: boolean, value: unknown } form value");
568
+ const innerType = value.isOk ? type.response.ok : type.response.error;
569
+ const innerCV = formValueToCV(value.isOk ? value.ok ?? value.value : value.err ?? value.value, innerType);
570
+ return value.isOk ? (0, __stacks_transactions.responseOkCV)(innerCV) : (0, __stacks_transactions.responseErrorCV)(innerCV);
571
+ }
572
+ return parseToCV(formValueToParseable(value, type), type);
573
+ }
574
+ /**
575
+ * Parses a raw string value from a URL query parameter into a "form value"
576
+ * based on the Clarity ABI type. This intermediate form value can then
577
+ * be converted to a ClarityValue using `formValueToCV`.
578
+ */
579
+ function parseQueryValue(value, type) {
580
+ if (value === void 0 || value === "") {
581
+ if (isClarityAbiOptional(type)) return {
582
+ isNone: true,
583
+ value: null
584
+ };
585
+ if (isClarityAbiList(type)) return [];
586
+ if (isClarityAbiTuple(type)) return {};
587
+ if (isClarityAbiPrimitive(type) && type === "bool") return false;
588
+ return "";
589
+ }
590
+ if (type === "principal" && value.startsWith("'")) return value.slice(1);
591
+ if (isClarityAbiOptional(type) || isClarityAbiList(type) || isClarityAbiTuple(type) || isClarityAbiResponse(type)) try {
592
+ return JSON.parse(value);
593
+ } catch {
594
+ return value;
595
+ }
596
+ if (isClarityAbiPrimitive(type) && type === "bool") return value === "true";
597
+ return value;
598
+ }
599
+ /**
600
+ * Converts all query parameters to an array of ClarityValues based on the function's ABI args.
601
+ */
602
+ function queryToFunctionArgs(query, args) {
603
+ return args.map((arg) => {
604
+ const rawValue = query[arg.name];
605
+ return formValueToCV(parseQueryValue(Array.isArray(rawValue) ? rawValue[0] : rawValue, arg.type), arg.type);
606
+ });
607
+ }
608
+
609
+ //#endregion
610
+ //#region src/api/index.ts
611
+ /** biome-ignore-all lint/style/useTrimStartEnd: suppressed */
612
+ function getTip(options) {
613
+ if (options.latest === false) return;
614
+ if (options.latest) return "latest";
615
+ if (typeof options.tip === "undefined") return "latest";
616
+ return options.tip;
617
+ }
618
+ async function ro(tx, options) {
619
+ const tip = getTip(options);
620
+ const cv = await callReadOnlyFunction({
621
+ contractAddress: tx.contractAddress,
622
+ contractName: tx.contractName,
623
+ functionName: tx.functionName,
624
+ functionArgs: tx.functionArgs,
625
+ tip,
626
+ url: getApiUrl(options),
627
+ apiKey: options.apiKey,
628
+ headers: options.headers
629
+ });
630
+ if (options.json) return cvToJSON(cv);
631
+ return cvToValue(cv, true);
632
+ }
633
+ async function roOk(tx, options) {
634
+ return expectOk(await ro(tx, options));
635
+ }
636
+ async function roErr(tx, options) {
637
+ return expectErr(await ro(tx, options));
638
+ }
639
+ function getApiUrl(opts) {
640
+ return (0, __stacks_network.networkFrom)(opts.network).client.baseUrl;
641
+ }
642
+ async function fetchMapGet(contractId, map, key, options) {
643
+ const payload = mapFactory(map, key);
644
+ const lookupKey = JSON.stringify((0, __stacks_transactions.cvToHex)(payload.keyCV));
645
+ const [addr, id] = contractId.split(".");
646
+ const path = generateUrl(`${v2Endpoint(getApiUrl(options))}/map_entry/${addr}/${id}/${payload.map.name}`, {
647
+ proof: 0,
648
+ tip: getTip(options)
649
+ });
650
+ return cvToValue((0, __stacks_transactions.hexToCV)((await (await fetch(path, {
651
+ method: "POST",
652
+ body: lookupKey,
653
+ headers: {
654
+ "Content-Type": "application/json",
655
+ Accept: "application/json",
656
+ ...getHeaders(options.apiKey, options.headers)
657
+ }
658
+ })).json()).data), true);
659
+ }
660
+ async function broadcast(transaction, options) {
661
+ const network = options.network;
662
+ const result = await (0, __stacks_transactions.broadcastTransaction)({
663
+ transaction,
664
+ network
665
+ });
666
+ if ("error" in result) throw new Error(`Error broadcasting tx: ${result.error} - ${result.reason} - ${JSON.stringify("reason_data" in result ? result.reason_data : void 0)}`);
667
+ return {
668
+ txId: result.txid,
669
+ stacksTransaction: transaction
670
+ };
671
+ }
672
+ var ClarigenClient = class {
673
+ network;
674
+ constructor(networkOrUrl, apiKey, headers) {
675
+ this.apiKey = apiKey;
676
+ this.headers = headers;
677
+ this.network = networkOrUrl;
678
+ }
679
+ roOptions(options) {
680
+ return {
681
+ network: this.network,
682
+ apiKey: this.apiKey,
683
+ headers: this.headers,
684
+ ...options
685
+ };
686
+ }
687
+ ro(tx, options) {
688
+ return ro(tx, this.roOptions(options || {}));
689
+ }
690
+ roOk(tx, options) {
691
+ return roOk(tx, this.roOptions(options || {}));
692
+ }
693
+ roErr(tx, options) {
694
+ return roErr(tx, this.roOptions(options || {}));
695
+ }
696
+ };
697
+
698
+ //#endregion
699
+ //#region src/post-conditions.ts
700
+ function createAssetInfo(contract, asset) {
701
+ const [addr, name] = contract.identifier.split(".");
702
+ if (!("identifier" in contract)) throw new Error("Invalid contract");
703
+ for (const nft of contract.non_fungible_tokens) if (nft.name === asset) return `${addr}.${name}::${nft.name}`;
704
+ for (const ft of contract.fungible_tokens) if (ft.name === asset) return `${addr}.${name}::${ft.name}`;
705
+ throw new Error(`Invalid asset: "${asset}" is not an asset in contract.`);
706
+ }
707
+ function makeNonFungiblePostCondition(contract, sender, condition, value) {
708
+ const [nftType] = contract.non_fungible_tokens;
709
+ const asset = createAssetInfo(contract, nftType.name);
710
+ const abiType = nftType.type;
711
+ return {
712
+ type: "nft-postcondition",
713
+ address: sender,
714
+ condition,
715
+ asset,
716
+ assetId: parseToCV(value, abiType)
717
+ };
718
+ }
719
+ function makeFungiblePostCondition(contract, sender, condition, amount) {
720
+ const [_addr, _name] = sender.split(".");
721
+ const [ftType] = contract.fungible_tokens;
722
+ return {
723
+ type: "ft-postcondition",
724
+ address: sender,
725
+ condition,
726
+ asset: createAssetInfo(contract, ftType.name),
727
+ amount
728
+ };
729
+ }
730
+
731
+ //#endregion
732
+ //#region src/raw-clarity.ts
733
+ /** biome-ignore-all lint/style/useTrimStartEnd: suppressed */
734
+ function unwrap(input, prefix = "") {
735
+ return input.slice(prefix.length + 2, -1);
736
+ }
737
+ function rawClarityToValue(input, type) {
738
+ if (isClarityAbiTuple(type)) {
739
+ const decoded = expectTuple(input);
740
+ const tuple = {};
741
+ const tupleReduced = Object.entries(decoded).reduce((acc, [key, val]) => {
742
+ const keyFixed = key.trim();
743
+ return {
744
+ ...acc,
745
+ [keyFixed]: val.trim()
746
+ };
747
+ }, {});
748
+ type.tuple.forEach(({ name, type: _type }) => {
749
+ const camelName = toCamelCase(name);
750
+ tuple[camelName] = rawClarityToValue(tupleReduced[name], _type);
751
+ });
752
+ return tuple;
753
+ }
754
+ if (isClarityAbiList(type)) return expectList(input).map((e) => rawClarityToValue(e, type.list.type));
755
+ if (isClarityAbiOptional(type)) {
756
+ if (input === "none") return null;
757
+ return rawClarityToValue(unwrap(input, "some"), type.optional);
758
+ }
759
+ if (isClarityAbiStringAscii(type)) return input.slice(1, -1);
760
+ if (isClarityAbiStringUtf8(type)) return input.slice(2, -1);
761
+ if (type === "bool") return input === "true";
762
+ if (type === "uint128") return BigInt(input.slice(1));
763
+ if (type === "int128") return BigInt(input);
764
+ if (type === "trait_reference") return input.replace(/^'/, "");
765
+ if (type === "principal") return input.replace(/^'/, "");
766
+ if (type === "none") return null;
767
+ if (isClarityAbiBuffer(type)) return hexToBytes(input.slice(2));
768
+ if (isClarityAbiResponse(type)) {
769
+ if (input.startsWith("(ok")) return ok(rawClarityToValue(unwrap(input, "ok"), type.response.ok));
770
+ return err(rawClarityToValue(unwrap(input, "err"), type.response.error));
771
+ }
772
+ throw new Error(`Unable to parse cv string to value: ${input} ${JSON.stringify(type, null, 2)}`);
773
+ }
774
+ const byteToHexCache = new Array(255);
775
+ for (let n = 0; n <= 255; ++n) byteToHexCache[n] = n.toString(16).padStart(2, "0");
776
+ function expectList(input) {
777
+ if (input.charAt(0) !== "[" || input.at(-1) !== "]") throw new Error(`Expected (list ..), got ${input.toString()}`);
778
+ const stack = [];
779
+ const elements = [];
780
+ let start = 1;
781
+ for (let i = 0; i < input.length; i++) {
782
+ if (input.charAt(i) === "," && stack.length === 1) {
783
+ elements.push(input.substring(start, i));
784
+ start = i + 2;
785
+ }
786
+ if ([
787
+ "(",
788
+ "[",
789
+ "{"
790
+ ].includes(input.charAt(i))) stack.push(input.charAt(i));
791
+ if (input.charAt(i) === ")" && stack.at(-1) === "(") stack.pop();
792
+ if (input.charAt(i) === "}" && stack.at(-1) === "{") stack.pop();
793
+ if (input.charAt(i) === "]" && stack.at(-1) === "[") stack.pop();
794
+ }
795
+ const remainder = input.substring(start, input.length - 1);
796
+ if (remainder.length > 0) elements.push(remainder);
797
+ return elements;
798
+ }
799
+ function expectTuple(input) {
800
+ if (input.charAt(0) !== "{" || input.at(-1) !== "}") throw new Error(`Expected '(tuple ..)', got ${input.toString()}`);
801
+ let start = 1;
802
+ const stack = [];
803
+ const elements = [];
804
+ for (let i = 0; i < input.length; i++) {
805
+ if (input.charAt(i) === "," && stack.length === 1) {
806
+ elements.push(input.substring(start, i));
807
+ start = i + 2;
808
+ }
809
+ if ([
810
+ "(",
811
+ "[",
812
+ "{"
813
+ ].includes(input.charAt(i))) stack.push(input.charAt(i));
814
+ if (input.charAt(i) === ")" && stack.at(-1) === "(") stack.pop();
815
+ if (input.charAt(i) === "}" && stack.at(-1) === "{") stack.pop();
816
+ if (input.charAt(i) === "]" && stack.at(-1) === "[") stack.pop();
817
+ }
818
+ const remainder = input.substring(start, input.length - 1);
819
+ if (remainder.length > 0) elements.push(remainder);
820
+ const tuple = {};
821
+ for (const element of elements) for (let i = 0; i < element.length; i++) if (element.charAt(i) === ":") {
822
+ const key = element.substring(0, i);
823
+ tuple[key] = element.substring(i + 2, element.length);
824
+ break;
825
+ }
826
+ return tuple;
827
+ }
828
+
829
+ //#endregion
830
+ exports.ClarigenClient = ClarigenClient;
831
+ exports.CoreNodeEventType = CoreNodeEventType;
832
+ exports.DEPLOYMENT_NETWORKS = DEPLOYMENT_NETWORKS;
833
+ exports.MAINNET_BURN_ADDRESS = MAINNET_BURN_ADDRESS;
834
+ exports.TESTNET_BURN_ADDRESS = TESTNET_BURN_ADDRESS;
835
+ exports.bootContractIdentifier = bootContractIdentifier;
836
+ exports.broadcast = broadcast;
837
+ exports.bytesToAscii = bytesToAscii;
838
+ exports.bytesToHex = bytesToHex;
839
+ exports.callReadOnlyFunction = callReadOnlyFunction;
840
+ exports.contractFactory = contractFactory;
841
+ exports.contractsFactory = contractsFactory;
842
+ exports.createAssetInfo = createAssetInfo;
843
+ exports.cvToHex = __stacks_transactions.cvToHex;
844
+ exports.cvToJSON = cvToJSON;
845
+ exports.cvToString = cvToString;
846
+ exports.cvToValue = cvToValue;
847
+ exports.deploymentFactory = deploymentFactory;
848
+ exports.err = err;
849
+ exports.expectErr = expectErr;
850
+ exports.expectOk = expectOk;
851
+ exports.extractErrors = extractErrors;
852
+ exports.fetchMapGet = fetchMapGet;
853
+ exports.filterEvents = filterEvents;
854
+ exports.findJsTupleKey = findJsTupleKey;
855
+ exports.formValueToCV = formValueToCV;
856
+ exports.formValueToParseable = formValueToParseable;
857
+ exports.functionsFactory = functionsFactory;
858
+ exports.getApiUrl = getApiUrl;
859
+ exports.getContractIdentifier = getContractIdentifier;
860
+ exports.getContractName = getContractName;
861
+ exports.getContractNameFromPath = getContractNameFromPath;
862
+ exports.getContractPrincipalCV = getContractPrincipalCV;
863
+ exports.getTypeString = getTypeString;
864
+ exports.hexToBytes = hexToBytes;
865
+ exports.hexToCV = __stacks_transactions.hexToCV;
866
+ exports.hexToCvValue = hexToCvValue;
867
+ exports.isClarityAbiBuffer = isClarityAbiBuffer;
868
+ exports.isClarityAbiList = isClarityAbiList;
869
+ exports.isClarityAbiOptional = isClarityAbiOptional;
870
+ exports.isClarityAbiPrimitive = isClarityAbiPrimitive;
871
+ exports.isClarityAbiResponse = isClarityAbiResponse;
872
+ exports.isClarityAbiStringAscii = isClarityAbiStringAscii;
873
+ exports.isClarityAbiStringUtf8 = isClarityAbiStringUtf8;
874
+ exports.isClarityAbiTraitReference = isClarityAbiTraitReference;
875
+ exports.isClarityAbiTuple = isClarityAbiTuple;
876
+ exports.isNumber = isNumber;
877
+ exports.isOptionalFormValue = isOptionalFormValue;
878
+ exports.isResponse = isResponse;
879
+ exports.isResponseFormValue = isResponseFormValue;
880
+ exports.makeContracts = makeContracts;
881
+ exports.makeFungiblePostCondition = makeFungiblePostCondition;
882
+ exports.makeNonFungiblePostCondition = makeNonFungiblePostCondition;
883
+ exports.mapFactory = mapFactory;
884
+ exports.ok = ok;
885
+ exports.parseQueryValue = parseQueryValue;
886
+ exports.parseReadOnlyResponse = parseReadOnlyResponse;
887
+ exports.parseToCV = parseToCV;
888
+ exports.principalToString = principalToString;
889
+ exports.projectErrors = projectErrors;
890
+ exports.projectFactory = projectFactory;
891
+ exports.queryToFunctionArgs = queryToFunctionArgs;
892
+ exports.rawClarityToValue = rawClarityToValue;
893
+ exports.ro = ro;
894
+ exports.roErr = roErr;
895
+ exports.roOk = roOk;
896
+ exports.toCamelCase = toCamelCase;
897
+ exports.toKebabCase = toKebabCase;
898
+ exports.transformArgsArray = transformArgsArray;
899
+ exports.transformArgsToCV = transformArgsToCV;
900
+ exports.transformObjectArgs = transformObjectArgs;
901
+ //# sourceMappingURL=index.cjs.map