Skip to content

Commit

Permalink
Refactor the related unit tests (#213)
Browse files Browse the repository at this point in the history
* Modify calling signTypedData by wallet client

* Upload pnpm-lock.yaml

* Remove useless type

* Delete StoryAPI and related tests

* Remove utils useless function

* Refactor client unit test

* Refactor dispute unit tests

* Refactor ipAccount tests

* Refactor nftClient tests

* Add address validation for signature

* Export PermissionSignatureResponse type

* bump up package version to 1.0.0-rc.15
  • Loading branch information
bonnie57 authored Jun 18, 2024
1 parent 23c44a0 commit 289661e
Show file tree
Hide file tree
Showing 16 changed files with 190 additions and 797 deletions.
2 changes: 1 addition & 1 deletion packages/core-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@story-protocol/core-sdk",
"version": "1.0.0-rc.14",
"version": "1.0.0-rc.15",
"description": "Story Protocol Core SDK",
"main": "dist/story-protocol-core-sdk.cjs.js",
"module": "dist/story-protocol-core-sdk.esm.js",
Expand Down
28 changes: 0 additions & 28 deletions packages/core-sdk/src/clients/storyAPI.ts

This file was deleted.

9 changes: 2 additions & 7 deletions packages/core-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ export { IPAccountClient } from "./resources/ipAccount";
export { RoyaltyClient } from "./resources/royalty";

export type { StoryConfig, SupportedChainIds } from "./types/config";
export type { TypedData } from "./types/common";

export type {
RegisterIpResponse,
RegisterRequest,
RegisterIpResponse,
RegisterDerivativeResponse,
RegisterDerivativeRequest,
RegisterDerivativeWithLicenseTokensRequest,
Expand All @@ -34,7 +33,6 @@ export type {
RegisterPILResponse,
AttachLicenseTermsRequest,
AttachLicenseTermsResponse,
LicenseTermsIdResponse,
MintLicenseTokensRequest,
MintLicenseTokensResponse,
LicenseTermsId,
Expand Down Expand Up @@ -64,11 +62,8 @@ export type {
} from "./types/resources/permission";
export { AccessPermission } from "./types/resources/permission";
export type {
Dispute,
RaiseDisputeRequest,
RaiseDisputeResponse,
SetDisputeJudgementRequest,
SetDisputeJudgementResponse,
CancelDisputeRequest,
CancelDisputeResponse,
ResolveDisputeRequest,
Expand All @@ -93,4 +88,4 @@ export type {
} from "./abi/generated";

export { getPermissionSignature } from "./utils/sign";
export type { PermissionSignatureRequest } from "./types/common";
export type { PermissionSignatureRequest, PermissionSignatureResponse } from "./types/common";
6 changes: 3 additions & 3 deletions packages/core-sdk/src/resources/dispute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ResolveDisputeResponse,
} from "../types/resources/dispute";
import { DisputeModuleClient, SimpleWalletClient } from "../abi/generated";
import { getAddress } from "../utils/utils";

export class DisputeClient {
private readonly rpcClient: PublicClient;
Expand Down Expand Up @@ -39,7 +40,7 @@ export class DisputeClient {
public async raiseDispute(request: RaiseDisputeRequest): Promise<RaiseDisputeResponse> {
try {
const txHash = await this.disputeModuleClient.raiseDispute({
targetIpId: request.targetIpId,
targetIpId: getAddress(request.targetIpId, "request.targetIpId"),
linkToDisputeEvidence: request.linkToDisputeEvidence,
targetTag: stringToHex(request.targetTag, { size: 32 }),
data: request.calldata || "0x",
Expand Down Expand Up @@ -104,14 +105,13 @@ export class DisputeClient {
disputeId: BigInt(request.disputeId),
data: request.data,
});

if (request.txOptions?.waitForTransaction) {
await this.rpcClient.waitForTransactionReceipt({ hash: txHash });
}

return { txHash: txHash };
} catch (error) {
handleError(error, "Failed to cancel dispute");
handleError(error, "Failed to resolve dispute");
}
}
}
4 changes: 2 additions & 2 deletions packages/core-sdk/src/resources/ipAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ export class IPAccountClient {
);

const txHash = await ipAccountClient.executeWithSig({
to: request.to,
to: getAddress(request.to, "request.to"),
value: BigInt(0),
data: request.data,
signer: request.signer,
signer: getAddress(request.signer, "request.signer"),
deadline: BigInt(request.deadline),
signature: request.signature,
});
Expand Down
10 changes: 6 additions & 4 deletions packages/core-sdk/src/types/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Address, WalletClient } from "viem";
import { Address, Hex, WalletClient } from "viem";

import { SetPermissionsRequest } from "./resources/permission";

Expand All @@ -9,10 +9,12 @@ export type TypedData = {

export type PermissionSignatureRequest = {
ipId: Address;
nonce: number | bigint;
deadline: bigint;
nonce: string | number | bigint;
deadline: string | number | bigint;
wallet: WalletClient;
chainId: bigint;
chainId: string | number | bigint;
permissions: Omit<SetPermissionsRequest, "txOptions">[];
permissionFunc?: "setPermission" | "setBatchPermissions";
};

export type PermissionSignatureResponse = Hex;
23 changes: 0 additions & 23 deletions packages/core-sdk/src/types/resources/dispute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,6 @@ import { Address } from "viem";

import { TxOptions } from "../options";

export type Dispute = {
targetIpId: Address; // The ipId that is the target of the dispute
disputeInitiator: Address; // The address of the dispute initiator
arbitrationPolicy: Address; // The address of the arbitration policy
linkToDisputeEvidence: string; // The link of the dispute evidence
targetTag: string; // The target tag of the dispute
currentTag: string; // The current tag of the dispute
};

export type RaiseDisputeRequest = {
targetIpId: Address;
arbitrationPolicy: Address;
Expand All @@ -26,20 +17,6 @@ export type RaiseDisputeResponse = {
arbitrationPolicy?: Address;
};

export type SetDisputeJudgementRequest = {
disputeId: number;
decision: boolean;
calldata?: Address;
txOptions?: TxOptions;
};

export type SetDisputeJudgementResponse = {
txHash: string;
disputeId?: bigint;
decision?: boolean;
data?: Address;
};

export type CancelDisputeRequest = {
disputeId: number | string | bigint;
calldata?: Address;
Expand Down
26 changes: 14 additions & 12 deletions packages/core-sdk/src/utils/sign.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Hex, encodeFunctionData, toFunctionSelector } from "viem";
import { encodeFunctionData, toFunctionSelector } from "viem";

import { accessControllerAbi, accessControllerAddress } from "../abi/generated";
import { getAddress } from "./utils";
import { defaultFunctionSelector } from "../constants/common";
import { PermissionSignatureRequest } from "../types/common";
import { PermissionSignatureRequest, PermissionSignatureResponse } from "../types/common";

/**
* Get the signature for setting permissions.
Expand All @@ -17,7 +17,9 @@ import { PermissionSignatureRequest } from "../types/common";
* @param param.permissionFunc - The permission function,default function is setPermission.
* @returns A Promise that resolves to the signature.
*/
export const getPermissionSignature = async (param: PermissionSignatureRequest): Promise<Hex> => {
export const getPermissionSignature = async (
param: PermissionSignatureRequest,
): Promise<PermissionSignatureResponse> => {
const { ipId, deadline, nonce, wallet, chainId, permissions, permissionFunc } = param;
if (!wallet.signTypedData) {
throw new Error("The wallet client does not support signTypedData, please try again.");
Expand All @@ -32,17 +34,17 @@ export const getPermissionSignature = async (param: PermissionSignatureRequest):
args:
permissionFunction === "setPermission"
? [
permissions[0].ipId,
permissions[0].signer,
permissions[0].to,
getAddress(permissions[0].ipId, "permissions[0].ipId"),
getAddress(permissions[0].signer, "permissions[0].signer"),
getAddress(permissions[0].to, "permissions[0].to"),
permissions[0].func ? toFunctionSelector(permissions[0].func) : defaultFunctionSelector,
permissions[0].permission,
]
: [
permissions.map((item) => ({
ipAccount: item.ipId,
signer: item.signer,
to: item.to,
permissions.map((item, index) => ({
ipAccount: getAddress(item.ipId, `permissions[${index}].ipId`),
signer: getAddress(item.signer, `permissions[${index}].signer`),
to: getAddress(item.to, `permissions[${index}].to`),
func: item.func ? toFunctionSelector(item.func) : defaultFunctionSelector,
permission: item.permission,
})),
Expand All @@ -54,7 +56,7 @@ export const getPermissionSignature = async (param: PermissionSignatureRequest):
name: "Story Protocol IP Account",
version: "1",
chainId: Number(chainId),
verifyingContract: ipId,
verifyingContract: getAddress(ipId, "ipId"),
},
types: {
Execute: [
Expand All @@ -74,7 +76,7 @@ export const getPermissionSignature = async (param: PermissionSignatureRequest):
value: BigInt(0),
data,
nonce: BigInt(nonce),
deadline,
deadline: BigInt(deadline),
},
});
};
Expand Down
66 changes: 0 additions & 66 deletions packages/core-sdk/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import {
Abi,
decodeEventLog,
PublicClient,
encodeAbiParameters,
parseAbiParameters,
Chain,
ContractEventName,
Hex,
Expand All @@ -15,14 +13,8 @@ import {
} from "viem";
import { sepolia } from "viem/chains";

import { TypedData } from "../types/common";
import { SupportedChainIds } from "../types/config";

export function isIntegerString(s: string): boolean {
const num = Number(s);
return !isNaN(num) && parseInt(s, 10) === num;
}

export async function waitTxAndFilterLog<
const TAbi extends Abi | readonly unknown[],
TEventName extends ContractEventName<TAbi> | undefined = ContractEventName<TAbi>,
Expand Down Expand Up @@ -85,64 +77,6 @@ export async function waitTx(
});
}

export function dictToQueryParams(params: Record<string, string | number>): string {
const queryParamList: string[] = [];
for (const key in params) {
const value = params[key];
queryParamList.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}

return queryParamList.join("&");
}

export function typedDataArrayToBytesArray(typedDataArray: Array<TypedData>): Array<Hex> {
const result: Array<Hex> = [];
typedDataArray.forEach(function (typedData: TypedData) {
result.push(typedDataToBytes(typedData));
});
return result;
}

export function typedDataToBytes(typedData: TypedData): Hex {
return encodeAbiParameters(parseAbiParameters(typedData.interface), typedData.data);
}

export function decodeShortstring(hexString: string): string {
if (hexString.startsWith("0x")) {
hexString = hexString.slice(2);
}

// Replace the last two hexadecimal digits with zero
hexString = hexString.substring(0, hexString.length - 2) + "00";

let asciiString = "";
for (let i = 0; i < hexString.length; i += 2) {
const hexByte = hexString.substring(i, i + 2);
if (hexByte === "00") {
break; // Stop if padding (00) is found
}
asciiString += String.fromCharCode(parseInt(hexByte, 16));
}
return asciiString;
}

export function splitIntoBytes32(hexString: string): Hex[] {
if (hexString.startsWith("0x")) {
hexString = hexString.slice(2); // Remove the '0x' prefix
}

if (hexString.length % 64 !== 0) {
throw new Error("Hex string length must be a multiple of 64.");
}

const bytes32Array: string[] = [];
for (let i = 0; i < hexString.length; i += 64) {
bytes32Array.push("0x" + hexString.substring(i, i + 64));
}

return bytes32Array as Hex[];
}

export function chainStringToViemChain(chainId: SupportedChainIds): Chain {
switch (chainId) {
case "11155111":
Expand Down
Loading

0 comments on commit 289661e

Please sign in to comment.