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

Error getting RGB++ assets through assets api #210

Closed
Dawn-githup opened this issue Aug 22, 2024 · 2 comments · Fixed by #213
Closed

Error getting RGB++ assets through assets api #210

Dawn-githup opened this issue Aug 22, 2024 · 2 comments · Fixed by #213
Assignees

Comments

@Dawn-githup
Copy link
Collaborator

curl --location --request GET 'https://api.testnet.rgbpp.io/rgbpp/v1/assets//' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJteS1hcHAiLCJhdWQiOiJhcGkudGVzdG5ldC5yZ2JwcC5pbyIsImp0aSI6IjlmMDZiN2Y3LTJhNjYtNGNjMy1hNzc0LTNkZWFlNTZjYzlkMSIsImlhdCI6MTcyMzU2Mzg3M30.lYhjo1LXMHJNemdlz01HKGDFKi6mD7k7iCYxcD8eJhM' \
--header 'origin: https://api.testnet.rgbpp.io' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Accept: */*' \
--header 'Host: api.testnet.rgbpp.io' \
--header 'Connection: keep-alive'
  • '/rgbpp/v1/assets/{btc_txid}/{vout}' Data can still be obtained even if the parameter is empty

  • Response:

[
    {
        "cellOutput": {
            "capacity": "0x7558bdb00",
            "lock": {
                "codeHash": "0x61ca7a4796a4eb19ca4f0d065cb9b10ddcf002f10f7cbb810c706cb6bb5c3248",
                "args": "0x00000000fee38fa69efbe7ec72fb5812426181c694e872f1301ec9e2727016c8600cfa67",
                "hashType": "type"
            },
            "type": {
                "codeHash": "0x685a60219309029d01310311dba953d67029170ca4848a4ff638e57002130a0d",
                "args": "0x180abd4f1e919e3e5b407c400ce09719375c8b35001f37e8e12d564b12d53fe3",
                "hashType": "data1"
            }
        },
        "data": "0x4d000000100000001e000000290000000a000000746578742f706c61696e0700000073706f7265203420000000f6def2e6480bac681a56ee8ed0c0577f83b74b93635130632c7981fac2bb8157",
        "outPoint": {
            "txHash": "0x5b7dfbed7d03cef8ad52c627145f86f3dba7f983e43e03acd90c8687ff4011b1",
            "index": "0x0"
        },
        "blockNumber": "0xcc7aa5",
        "txIndex": "0x2",
        "typeHash": "0xb46fe1b9da5cd7cdbebbdff0e6c7930deeae1d9d60549d699789f8749f40b9f1"
    },
    {
        "cellOutput": {
            "capacity": "0x5e9f53e00",
            "lock": {
                "codeHash": "0x61ca7a4796a4eb19ca4f0d065cb9b10ddcf002f10f7cbb810c706cb6bb5c3248",
                "args": "0x00000000fe7e313c6bb99211e222dd1a4ae62a046ef4170d1e74a7252a827b0636ef6965",
                "hashType": "type"
            },
            "type": {
                "codeHash": "0x25c29dc317811a6f6f3985a7a9ebc4838bd388d19d0feeecf0bcd60f6c0975bb",
                "args": "0xc625c4ac0ba3ece5886d04958c3fc2d5558a21841c03577fad2d7c46e5b2b2b9",
                "hashType": "type"
            }
        },
        "data": "0x00e1f505000000000000000000000000",
        "outPoint": {
            "txHash": "0xeec5c357338f622f9bf586532be687f8fc1918566f27b4abb7fa5f9c1891af6b",
            "index": "0x0"
        },
        "blockNumber": "0xcb42df",
        "txIndex": "0x2",
        "typeHash": "0x6d7dd4497d1ef095644e422d30b2456cfe32c6469346c77752a4d6b56f432a73"
    },
    .......
]
@ShookLyngs
Copy link
Collaborator

The Issue

The issue arises because we didn't add enough restrictions/validations to the params schema in the routes. This issue can occur in many routes, and I believe we can resolve it in two ways:

  1. Validate the params as we do when validating Bitcoin addresses
  2. Add validators to the params schema and prompt the errors correctly

Validate the params as we do when validating Bitcoin addresses

Currently, the Bitcoin address params are validated as follows:

const { address } = request.params;
const valid = validateBitcoinAddress(address);
if (!valid) {
  throw fastify.httpErrors.badRequest('Invalid Bitcoin address');
}

When an invalid address is passed, an error will be thrown:

{
  "message": "Invalid Bitcoin address"
}

We can add more custom validation for other params, like so:

const { txid } = request.params;
validateHashAndThrow(txid);

Add validators to the params schema and prompt the errors correctly

We can add validators to the params schema:

params: z.object({
  hash: z.string().describe('The Bitcoin block hash').length(64, 'Invalid hash'),
}),

Then, an error will be thrown when requesting the /bitcoin/v1/block/header API without passing a block hash:

{
  "message": "[\n  {\n    \"code\": \"too_small\",\n    \"minimum\": 64,\n    \"type\": \"string\",\n    \"inclusive\": true,\n    \"exact\": true,\n    \"message\": \"Invalid hash\",\n    \"path\": [\n      \"hash\"\n    ]\n  }\n]"
}

The above error message is a stringified JSON, which does not look good. However, we could add error handling logic for the ZodError specifically to improve the error presentation:

fastify.setErrorHandler((error, request, reply) => {
  if (error.name === 'ZodError') {
    try {
      const json = JSON.parse(error.message);
      reply.status(400).send({
        message: 'Zod validation failed',
        error: json,
      });
    } catch {
      //
    }
  }
  reply.status(400).send(error);
});

The formatted error will be presented as:

{
  "message": "Zod validation failed",
  "error": [
    {
      "code": "too_small",
      "minimum": 64,
      "type": "string",
      "inclusive": true,
      "exact": true,
      "message": "Invalid hash",
      "path": [
        "hash"
      ]
    }
  ]
}

@ShookLyngs
Copy link
Collaborator

@ahonn suggests that we should only prompt the first schema parse error instead of throwing all the errors at once. A solution is to use a custom validatorCompiler to replace the original (refer to: https://github.com/ckb-cell/btc-assets-api/blob/develop/src/app.ts#L64):

import { serializerCompiler } from 'fastify-type-provider-zod';

const validatorCompiler: FastifySchemaCompiler<ZodAny> =
  ({ schema }) =>
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  (data): any => {
    try {
      return { value: schema.parse(data) };
    } catch (error) {
      if (error instanceof ZodError) {
        return {
          error: new Error(error.errors[0].message),
        };
      }
      return { error };
    }
  };

app.setValidatorCompiler(validatorCompiler);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants