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

[WIP] Add logic to handle undefined client #295

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions 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.23",
"version": "1.1.0-stable",
"description": "Story Protocol Core SDK",
"main": "dist/story-protocol-core-sdk.cjs.js",
"module": "dist/story-protocol-core-sdk.esm.js",
Expand All @@ -17,7 +17,7 @@
],
"scripts": {
"build": "pnpm run fix && preconstruct build",
"test": "pnpm run test:unit && pnpm run test:integration",
"test": "pnpm run test:unit",
"test:unit": "TS_NODE_PROJECT='./tsconfig.test.json' c8 --all --src ./src mocha -r ts-node/register './test/unit/**/*.test.ts'",
"test:integration": "TS_NODE_PROJECT='./tsconfig.test.json' mocha -r ts-node/register './test/integration/**/*.test.ts' --timeout 240000",
"fix": "pnpm run format:fix && pnpm run lint:fix",
Expand Down
2 changes: 1 addition & 1 deletion packages/core-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ if (typeof process !== "undefined") {
export class StoryClient {
private readonly config: StoryConfig & { chainId: SupportedChainIds };
private readonly rpcClient: PublicClient;
private readonly wallet: SimpleWalletClient;
public readonly wallet: SimpleWalletClient;
private _ipAsset: IPAssetClient | null = null;
private _permission: PermissionClient | null = null;
private _license: LicenseClient | null = null;
Expand Down
1 change: 1 addition & 0 deletions packages/core-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export type {
MintLicenseTokensResponse,
LicenseTermsId,
LicenseTerms,
RegisterPILTermsRequest,
} from "./types/resources/license";
export { PIL_TYPE } from "./types/resources/license";

Expand Down
41 changes: 31 additions & 10 deletions packages/react-sdk/generator/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ const visit = (file) => {
if (
ts.isMethodDeclaration(member) &&
(member.modifiers?.some(
(m) => m.kind === ts.SyntaxKind.PublicKeyword
(m) => m.kind === ts.SyntaxKind.PublicKeyword,
) ??
true) &&
member.name &&
ts.isIdentifier(member.name)
) {
const requests = [];
const isAsync = member.modifiers?.some(
(modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword
(modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword,
);
program.getTypeChecker().getSignatureFromDeclaration(member);
member.parameters.forEach((parameter) => {
Expand All @@ -72,7 +72,7 @@ const visit = (file) => {
ts
.getLeadingCommentRanges(sourceFile.text, member.pos)
?.map((range) =>
sourceFile.text.substring(range.pos, range.end).trim()
sourceFile.text.substring(range.pos, range.end).trim(),
) || [],
defaultValues: undefined, // Get default value,
};
Expand Down Expand Up @@ -104,16 +104,16 @@ files.forEach((file, index) => {
(acc, curr) =>
acc.concat(
curr.requests.map((item) => item.type),
curr.responseType
curr.responseType,
),
[]
[],
);
const filteredTypes = [
...new Set(
types
.filter((type) => !isPrimitiveType(type))
.filter((type) => !isViemType(type))
.filter((type) => !isEnclosedInCurlyBraces(type))
.filter((type) => !isEnclosedInCurlyBraces(type)),
),
];
exportTypes.push(...filteredTypes);
Expand All @@ -123,8 +123,29 @@ files.forEach((file, index) => {
name: fileName,
methodNames: asyncMethods,
viemTypes: [...new Set(types.filter((type) => isViemType(type)))],
})
}),
);

const returnObjectWithUndefined = asyncMethods.reduce((acc, method) => {
acc[method] = undefined;
return acc;
}, {});

sources.push(
ejs.render(
`
if (!client) {
return {
loadings,
errors,
<%= Object.entries(returnObjectWithUndefined).map(([key, value]) => \`\${key}: \${value}\`).join(',\\n ') %>
};
}
`,
{ returnObjectWithUndefined },
),
);

const methodTemplates = methods.map((method) => {
return ejs.render(resourceTemplate.methodTemplate, {
method: method,
Expand All @@ -138,7 +159,7 @@ files.forEach((file, index) => {
ejs.render(resourceTemplate.endTemplate, {
methodNames,
name: fileName,
})
}),
);
fs.writeFileSync(`src/resources/use${fileName}.ts`, sources.join("\n"));
});
Expand All @@ -151,7 +172,7 @@ exec("npm run fix", (error) => {
if (error) {
console.log(
"\x1b[31m%s\x1b[0m",
"\nError occurred while running npm run fix command. Please run `npm run fix` manually."
"\nError occurred while running npm run fix command. Please run `npm run fix` manually.",
);
bar.stop();
return;
Expand All @@ -160,6 +181,6 @@ exec("npm run fix", (error) => {
bar.stop();
console.log(
"\x1b[32m%s\x1b[0m",
"React SDK templates generated successfully!"
"React SDK templates generated successfully!",
);
});
5 changes: 3 additions & 2 deletions packages/react-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@story-protocol/react-sdk",
"version": "0.0.2",
"version": "1.1.0-stable",
"description": "The Story Protocol React SDK",
"main": "dist/story-protocol-react-sdk.cjs.js",
"module": "dist/story-protocol-react-sdk.esm.js",
Expand All @@ -14,6 +14,7 @@
"scripts": {
"generate": "node ./generator/index.js",
"build": "pnpm run fix && preconstruct build",
"test:integration": "jest -i",
"fix": "pnpm run format:fix && pnpm run lint:fix",
"format": "prettier --check .",
"format:fix": "prettier --write .",
Expand Down Expand Up @@ -62,7 +63,7 @@
},
"license": "MIT",
"dependencies": {
"@story-protocol/core-sdk": "1.0.0-rc.22",
"@story-protocol/core-sdk": "1.1.0-stable",
"react": "^18.3.1",
"viem": "^2.8.12"
},
Expand Down
10 changes: 9 additions & 1 deletion packages/react-sdk/src/StoryProtocolContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,21 @@ const StoryContext = createContext<StoryClient>({} as StoryClient);
const StoryProvider = ({ config, children }: Props) => {
const [client, setClient] = useState<StoryClient>();

if (!client) {
if (!config.wallet) {
setClient(
StoryClient.newClient({
transport: config.transport,
}),
);
} else if (!client) {
setClient(StoryClient.newClient(config));
}

return (
<StoryContext.Provider value={client!}>{children}</StoryContext.Provider>
);
};

const useStoryContext = (): StoryClient => {
return useContext(StoryContext);
};
Expand Down
4 changes: 3 additions & 1 deletion packages/react-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type {
IPAccountExecuteWithSigRequest,
IPAccountExecuteWithSigResponse,
IpAccountStateResponse,
TokenResponse,
GenerateCreatorMetadataParam,
IpCreator,
GenerateIpMetadataParam,
Expand All @@ -41,8 +42,9 @@ export type {
RegisterIpAndMakeDerivativeRequest,
RegisterIpAndMakeDerivativeResponse,
MintAndRegisterIpAndMakeDerivativeRequest,
RegisterNonComSocialRemixingPILRequest,
RegisterPILTermsRequest,
RegisterPILResponse,
RegisterNonComSocialRemixingPILRequest,
RegisterCommercialUsePILRequest,
RegisterCommercialRemixPILRequest,
AttachLicenseTermsRequest,
Expand Down
16 changes: 13 additions & 3 deletions packages/react-sdk/src/resources/useDispute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ const useDispute = () => {
resolveDispute: null,
});

if (!client) {
return {
loadings,
errors,
raiseDispute: undefined,
cancelDispute: undefined,
resolveDispute: undefined,
};
}

/**
* Raises a dispute on a given ipId
* @param request - The request object containing necessary data to raise a dispute.
Expand All @@ -47,7 +57,7 @@ const useDispute = () => {
"raiseDispute",
client.dispute.raiseDispute.bind(client.dispute),
setLoadings,
setErrors
setErrors,
);

/**
Expand All @@ -70,7 +80,7 @@ const useDispute = () => {
"cancelDispute",
client.dispute.cancelDispute.bind(client.dispute),
setLoadings,
setErrors
setErrors,
);

/**
Expand All @@ -91,7 +101,7 @@ const useDispute = () => {
"resolveDispute",
client.dispute.resolveDispute.bind(client.dispute),
setLoadings,
setErrors
setErrors,
);

return {
Expand Down
37 changes: 32 additions & 5 deletions packages/react-sdk/src/resources/useIpAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import {
IPAccountExecuteWithSigRequest,
IPAccountExecuteWithSigResponse,
IpAccountStateResponse,
TokenResponse,
} from "@story-protocol/core-sdk";
import { Address } from "viem";
import { useState } from "react";

import { useStoryContext } from "../StoryProtocolContext";
Expand All @@ -16,13 +18,26 @@ const useIpAccount = () => {
execute: false,
executeWithSig: false,
getIpAccountNonce: false,
getToken: false,
});
const [errors, setErrors] = useState<Record<string, string | null>>({
execute: null,
executeWithSig: null,
getIpAccountNonce: null,
getToken: null,
});

if (!client) {
return {
loadings,
errors,
execute: undefined,
executeWithSig: undefined,
getIpAccountNonce: undefined,
getToken: undefined,
};
}

/** Executes a transaction from the IP Account.
* @param request - The request object containing necessary data to execute IP Account a transaction.
* @param request.ipId The Ip Id to get ip account.
Expand All @@ -40,7 +55,7 @@ const useIpAccount = () => {
"execute",
client.ipAccount.execute.bind(client.ipAccount),
setLoadings,
setErrors
setErrors,
);

/** Executes a transaction from the IP Account.
Expand All @@ -62,21 +77,32 @@ const useIpAccount = () => {
"executeWithSig",
client.ipAccount.executeWithSig.bind(client.ipAccount),
setLoadings,
setErrors
setErrors,
);

/** Returns the IPAccount&#39;s internal nonce for transaction ordering.
* @param ipId The IP ID
* @returns The nonce for transaction ordering.
* @returns A Promise that resolves to the IP Account&#39;s nonce.
*/
const getIpAccountNonce = withLoadingErrorHandling<
string,
Address,
IpAccountStateResponse
>(
"getIpAccountNonce",
client.ipAccount.getIpAccountNonce.bind(client.ipAccount),
setLoadings,
setErrors
setErrors,
);

/**
* Returns the identifier of the non-fungible token which owns the account
* @returns A Promise that resolves to an object containing the chain ID, token contract address, and token ID.
*/
const getToken = withLoadingErrorHandling<Address, TokenResponse>(
"getToken",
client.ipAccount.getToken.bind(client.ipAccount),
setLoadings,
setErrors,
);

return {
Expand All @@ -85,6 +111,7 @@ const useIpAccount = () => {
execute,
executeWithSig,
getIpAccountNonce,
getToken,
};
};
export default useIpAccount;
Loading