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

Upgrade version to 1.10.0 #184

Merged
merged 9 commits into from
May 3, 2024
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ yarn add @ainblockchain/ain-js
## Examples
```
const Ain = require('./lib/ain').default;
const ain = new Ain('http://node.ainetwork.ai:8080/');
const ain = new Ain('http://localhost:8081/', 'ws://localhost:5100/');
// or const ain = new Ain('https://testnet-api.ainetwork.ai/', 'wss://testnet-event.ainetwork.ai/');

ain.wallet.create(1);

Expand Down
16 changes: 8 additions & 8 deletions __tests__/ain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('ain-js', function() {
it('chainId', function() {
expect(ain.chainId).toBe(0);
expect(ain.wallet.chainId).toBe(0);
ain.setProvider(test_node_1, 2);
ain.setProvider(test_node_1, null, 2);
expect(ain.chainId).toBe(2);
expect(ain.wallet.chainId).toBe(2);
});
Expand Down Expand Up @@ -273,7 +273,7 @@ describe('ain-js', function() {
ain.wallet.setDefaultAccount(TEST_ADDR);
const sig = ain.wallet.sign(message);
const addr:string = String(ain.wallet.defaultAccount!.address);
expect(Ain.utils.ecVerifySig(message, sig, addr)).toBe(true);
expect(ain.wallet.verifySignature(message, sig, addr)).toBe(true);
});

it('signTransaction', function() {
Expand All @@ -289,7 +289,7 @@ describe('ain-js', function() {
}
const sig = ain.wallet.signTransaction(tx);
const addr:string = String(ain.wallet.defaultAccount!.address);
expect(Ain.utils.ecVerifySig(tx, sig, addr)).toBe(true);
expect(ain.wallet.verifySignature(tx, sig, addr)).toBe(true);
});

it('recover', function() {
Expand Down Expand Up @@ -401,7 +401,7 @@ describe('ain-js', function() {

it('chainId', function() {
// chainId = 0
ain.setProvider(test_node_2, 0);
ain.setProvider(test_node_2, null, 0);
let tx: TransactionBody = {
nonce: 17,
gas_price: 500,
Expand All @@ -415,11 +415,11 @@ describe('ain-js', function() {
let sig = ain.wallet.signTransaction(tx);
let addr:string = String(ain.wallet.defaultAccount!.address);
expect(ain.wallet.verifySignature(tx, sig, addr)).toBe(true);
expect(() => Ain.utils.ecVerifySig(tx, sig, addr, 2)).toThrow('[ain-util] ecRecoverPub: Invalid signature v value');
expect(ain.wallet.verifySignature(tx, sig, addr, 2)).toBe(false);
expect(ain.wallet.recover(sig)).toBe(addr);

// chainId = 2
ain.setProvider(test_node_2, 2);
ain.setProvider(test_node_2, null, 2);
tx = {
nonce: 17,
timestamp: Date.now(),
Expand All @@ -432,7 +432,7 @@ describe('ain-js', function() {
sig = ain.wallet.signTransaction(tx);
addr = String(ain.wallet.defaultAccount!.address);
expect(ain.wallet.verifySignature(tx, sig, addr)).toBe(true);
expect(() => Ain.utils.ecVerifySig(tx, sig, addr, 0)).toThrow('[ain-util] ecRecoverPub: Invalid signature v value');
expect(ain.wallet.verifySignature(tx, sig, addr, 0)).toBe(false);
expect(ain.wallet.recover(sig)).toBe(addr);
});
});
Expand Down Expand Up @@ -476,7 +476,7 @@ describe('ain-js', function() {
}

beforeAll(async () => {
ain.setProvider(test_node_2, 0);
ain.setProvider(test_node_2, null, 0);
const newAccounts = ain.wallet.create(2);
defaultAddr = ain.wallet.defaultAccount!.address as string;
addr1 = newAccounts[0];
Expand Down
4 changes: 2 additions & 2 deletions __tests__/ain_raw.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const TEST_ADDR = '0x08Aed7AF9354435c38d52143EE50ac839D20696b';
jest.setTimeout(180000);

describe('ain-js', function() {
const ain = new Ain(test_node_1, 0, { rawResultMode: true });
const ain = new Ain(test_node_1, null, 0, { rawResultMode: true });

beforeAll(() => {
ain.wallet.add(TEST_SK);
Expand Down Expand Up @@ -61,7 +61,7 @@ describe('ain-js', function() {
}

beforeAll(async () => {
ain.setProvider(test_node_2, 0);
ain.setProvider(test_node_2, null, 0);
const newAccounts = ain.wallet.create(2);
defaultAddr = ain.wallet.defaultAccount!.address as string;
addr1 = newAccounts[0];
Expand Down
8 changes: 5 additions & 3 deletions __tests__/event_manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
import Ain from '../src/ain';
import { FAILED_TO_REGISTER_ERROR_CODE } from '../src/constants';
import { FilterDeletionReasons, TransactionStates } from '../src/types';

const { test_event_handler_node } = require('./test_data');
const {
test_node_3,
test_event_handler_node,
} = require('./test_data');

jest.setTimeout(180000);

describe('Event Handler', function() {
let ain = new Ain(test_event_handler_node);
let ain = new Ain(test_node_3, test_event_handler_node);
let eventFilterId: string;

beforeAll(async () => {
Expand Down
3 changes: 2 additions & 1 deletion __tests__/test_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export const test_seed = 'receive ocean impact unaware march just dragon easy po

export const test_node_1 = 'http://localhost:8081';
export const test_node_2 = 'http://localhost:8082';
export const test_event_handler_node = 'http://localhost:8083';
export const test_node_3 = 'http://localhost:8083';
export const test_event_handler_node = 'ws://localhost:5100';
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ainblockchain/ain-js",
"version": "1.9.0",
"version": "1.10.0",
"description": "",
"main": "lib/ain.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion samples/event_manager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const Ain = require('@ainblockchain/ain-js').default;
const ain = new Ain('https://testnet-event.ainetwork.ai/');
const ain = new Ain('https://testnet-api.ainetwork.ai/', 'wss://testnet-event.ainetwork.ai/');

async function main() {
await ain.em.connect(); // NOTE: https://docs.ainetwork.ai/reference/blockchain-sdk/ain-js/ain.em#connect
Expand Down
14 changes: 10 additions & 4 deletions src/ain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export default class Ain {
public axiosConfig: AxiosRequestConfig | undefined;
/** The chain ID of the blockchain network. */
public chainId: number;
/** The endpoint Url of the event handler websocket server. */
public eventHandlerUrl?: string | null;
/** The network provider object. */
public provider: Provider;
/** The raw result mode option. */
Expand All @@ -43,12 +45,14 @@ export default class Ain {
/**
* Creates a new Ain object.
* @param {string} providerUrl The endpoint URL of the network provider.
* @param {string} eventHandlerUrl The endpoint URL of the event handler websocket server.
* @param {number} chainId The chain ID of the blockchain network.
* @param {AinOptions} ainOptions The options of the class.
*/
constructor(providerUrl: string, chainId?: number, ainOptions?: AinOptions) {
constructor(providerUrl: string, eventHandlerUrl?: string, chainId?: number, ainOptions?: AinOptions) {
this.axiosConfig = ainOptions?.axiosConfig;
this.provider = new Provider(this, providerUrl, this.axiosConfig);
this.eventHandlerUrl = eventHandlerUrl;
this.chainId = chainId || 0;
this.rawResultMode = ainOptions?.rawResultMode || false;
this.net = new Network(this.provider);
Expand All @@ -61,15 +65,17 @@ export default class Ain {

/**
* Sets a new provider.
* @param {string} providerUrl The endpoint URL of the network provider.
* @param {number} chainId The chain ID of the blockchain network.
* @param {string} providerUrl The endpoint URL of the network provider. e.g. http://localhost:8081, https://testnet-api.ainetwork.ai
* @param {string} eventHandlerUrl The endpoint URL of the event handler websocket server. e.g. ws://localhost:5100, wss://testnet-event.ainetwork.ai
* @param {number} chainId The chain ID of the blockchain network. e.g. 0 for local or testnet, and 1 for mainnet
* @param {AxiosRequestConfig} axiosConfig The axios request config.
*/
setProvider(providerUrl: string, chainId?: number, axiosConfig?: AxiosRequestConfig | undefined) {
setProvider(providerUrl: string, eventHandlerUrl?: string, chainId?: number, axiosConfig?: AxiosRequestConfig | undefined) {
if (axiosConfig) {
this.axiosConfig = axiosConfig;
}
this.provider = new Provider(this, providerUrl, this.axiosConfig);
this.eventHandlerUrl = eventHandlerUrl;
this.chainId = chainId || 0;
this.db = new Database(this, this.provider);
this.net = new Network(this.provider);
Expand Down
12 changes: 8 additions & 4 deletions src/event-manager/event-channel-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ export default class EventChannelClient {
private readonly _eventCallbackManager: EventCallbackManager;
/** The web socket client. */
private _ws?: WebSocket | WebSocketBE;
/** The blockchain endpoint URL. */
private _endpointUrl?: string;
/** Whether it's connected or not. */
private _isConnected: boolean;
/** The handshake timeout object. */
Expand All @@ -42,7 +40,6 @@ export default class EventChannelClient {
this._ain = ain;
this._eventCallbackManager = eventCallbackManager;
this._ws = undefined;
this._endpointUrl = undefined;
this._isConnected = false;
this._handshakeTimeout = undefined;
this._heartbeatTimeout = undefined;
Expand All @@ -63,6 +60,13 @@ export default class EventChannelClient {
reject(new Error(`Can't connect multiple channels`));
return;
}
const url = this._ain.eventHandlerUrl;
if (!url) {
reject(new Error(`eventHandlerUrl is not set properly: ${url}`));
return;
}
// TODO(platfowner): Remove or re-implement without using getEventHandlerNetworkInfo() below.
/*
const eventHandlerNetworkInfo = await this._ain.net.getEventHandlerNetworkInfo();
const url = eventHandlerNetworkInfo.url;
if (!url) {
Expand All @@ -86,8 +90,8 @@ export default class EventChannelClient {
reject(new Error(`Exceed event channel limit! (node:${url})`));
return;
}
*/

