Skip to content

Commit

Permalink
chore: sign document should be clear on what errors it could throw, e…
Browse files Browse the repository at this point in the history
…xport of v4 verify shd be more explicit (#280)

* chore: sign document should be clear on what errors it could throw

* fix: verify export naming shd be more explicit
  • Loading branch information
phanshiyu authored May 6, 2024
1 parent 81e1dbe commit da0e5c8
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 11 deletions.
4 changes: 2 additions & 2 deletions src/4.0/__tests__/sign.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ describe("V4 sign", () => {
}
)
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Document has not been properly wrapped:
{
"Document has not been properly wrapped:
{
"_errors": [],
"proof": {
"_errors": [],
Expand Down
2 changes: 1 addition & 1 deletion src/4.0/exports/verify.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { verify } from "../verify";
export { verify as verifySignature } from "../verify";
32 changes: 24 additions & 8 deletions src/4.0/sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,38 @@ export const signDocument = async <T extends V4Document>(

const { proof: validatedProof } = parsedResults.data;
const merkleRoot = `0x${validatedProof.merkleRoot}`;
const signature = await sign(algorithm, merkleRoot, keyOrSigner);
const proof: V4SignedWrappedDocument["proof"] = {
...validatedProof,
key: "public" in keyOrSigner ? keyOrSigner.public : `did:ethr:${await keyOrSigner.getAddress()}#controller`,
signature,
};
return { ...document, proof };

try {
const signature = await sign(algorithm, merkleRoot, keyOrSigner);
const proof: V4SignedWrappedDocument["proof"] = {
...validatedProof,
key: "public" in keyOrSigner ? keyOrSigner.public : `did:ethr:${await keyOrSigner.getAddress()}#controller`,
signature,
};
return { ...document, proof };
} catch (error) {
throw new CouldNotSignDocumentError(error);
}
};

class WrappedDocumentValidationError extends Error {
constructor(public error: ZodError) {
super(`Document has not been properly wrapped: \n ${JSON.stringify(error.format(), null, 2)}`);
super(`Document has not been properly wrapped:\n${JSON.stringify(error.format(), null, 2)}`);
Object.setPrototypeOf(this, WrappedDocumentValidationError.prototype);
}
}

/**
* Cases where this can be thrown includes: network error, invalid keys or signer
*/
class CouldNotSignDocumentError extends Error {
constructor(public error: unknown) {
super(`Could not sign document:\n${error instanceof Error ? error.message : JSON.stringify(error, null, 2)}`);
Object.setPrototypeOf(this, CouldNotSignDocumentError.prototype);
}
}

export const signDocumentErrors = {
WrappedDocumentValidationError,
CouldNotSignDocumentError,
};

0 comments on commit da0e5c8

Please sign in to comment.