Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cli option to decode serialized Clarity values #1599

Merged
merged 3 commits into from Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/cli/src/argparse.ts
Expand Up @@ -395,6 +395,37 @@ export const CLI_ARGS = {
'\n',
group: 'Account Management',
},
decode_cv: {
type: 'array',
items: [
{
name: 'clarity_value',
type: 'string',
realtype: 'string',
pattern: '-|^(0x|0X)?[a-fA-F0-9]+$',
},
{
name: 'format',
type: 'string',
realtype: 'format',
pattern: '^(repr|pretty|json)$',
},
],
minItems: 1,
maxItems: 4,
help:
'Decode a serialized Clarity value.\n' +
'\n' +
'Example:\n' +
'\n' +
' $ stx decode_cv 0x050011deadbeef11ababffff11deadbeef11ababffff\n' +
' S08XXBDYXW8TQAZZZW8XXBDYXW8TQAZZZZ88551S\n' +
' $ stx decode_cv --format json SPA2MZWV9N67TBYVWTE0PSSKMJ2F6YXW7CBE6YPW\n' +
' {"type":"principal","value":"S08XXBDYXW8TQAZZZW8XXBDYXW8TQAZZZZ88551S"}\n' +
' $ echo 0x050011deadbeef11ababffff11deadbeef11ababffff | stx decode_cv -\n' +
' S08XXBDYXW8TQAZZZW8XXBDYXW8TQAZZZZ88551S\n',
group: 'Utilities',
},
convert_address: {
type: 'array',
items: [
Expand Down
35 changes: 35 additions & 0 deletions packages/cli/src/cli.ts
Expand Up @@ -41,6 +41,8 @@ import {
TransactionVersion,
TxBroadcastResult,
validateContractCall,
Cl,
cvToJSON,
} from '@stacks/transactions';
import express from 'express';
import { prompt } from 'inquirer';
Expand Down Expand Up @@ -952,6 +954,37 @@ async function readOnlyContractFunctionCall(
});
}

/*
* Decode a serialized Clarity value
* args:
* @value (string) the hex string of the serialized value, or '-' to read from stdin
* @format (string) the format to output the value in; one of 'pretty', 'json', or 'repr'
*/
function decodeCV(_network: CLINetworkAdapter, args: string[]): Promise<string> {
const inputArg = args[0];
const format = args[1];

let inputValue: string;
if (inputArg === '-') {
janniks marked this conversation as resolved.
Show resolved Hide resolved
inputValue = fs.readFileSync(process.stdin.fd, 'utf-8').trim();
} else {
inputValue = inputArg;
}

const cv = Cl.deserialize(inputValue);
let cvString: string;
if (format === 'pretty') {
cvString = Cl.prettyPrint(cv, 2);
} else if (format === 'json') {
cvString = JSON.stringify(cvToJSON(cv));
} else if (format === 'repr' || !format) {
cvString = cvToString(cv);
} else {
throw new Error('Invalid format option');
}
return Promise.resolve(cvString);
}

// /*
// * Get the number of confirmations of a txid.
// * args:
Expand Down Expand Up @@ -1959,6 +1992,7 @@ const COMMANDS: Record<string, CommandFunction> = {
can_stack: canStack,
call_contract_func: contractFunctionCall,
call_read_only_contract_func: readOnlyContractFunctionCall,
decode_cv: decodeCV,
convert_address: addressConvert,
decrypt_keychain: decryptMnemonic,
deploy_contract: contractDeploy,
Expand Down Expand Up @@ -2159,6 +2193,7 @@ export const testables =
process.env.NODE_ENV === 'test'
? {
addressConvert,
decodeCV,
canStack,
contractFunctionCall,
getStacksWalletKey,
Expand Down
36 changes: 36 additions & 0 deletions packages/cli/tests/cli.test.ts
Expand Up @@ -3,6 +3,7 @@ import { CLIMain, testables } from '../src/cli';
import { CLINetworkAdapter, CLI_NETWORK_OPTS, getNetwork } from '../src/network';

import {
Cl,
ClarityAbi,
createStacksPrivateKey,
publicKeyFromSignatureVrs,
Expand All @@ -23,6 +24,7 @@ import {
WalletKeyInfoResult,
} from './derivation-path/keychain';
import * as fixtures from './fixtures/cli.fixture';
import { bytesToHex } from '@stacks/common';

const TEST_ABI: ClarityAbi = JSON.parse(
readFileSync(path.join(__dirname, './abi/test-abi.json')).toString()
Expand All @@ -34,6 +36,7 @@ jest.mock('inquirer');

const {
addressConvert,
decodeCV,
canStack,
contractFunctionCall,
getStacksWalletKey,
Expand All @@ -53,6 +56,39 @@ const testnetNetwork = new CLINetworkAdapter(
{} as CLI_NETWORK_OPTS
);

describe('decode_cv', () => {
janniks marked this conversation as resolved.
Show resolved Hide resolved
test('Should decode from hex arg', async () => {
const result = await decodeCV(mainnetNetwork, [
'0x050011deadbeef11ababffff11deadbeef11ababffff',
]);
expect(result).toEqual('S08XXBDYXW8TQAZZZW8XXBDYXW8TQAZZZZ88551S');
});

test('Should decode from hex to json', async () => {
const result = await decodeCV(mainnetNetwork, [
'0x050011deadbeef11ababffff11deadbeef11ababffff',
'json',
]);
expect(result).toEqual(
'{"type":"principal","value":"S08XXBDYXW8TQAZZZW8XXBDYXW8TQAZZZZ88551S"}'
);
});

test('Should decode from hex to repr', async () => {
const list = Cl.list([1, 2, 3].map(Cl.int));
const serialized = bytesToHex(Cl.serialize(list));
const result = await decodeCV(mainnetNetwork, [serialized, 'repr']);
expect(result).toEqual('(list 1 2 3)');
});

test('Should decode from hex to pretty print', async () => {
const list = Cl.list([1, 2, 3].map(Cl.int));
const serialized = bytesToHex(Cl.serialize(list));
const result = await decodeCV(mainnetNetwork, [serialized, 'pretty']);
expect(result).toEqual('(list\n 1\n 2\n 3\n)');
});
});

describe('convert_address', () => {
test.each(fixtures.convertAddress)('%p - testnet: %p', async (input, testnet, expectedResult) => {
const network = testnet ? testnetNetwork : mainnetNetwork;
Expand Down