this._endpointUrl = url;
// NOTE(platfowner): Fix WebSocket module import issue (see https://github.com/ainblockchain/ain-js/issues/177).
this._ws = isBrowser ? new WebSocket(url) : new WebSocketBE(url);
// NOTE(platfowner): A custom handshake timeout (see https://github.com/ainblockchain/ain-js/issues/171).
Expand Down
3 changes: 2 additions & 1 deletion src/he/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ This is a function developed for testing purposes. It returns the secret key cur

## Usage
```ts
const ain = new Ain('http://node.ainetwork.ai:8080');
const ain = new Ain('http://localhost:8081', 'ws://localhost:5100');
// or const ain = new Ain('https://testnet-api.ainetwork.ai/', 'wss://testnet-event.ainetwork.ai/');
await ain.he.init();
const TEST_DATA = Float64Array.from({ length: ain.he.seal.encoder.slotCount }).map((x, i) => i);
const cipherText = ain.he.encrypt(TEST_DATA);
Expand Down
11 changes: 9 additions & 2 deletions src/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,10 +367,17 @@ export default class Wallet {
* @param {any} data The data used in the signing.
* @param {string} signature The signature to verify.
* @param {string} address The address to verify.
* @param {number} chainId The chain Id for test purposes only.
* @returns {boolean}
*/
verifySignature(data: any, signature: string, address: string): boolean {
return Ain.utils.ecVerifySig(data, signature, address, this.chainId);
verifySignature(data: any, signature: string, address: string, chainId?: number): boolean {
try {
return Ain.utils.ecVerifySig(data, signature, address, chainId !== undefined ? chainId : this.chainId);
} catch (err: unknown) {
let errMsg = err instanceof Error ? err.message : err;
console.log(`Signature verification failed with error: ${errMsg}`);
return false;
}
}

/**
Expand Down
Loading