All files / src/transactions contract-abi.ts

76.71% Statements 145/189
69.44% Branches 100/144
94.73% Functions 18/19
76.13% Lines 134/176

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359                                                        10x 10x     10x 119x 10x 53x 10x 22x 10x 17x 10x 33x 10x 26x 10x 19x 10x 11x   10x 57x 28x 4x 24x 4x 20x 14x 6x 4x 2x 2x           29x 8x 21x 4x 17x 4x 13x 5x 8x 4x 4x 2x 2x 2x                                                                                                                   10x   10x 55x 32x 5x 27x 4x   23x 23x 5x 18x 3x 15x 3x 12x 3x 9x 3x 6x 30x 3x 3x           10x 1x 1x 1x         57x         15x   4x   4x   8x         2x         2x         1x         3x         1x         3x         1x         5x         3x     5x 5x 5x 37x 37x 37x       37x 36x 2x   34x   1x     2x                                 10x 50x 14x 12x 12x   12x 1x         11x 11x 11x   11x 5x 5x                   6x 2x 1x   1x                             10x 7x 7x 6x 1x 5x 1x 4x 2x 1x 1x 1x       2x 2x 1x 1x   1x         1x 1x 1x     1x                          
import {
  ClarityValue,
  uintCV,
  intCV,
  contractPrincipalCV,
  standardPrincipalCV,
  noneCV,
  bufferCV,
  falseCV,
  trueCV,
  ClarityType,
  getCVTypeString,
  bufferCVFromString,
  stringAsciiCV,
  stringUtf8CV,
  ClarityAbi,
  ClarityAbiFunction,
  ClarityAbiType,
  ClarityAbiTypePrimitive,
  ClarityAbiTypeBuffer,
  ClarityAbiTypeStringAscii,
  ClarityAbiTypeStringUtf8,
  ClarityAbiTypeResponse,
  ClarityAbiTypeOptional,
  ClarityAbiTypeTuple,
  ClarityAbiTypeList,
  ClarityAbiTypeId,
  ClarityAbiTypeUnion,
} from 'micro-stacks/clarity';
import { utf8ToBytes, cloneDeep, NotImplementedError } from 'micro-stacks/common';
import { ContractCallPayload } from './payload';
 
export const isClarityAbiPrimitive = (val: ClarityAbiType): val is ClarityAbiTypePrimitive =>
  typeof val === 'string';
export const isClarityAbiBuffer = (val: ClarityAbiType): val is ClarityAbiTypeBuffer =>
  (val as ClarityAbiTypeBuffer).buffer !== undefined;
export const isClarityAbiStringAscii = (val: ClarityAbiType): val is ClarityAbiTypeStringAscii =>
  (val as ClarityAbiTypeStringAscii)['string-ascii'] !== undefined;
export const isClarityAbiStringUtf8 = (val: ClarityAbiType): val is ClarityAbiTypeStringUtf8 =>
  (val as ClarityAbiTypeStringUtf8)['string-utf8'] !== undefined;
export const isClarityAbiResponse = (val: ClarityAbiType): val is ClarityAbiTypeResponse =>
  (val as ClarityAbiTypeResponse).response !== undefined;
export const isClarityAbiOptional = (val: ClarityAbiType): val is ClarityAbiTypeOptional =>
  (val as ClarityAbiTypeOptional).optional !== undefined;
export const isClarityAbiTuple = (val: ClarityAbiType): val is ClarityAbiTypeTuple =>
  (val as ClarityAbiTypeTuple).tuple !== undefined;
export const isClarityAbiList = (val: ClarityAbiType): val is ClarityAbiTypeList =>
  (val as ClarityAbiTypeList).list !== undefined;
 
export function getTypeUnion(val: ClarityAbiType): ClarityAbiTypeUnion {
  if (isClarityAbiPrimitive(val)) {
    if (val === 'uint128') {
      return { id: ClarityAbiTypeId.ClarityAbiTypeUInt128, type: val };
    } else if (val === 'int128') {
      return { id: ClarityAbiTypeId.ClarityAbiTypeInt128, type: val };
    } else if (val === 'bool') {
      return { id: ClarityAbiTypeId.ClarityAbiTypeBool, type: val };
    } else if (val === 'principal') {
      return { id: ClarityAbiTypeId.ClarityAbiTypePrincipal, type: val };
    } else if (val === 'trait_reference') {
      return { id: ClarityAbiTypeId.ClarityAbiTypeTraitReference, type: val };
    } else Eif (val === 'none') {
      return { id: ClarityAbiTypeId.ClarityAbiTypeNone, type: val };
    } else {
      throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(val)}`);
    }
  } else if (isClarityAbiBuffer(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeBuffer, type: val };
  } else if (isClarityAbiResponse(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeResponse, type: val };
  } else if (isClarityAbiOptional(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeOptional, type: val };
  } else if (isClarityAbiTuple(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeTuple, type: val };
  } else if (isClarityAbiList(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeList, type: val };
  } else if (isClarityAbiStringAscii(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeStringAscii, type: val };
  } else if (isClarityAbiStringUtf8(val)) {
    return { id: ClarityAbiTypeId.ClarityAbiTypeStringUtf8, type: val };
  } else E{
    throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(val)}`);
  }
}
 
