Skip to content

Commit

Permalink
Merge pull request #215 from storyprotocol/dev
Browse files Browse the repository at this point in the history
Publish rc15
  • Loading branch information
edisonz0718 authored Jul 2, 2024
2 parents d7367a0 + 2629456 commit 0393af4
Show file tree
Hide file tree
Showing 54 changed files with 4,944 additions and 1,012 deletions.
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Once core-react is published to npm, react-sdk can be updated to use it
link-workspace-packages: false
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
4 changes: 1 addition & 3 deletions packages/core-sdk/src/resources/license.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,7 @@ export class LicenseClient {
licenseTermsId: request.licenseTermsId,
});
if (isAttachedLicenseTerms) {
throw new Error(
`License terms id ${request.licenseTermsId} is already attached to the IP with id ${request.ipId}.`,
);
return { txHash: "", success: false };
}
const txHash = await this.licensingModuleClient.attachLicenseTerms({
ipId: request.ipId,
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;
24 changes: 0 additions & 24 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 @@ -23,21 +14,6 @@ export type RaiseDisputeRequest = {
export type RaiseDisputeResponse = {
txHash: string;
disputeId?: bigint;
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 = {
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
6 changes: 3 additions & 3 deletions packages/core-sdk/test/integration/dispute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe("Dispute Functions", () => {

before(async () => {
clientA = getStoryClientInSepolia();
clientB = getStoryClientInSepolia(process.env.SEPOLIA_WALLET_PRIVATE_KEY2 as Address);
clientB = getStoryClientInSepolia();
const mockERC20 = new MockERC20();
await mockERC20.approve(arbitrationPolicyAddress);
const tokenId = await getTokenId();
Expand All @@ -33,7 +33,7 @@ describe("Dispute Functions", () => {
).ipId!;
});

it("raise a dispute", async () => {
it("should not throw error when raise a dispute", async () => {
const raiseDisputeRequest: RaiseDisputeRequest = {
targetIpId: ipIdB,
arbitrationPolicy: arbitrationPolicyAddress,
Expand All @@ -50,7 +50,7 @@ describe("Dispute Functions", () => {
expect(response.disputeId).to.be.a("bigint");
});

it("cancel a dispute", async () => {
it("should not throw error when cancel a dispute", async () => {
const cancelDispute: CancelDisputeRequest = {
disputeId: disputeId,
txOptions: {
Expand Down
2 changes: 0 additions & 2 deletions packages/core-sdk/test/integration/ipAccount.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
accessControllerAddress,
coreMetadataModuleAddress,
} from "../../src/abi/generated";
import { privateKeyToAccount } from "viem/accounts";
import { getDeadline } from "../../src/utils/sign";

chai.use(chaiAsPromised);
Expand Down Expand Up @@ -61,7 +60,6 @@ describe("Ip Account functions", () => {
});

it("should not throw error when executeWithSig setting permission", async () => {
const account = privateKeyToAccount(process.env.SEPOLIA_WALLET_PRIVATE_KEY as Hex);
const state = await client.ipAccount.getIpAccountNonce(ipId);
const expectedState = state + 1n;
const deadline = getDeadline(60000n);
Expand Down
Loading

0 comments on commit 0393af4

Please sign in to comment.