Skip to content

Additional Documentation #16

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

Merged
merged 5 commits into from
Dec 10, 2023
Merged
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: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ docs

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
.parcel-cache

.idea
62 changes: 54 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,69 @@
This is a work in progress. The API is not yet stable, and is subject to change, including breaking changes. Contributions welcome.

# Valorem TypeScript SDK

This is a TypeScript SDK for interacting with Valorem's smart contracts and Trade API.
> This TypeScript SDK provides a streamlined interface for interacting with Valorem's smart
> contracts and Trade API, enabling developers to build applications on top of Valorem's
> infrastructure with ease. Please note that this SDK is a work in progress, and the API is
> subject to change, including potential breaking changes.

## Table of Contents

- [Installation](#installation)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [Examples](#examples)
- [Documentation](#documentation)
- [Contributing](#contributing)
- [License](#license)

## Installation

To install the Valorem TypeScript SDK, choose your package manager and run the appropriate command:

Using npm:

```bash
npm i @valorem-labs-inc/sdk
```

Using pnpm:

```bash
pnpm i @valorem-labs-inc/sdk
```

Using yarn:

```bash
yarn add @valorem-labs-inc/sdk
```

## Getting Started

To get started with the SDK, you'll need to set up the necessary clients from Viem and initialize
the ValoremSDK. Here's a quick start guide:

```typescript
import { createPublicClient, createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { arbitrumGoerli } from 'viem/chains';
import { ValoremSDK } from '@valorem-labs-inc/sdk';

// set up viem clients
// Replace YOUR_PRIVATE_KEY with your Ethereum private key.
const account = privateKeyToAccount(YOUR_PRIVATE_KEY);

// Set up Viem clients for the Arbitrum Goerli test network.
const publicClient = createPublicClient({
chain: arbitrumGoerli,
transport: http(),
});

const walletClient = createWalletClient({
account,
chain: arbitrumGoerli,
transport: http(),
});

// init Valorem SDK
// Initialize the Valorem SDK with the created clients.
const valoremSDK = new ValoremSDK({
publicClient,
walletClient,
Expand All @@ -47,14 +72,35 @@ const valoremSDK = new ValoremSDK({

## Usage

Here's how you can sign in and send requests to the Trade API using the SDK:

```typescript
const webTaker = valoremSDK.webTaker;

// Sign in to the Trade API.
await webTaker.signIn();
// now you can send requests to the Trade API

// Now you can send requests to the Trade API.
```

A full example of using the Valorem Typescript SDK to create an option, request a quote, and fulfill a trade order is located here: [@valorem-labs-inc/trade-interfaces/examples/typescript/src/RFQ_taker.ts](https://github.com/valorem-labs-inc/trade-interfaces/blob/main/examples/typescript/src/RFQ_taker.ts).
Yes, it's really that easy.

## Examples

For a comprehensive example of using the Valorem TypeScript SDK to create options,
request quotes, and fulfill trade orders, check out the [example file](https://github.com/valorem-labs-inc/trade-interfaces/blob/main/examples/typescript/src/RFQ_taker.ts).

## Documentation

For documentation, visit [https://valorem-labs-inc.github.io/typescript-sdk/](https://valorem-labs-inc.github.io/typescript-sdk/)
Documentation for the Valorem TypeScript SDK is available [here](https://valorem-labs-inc.github.io/typescript-sdk/).

## Contributing

We welcome contributions to the Valorem TypeScript SDK!
If you have suggestions, bug reports, or contributions, please submit them
as issues or pull requests in the repository.

## License

The Valorem TypeScript SDK is licensed under the MIT License.
See the [LICENSE](LICENSE) file for more details.
48 changes: 47 additions & 1 deletion src/entities/contracts/base-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import type {
SEAPORT_VALIDATOR_ABI,
} from '../../abi';

/**
* Type helper for creating a contract instance.
*/
type IContract<T extends Abi> = ReturnType<
typeof getContract<
Transport,
Expand All @@ -23,27 +26,70 @@ type IContract<T extends Abi> = ReturnType<
>
>;

/**
* Constructor arguments for creating a new Contract instance.
*/
export interface ContractConstructorArgs {
address: Address;
abi: Abi;
publicClient: PublicClient;
walletClient?: WalletClient;
}

/**
* Interface for the Clearinghouse contract.
*/
export type IClearinghouse = IContract<typeof CLEAR_ABI>;

/**
* Interface for the Seaport contract.
*/
export type ISeaport = IContract<typeof SEAPORT_V1_5_ABI>;

/**
* Interface for the Seaport Validator contract.
*/
export type ISeaportValidator = IContract<typeof SEAPORT_VALIDATOR_ABI>;

/**
* Interface for the ERC20 contract.
*/
export type IERC20 = IContract<typeof ERC20_ABI>;

/** Reusable extension of viem's contract interface */
/**
* Reusable extension of viem's contract interface to interact with smart contracts.
* Provides read and write functionality through the public and wallet clients.
*
* TContract - The contract type which can be either IClearinghouse, ISeaport, or IERC20.
*/
export class Contract<TContract extends IClearinghouse | ISeaport | IERC20> {
/**
* Address of the smart contract.
*/
public address: Address;

/**
* Read-only methods of the smart contract.
*/
public read: TContract['read'];

/**
* Simulated methods of the smart contract.
*/
public simulate: TContract['simulate'];

/**
* State-changing methods of the smart contract. Present only if walletClient is provided.
*/
public write?: TContract['write'];

private contract: TContract;

/**
* Constructs a new Contract instance.
*
* @param args - The constructor arguments containing the contract address, ABI, and clients for interaction.
*/
public constructor({
address,
abi,
Expand Down
17 changes: 17 additions & 0 deletions src/entities/contracts/clearinghouse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,24 @@ import { CLEAR_ABI } from '../../abi';
import type { IClearinghouse, ContractConstructorArgs } from './base-contract';
import { Contract } from './base-contract';

/**
* Specialized contract that extends the generic Contract class to interact
* specifically with the Valorem Clearinghouse. It encapsulates the functionality
* to write and settle option contracts on-chain.
*
* The ClearinghouseContract enables users to write options, execute them,
* and redeem claim tokens post-expiration, handling ERC-20 asset pairs.
*/
export class ClearinghouseContract extends Contract<IClearinghouse> {
/**
* Initializes a new instance of the ClearinghouseContract with the specific address
* and ABI
for the Valorem Clear smart contract. This contract is responsible for the

creation, settlement, and redemption of options and claims within the Valorem ecosystem.
@param args - Contains the publicClient and optionally walletClient for interaction
with the blockchain.
*/
public constructor(
args: Pick<ContractConstructorArgs, 'publicClient' | 'walletClient'>,
) {
Expand Down
28 changes: 28 additions & 0 deletions src/entities/contracts/erc20.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,66 @@ import { erc20ABI } from '@wagmi/core';
import type { ContractConstructorArgs, IERC20 } from './base-contract';
import { Contract } from './base-contract';

/**
* Extends the generic Contract class to interface specifically with ERC20 tokens.
* It provides properties and methods to interact with the standard ERC20 functions.
*/
export class ERC20Contract extends Contract<IERC20> {
private _symbol?: string;
private _decimals?: number;

/**
* Initializes a new instance of the ERC20Contract with the provided arguments
* and begins fetching the token's symbol and decimals for later use.
*
* @param args - Contains the contract address, publicClient, and optionally
* walletClient for interaction with the ERC20 token contract.
*/
public constructor(
args: Pick<
ContractConstructorArgs,
'address' | 'publicClient' | 'walletClient'
>,
) {
super({ ...args, abi: erc20ABI });
// Asynchronously fetch and set the symbol and decimals which are commonly used properties.
void this.getSymbol();
void this.getDecimals();
}

/**
* Gets the token symbol if it has been set; otherwise, throws an error.
* @returns - The symbol of the ERC20 token.
*/
public get symbol() {
if (!this._symbol) throw new Error('Symbol not set');
return this._symbol;
}

/**
* Gets the token decimals if they have been set; otherwise, throws an error.
* @returns - The decimals of the ERC20 token.
*/
public get decimals() {
if (!this._decimals) throw new Error('Decimals not set');
return this._decimals;
}

/**
* Fetches the token symbol from the smart contract if not already cached.
* @returns - A promise that resolves to the symbol of the ERC20 token.
*/
private async getSymbol(): Promise<string> {
if (!this._symbol) {
this._symbol = await this.read.symbol();
}
return this._symbol;
}

/**
* Fetches the token decimals from the smart contract if not already cached.
* @returns - A promise that resolves to the decimals of the ERC20 token.
*/
private async getDecimals(): Promise<number> {
if (!this._decimals) {
this._decimals = await this.read.decimals();
Expand Down
20 changes: 20 additions & 0 deletions src/entities/contracts/seaport-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,32 @@ import type {
ISeaportValidator,
} from './base-contract';

/**
* Provides an interface to the Seaport Validator contract which contains methods
* for validating Seaport orders. It handles the retrieval and processing of error
* and warning messages that assist in debugging order issues.
*/
export class SeaportValidatorContract {
/**
* The address of the Seaport Validator smart contract.
*/
public address: Address;

/**
* Read-only interface of the Seaport Validator contract, containing validation methods.
*/
public read: ISeaportValidator['read'];

private contract: ISeaportValidator;

/**
* Constructs a new SeaportValidatorContract instance, setting up the connection
* to the validator contract deployed at a known address.
*
* @param publicClient - The public client used for interacting with the blockchain.
* @param walletClient - The wallet client used for signed transactions, not necessary
* for read-only interactions with the validator.
*/
public constructor({
publicClient,
walletClient,
Expand Down
16 changes: 16 additions & 0 deletions src/entities/contracts/seaport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,25 @@ import type { ContractConstructorArgs, ISeaport } from './base-contract';
import { Contract } from './base-contract';
import { SeaportValidatorContract } from './seaport-validator';

/**
* Extends the generic Contract class to interact with the Seaport protocol,
* enabling trading functionalities for ERC20, ERC721, ERC1155 and native gas tokens.
* This class provides a structured interface to the Seaport smart contract and its
* operations.
*/
export class SeaportContract extends Contract<ISeaport> {
/**
* An instance of SeaportValidatorContract, for offer validation within the Seaport protocol.
*/
public validator: SeaportValidatorContract;

/**
* Constructs a new SeaportContract instance with the specified arguments.
* Initializes the SeaportValidatorContract for offer validation.
*
* @param args - Contains the publicClient and optionally walletClient for interaction
* with the Seaport protocol.
*/
public constructor(
args: Pick<ContractConstructorArgs, 'publicClient' | 'walletClient'>,
) {
Expand Down
7 changes: 6 additions & 1 deletion src/entities/options/exercisable-option.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,23 @@ import { Option } from './exercisable-option';
import { Claim } from './redeemable-claim';
import { OptionType } from './option-type';

// The unique identifier for the option we want to test.
const optionId =
39619444411110155182191577564943662405077439414287374917766485031893178777600n;

describe('Exercisable Option', () => {
it('Should be able to load a Option', async () => {
it('Should be able to load an Option', async () => {
// Load the option from its ID using the clearinghouse contract.
const option = await Option.fromId(optionId, clearinghouse);

// Assert various properties of the option to ensure it has loaded correctly.
expect(option.tokenId).toEqual(optionId);
expect(option.tokenType).toEqual(1);
expect(option.typeExists).toBeTruthy();
expect(option.optionTypeId).toEqual(optionId);
expect(option.optionInfo).toBeDefined();

// Check the instance types to confirm the option's inheritance and type.
expect(option instanceof Option).toBeTruthy();
expect(option instanceof OptionType).toBeTruthy();
expect(option instanceof Claim).toBeFalsy();
Expand Down
Loading