function encodeClarityValue(type: ClarityAbiType, val: string): ClarityValue;
function encodeClarityValue(type: ClarityAbiTypeUnion, val: string): ClarityValue;
function encodeClarityValue(
  input: ClarityAbiTypeUnion | ClarityAbiType,
  val: string
): ClarityValue {
  let union: ClarityAbiTypeUnion;
  if ((input as ClarityAbiTypeUnion).id !== undefined) {
    union = input as ClarityAbiTypeUnion;
  } else {
    union = getTypeUnion(input as ClarityAbiType);
  }
  switch (union.id) {
    case ClarityAbiTypeId.ClarityAbiTypeUInt128:
      return uintCV(val);
    case ClarityAbiTypeId.ClarityAbiTypeInt128:
      return intCV(val);
    case ClarityAbiTypeId.ClarityAbiTypeBool:
      if (val === 'false' || val === '0') return falseCV();
      else if (val === 'true' || val === '1') return trueCV();
      else throw new Error(`Unexpected Clarity bool value: ${JSON.stringify(val)}`);
    case ClarityAbiTypeId.ClarityAbiTypePrincipal:
      if (val.includes('.')) {
        const [addr, name] = val.split('.');
        return contractPrincipalCV(addr, name);
      } else {
        return standardPrincipalCV(val);
      }
    case ClarityAbiTypeId.ClarityAbiTypeTraitReference:
      const [addr, name] = val.split('.');
      return contractPrincipalCV(addr, name);
    case ClarityAbiTypeId.ClarityAbiTypeNone:
      return noneCV();
    case ClarityAbiTypeId.ClarityAbiTypeBuffer:
      return bufferCV(utf8ToBytes(val));
    case ClarityAbiTypeId.ClarityAbiTypeStringAscii:
      return stringAsciiCV(val);
    case ClarityAbiTypeId.ClarityAbiTypeStringUtf8:
      return stringUtf8CV(val);
    case ClarityAbiTypeId.ClarityAbiTypeResponse:
      throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
    case ClarityAbiTypeId.ClarityAbiTypeOptional:
      throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
    case ClarityAbiTypeId.ClarityAbiTypeTuple:
      throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
    case ClarityAbiTypeId.ClarityAbiTypeList:
      throw new NotImplementedError(`Unsupported encoding for Clarity type: ${union.id}`);
    default:
      throw new Error(`Unexpected Clarity type ID: ${JSON.stringify(union)}`);
  }
}
 
export { encodeClarityValue };
 
export function getTypeString(val: ClarityAbiType): string {
  if (isClarityAbiPrimitive(val)) {
    if (val === 'int128') {
      return 'int';
    } else if (val === 'uint128') {
      return 'uint';
    }
    return val;
  } else if (isClarityAbiBuffer(val)) {
    return `(buff ${val.buffer.length})`;
  } else if (isClarityAbiStringAscii(val)) {
    return `(string-ascii ${val['string-ascii'].length})`;
  } else if (isClarityAbiStringUtf8(val)) {
    return `(string-utf8 ${val['string-utf8'].length})`;
  } else if (isClarityAbiResponse(val)) {
    return `(response ${getTypeString(val.response.ok)} ${getTypeString(val.response.error)})`;
  } else if (isClarityAbiOptional(val)) {
    return `(optional ${getTypeString(val.optional)})`;
  } else if (isClarityAbiTuple(val)) {
    return `(tuple ${val.tuple.map(t => `(${t.name} ${getTypeString(t.type)})`).join(' ')})`;
  } else if (isClarityAbiList(val)) {
    return `(list ${val.list.length} ${getTypeString(val.list.type)})`;
  } else E{
    throw new Error(`Type string unsupported for Clarity type: ${JSON.stringify(val)}`);
  }
}
 
export function abiFunctionToString(func: ClarityAbiFunction): string {
  const access = func.access === 'read_only' ? 'read-only' : func.access;
  return `(define-${access} (${func.name} ${func.args
    .map(arg => `(${arg.name} ${getTypeString(arg.type)})`)
    .join(' ')}))`;
}
 
