MCPcopy Create free account
hub / github.com/CashScript/cashscript / encodeFunctionArgument

Function encodeFunctionArgument

packages/cashscript/src/Argument.ts:39–100  ·  view source on GitHub ↗
(argument: FunctionArgument, typeStr: string)

Source from the content-addressed store, hash-verified

37 * bounded bytes type receives a value of the wrong length.
38 */
39export function encodeFunctionArgument(argument: FunctionArgument, typeStr: string): EncodedFunctionArgument {
40 let type = parseType(typeStr);
41
42 if (type === PrimitiveType.BOOL) {
43 if (typeof argument !== 'boolean') {
44 throw new TypeError(typeof argument, type);
45 }
46 return encodeBool(argument);
47 }
48
49 if (type === PrimitiveType.INT) {
50 if (typeof argument !== 'bigint') {
51 throw new TypeError(typeof argument, type);
52 }
53 return encodeInt(argument);
54 }
55
56 if (type === PrimitiveType.STRING) {
57 if (typeof argument !== 'string') {
58 throw new TypeError(typeof argument, type);
59 }
60 return encodeString(argument);
61 }
62
63 if (type === PrimitiveType.SIG && argument instanceof SignatureTemplate) return argument;
64
65 // Convert hex string to Uint8Array
66 if (typeof argument === 'string') {
67 if (argument.startsWith('0x')) {
68 argument = argument.slice(2);
69 }
70
71 argument = hexToBin(argument);
72 }
73
74 if (!(argument instanceof Uint8Array)) {
75 throw Error(`Value for type ${type} should be a Uint8Array or hex string`);
76 }
77
78 // Redefine SIG as a bytes65 (Schnorr) or bytes71, bytes72, bytes73 (ECDSA) or bytes0 (for NULLFAIL)
79 if (type === PrimitiveType.SIG) {
80 if (![0, 65, 71, 72, 73].includes(argument.byteLength)) {
81 throw new TypeError(`bytes${argument.byteLength}`, type);
82 }
83 type = new BytesType(argument.byteLength);
84 }
85
86 // Redefine DATASIG as a bytes64 (Schnorr) or bytes70, bytes71, bytes72 (ECDSA) or bytes0 (for NULLFAIL)
87 if (type === PrimitiveType.DATASIG) {
88 if (![0, 64, 70, 71, 72].includes(argument.byteLength)) {
89 throw new TypeError(`bytes${argument.byteLength}`, type);
90 }
91 type = new BytesType(argument.byteLength);
92 }
93
94 // Bounded bytes types require a correctly sized argument
95 if (type instanceof BytesType && type.bound && argument.byteLength !== type.bound) {
96 throw new TypeError(`bytes${argument.byteLength}`, type);

Callers 1

createUnlockerMethod · 0.85

Calls 4

parseTypeFunction · 0.90
encodeBoolFunction · 0.90
encodeIntFunction · 0.90
encodeStringFunction · 0.90

Tested by

no test coverage detected