function matchType(cv: ClarityValue, abiType: ClarityAbiType): boolean {
  const union = getTypeUnion(abiType);
 
  switch (cv.type) {
    case ClarityType.BoolTrue:
    case ClarityType.BoolFalse:
      return union.id === ClarityAbiTypeId.ClarityAbiTypeBool;
    case ClarityType.Int:
      return union.id === ClarityAbiTypeId.ClarityAbiTypeInt128;
    case ClarityType.UInt:
      return union.id === ClarityAbiTypeId.ClarityAbiTypeUInt128;
    case ClarityType.Buffer:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeBuffer &&
        union.type.buffer.length >= cv.buffer.length
      );
    case ClarityType.StringASCII:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeStringAscii &&
        union.type['string-ascii'].length >= cv.data.length
      );
    case ClarityType.StringUTF8:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeStringUtf8 &&
        union.type['string-utf8'].length >= cv.data.length
      );
    case ClarityType.OptionalNone:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeNone ||
        union.id === ClarityAbiTypeId.ClarityAbiTypeOptional
      );
    case ClarityType.OptionalSome:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeOptional &&
        matchType(cv.value, union.type.optional)
      );
    case ClarityType.ResponseErr:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeResponse &&
        matchType(cv.value, union.type.response.error)
      );
    case ClarityType.ResponseOk:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypeResponse &&
        matchType(cv.value, union.type.response.ok)
      );
    case ClarityType.PrincipalContract:
      return (
        union.id === ClarityAbiTypeId.ClarityAbiTypePrincipal ||
        union.id === ClarityAbiTypeId.ClarityAbiTypeTraitReference
      );
    case ClarityType.PrincipalStandard:
      return union.id === ClarityAbiTypeId.ClarityAbiTypePrincipal;
    case ClarityType.List:
      return (
        union.id == ClarityAbiTypeId.ClarityAbiTypeList &&
        union.type.list.length >= cv.list.length &&
        cv.list.every(val => matchType(val, union.type.list.type))
      );
    case ClarityType.Tuple:
      if (union.id == ClarityAbiTypeId.ClarityAbiTypeTuple) {
        const tuple = cloneDeep(cv.data);
        for (let i = 0; i < union.type.tuple.length; i++) {
          const abiTupleEntry = union.type.tuple[i];
          const key = abiTupleEntry.name;
          const val = tuple[key];
 
          // if key exists in cv tuple, check if its type matches the abi
          // return false if key doesn't exist
          if (val) {
            if (!matchType(val, abiTupleEntry.type)) {
              return false;
            }
            delete tuple[key];
          } else {
            return false;
          }
        }
        return true;
      } else E{
        return false;
      }
    default:
      return false;
  }
}
 
/**
 * Validates a contract-call payload with a contract ABI
 *
 * @param {ContractCallPayload} payload - a contract-call payload
 * @param {ClarityAbi} abi - a contract ABI
 *
 * @returns {boolean} true if the payloads functionArgs type check against those in the ABI
 */
export function validateContractCall(payload: ContractCallPayload, abi: ClarityAbi): boolean {
  const filtered = abi.functions.filter(fn => fn.name === payload.functionName.content);
  if (filtered.length === 1) {
    const abiFunc = filtered[0];
    const abiArgs = abiFunc.args;
 
    if (payload.functionArgs.length !== abiArgs.length) {
      throw new Error(
        `Clarity function expects ${abiArgs.length} argument(s) but received ${payload.functionArgs.length}`
      );
    }
 
    for (let i = 0; i < payload.functionArgs.length; i++) {
      const payloadArg = payload.functionArgs[i];
      const abiArg = abiArgs[i];
 
      if (!matchType(payloadArg, abiArg.type)) {
        const argNum = i + 1;
        throw new Error(
          `Clarity function \`${
            payload.functionName.content
          }\` expects argument ${argNum} to be of type ${getTypeString(
            abiArg.type
          )}, not ${getCVTypeString(payloadArg)}`
        );
      }
    }
 
    return true;
  } else if (filtered.length === 0) {
    throw new Error(`ABI doesn't contain a function with the name ${payload.functionName.content}`);
  } else {
    throw new Error(
      `Malformed ABI. Contains multiple functions with the name ${payload.functionName.content}`
    );
  }
}
 
/**
 * Convert string input to Clarity value based on contract ABI data. Only handles Clarity
 * primitives and buffers. Responses, optionals, tuples and lists are not supported.
 *
 * @param {string} input - string to be parsed into Clarity value
 * @param {ClarityAbiType} type - the contract function argument object
 *
 * @returns {ClarityValue} returns a Clarity value
 */
export function parseToCV(input: string, type: ClarityAbiType): ClarityValue {
  const typeString = getTypeString(type);
  if (isClarityAbiPrimitive(type)) {
    if (type === 'uint128') {
      return uintCV(input);
    } else if (type === 'int128') {
      return intCV(input);
    } else if (type === 'bool') {
      if (input.toLowerCase() === 'true') {
        return trueCV();
      } else if (input.toLowerCase() === 'false') {
        return falseCV();
      } else E{
        throw new Error(`Invalid bool value: ${input}`);
      }
    } else if (type === 'principal') {
      if (input.includes('.')) {
        const [address, contractName] = input.split('.');
        return contractPrincipalCV(address, contractName);
      } else {
        return standardPrincipalCV(input);
      }
    } else E{
      throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
    }
  } else if (isClarityAbiBuffer(type)) {
    const inputLength = utf8ToBytes(input).byteLength;
    Iif (inputLength > type.buffer.length) {
      throw new Error(`Input exceeds specified buffer length limit of ${type.buffer.length}`);
    }
    return bufferCVFromString(input);
  } else Eif (isClarityAbiResponse(type)) {
    throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
  } else if (isClarityAbiOptional(type)) {
    throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
  } else if (isClarityAbiTuple(type)) {
    throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
  } else if (isClarityAbiList(type)) {
    throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
  } else {
    throw new Error(`Contract function contains unsupported Clarity ABI type: ${typeString}`);
  }
}