Skip to content

Commit

Permalink
Merge main (#460)
Browse files Browse the repository at this point in the history
* merge main

* update wallet pro

* fix test

* update version
  • Loading branch information
Ben-Rey authored Aug 22, 2023
1 parent dbc6752 commit d370c74
Show file tree
Hide file tree
Showing 22 changed files with 665 additions and 1,265 deletions.
660 changes: 21 additions & 639 deletions README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions examples/smartContracts/deployer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export async function awaitTxConfirmation(
.smartContracts()
.awaitRequiredOperationStatus(
deploymentOperationId,
EOperationStatus.FINAL,
EOperationStatus.FINAL_SUCCESS,
);
console.log(
`Transaction with Operation ID ${chalk.yellow(
Expand All @@ -57,7 +57,7 @@ export async function awaitTxConfirmation(
throw new Error(ex);
}

if (status !== EOperationStatus.FINAL) {
if (status !== EOperationStatus.FINAL_SUCCESS) {
const msg = chalk.red(
`Transaction ${chalk.yellow(
deploymentOperationId,
Expand Down
4 changes: 2 additions & 2 deletions examples/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ if (!receiverPrivateKey) {

const isVerified = await web3Client
.wallet()
.verifySignature(message, signedMessage, deployerAccount.publicKey);
.verifySignature(message, signedMessage);
console.log('Signature verification: ', isVerified);

// send from base account to receiver
Expand All @@ -136,7 +136,7 @@ if (!receiverPrivateKey) {
console.log('Awaiting Finalization ...');
await web3Client
.smartContracts()
.awaitRequiredOperationStatus(txId[0], EOperationStatus.FINAL);
.awaitRequiredOperationStatus(txId[0], EOperationStatus.FINAL_SUCCESS);

console.log('Polling events ... ');
const events = await EventPoller.getEventsOnce(
Expand Down
628 changes: 140 additions & 488 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@massalabs/massa-web3",
"version": "1.23.0",
"version": "1.24.0",
"description": "massa's web3 sdk client",
"main": "dist/cmd/index.js",
"module": "dist/esm/index.js",
Expand Down Expand Up @@ -58,7 +58,7 @@
"bundle.min.js"
],
"dependencies": {
"@massalabs/wallet-provider": "^1.2.0",
"@massalabs/wallet-provider": "^1.3.2",
"@noble/ed25519": "^1.7.3",
"@noble/hashes": "^1.2.0",
"@types/ws": "^8.5.4",
Expand All @@ -80,7 +80,7 @@
"devDependencies": {
"@massalabs/eslint-config": "^0.0.9",
"@massalabs/prettier-config-as": "^0.0.2",
"@massalabs/web3-utils": "^1.2.0",
"@massalabs/web3-utils": "^1.4.1",
"@types/bn.js": "^5.1.1",
"@types/jest": "^29.5.2",
"@types/node": "^18.13.0",
Expand Down
8 changes: 4 additions & 4 deletions powered-by.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ The following is a list of all the dependencies of this project:

**License:** ISC - perpetual

**Used version:** 1.2.0
**Used version:** 1.4.1

**Many thanks to:**

Expand All @@ -189,7 +189,7 @@ The following is a list of all the dependencies of this project:

**License:** MIT - perpetual

**Used version:** 18.17.1
**Used version:** 18.17.4

**Many thanks to:** n/a

Expand Down Expand Up @@ -229,7 +229,7 @@ The following is a list of all the dependencies of this project:

**License:** MIT - perpetual

**Used version:** 8.45.0
**Used version:** 8.46.0

**Many thanks to:** [Nicholas C. Zakas]([email protected])

Expand All @@ -253,7 +253,7 @@ The following is a list of all the dependencies of this project:

**License:** MIT - perpetual

**Used version:** 2.27.5
**Used version:** 2.28.0

**Many thanks to:** [Ben Mosher]([email protected])

Expand Down
2 changes: 2 additions & 0 deletions scripts/publish-dev.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ BRANCH=${GITHUB_REF##*/}
TAG=""
if [[ "$BRANCH" == "buildnet" ]]; then
TAG="buildnet-"
elif [[ "$BRANCH" == "testnet" ]]; then
TAG="testnet-"
fi

npm publish --access public --tag ${TAG}dev
8 changes: 6 additions & 2 deletions src/interfaces/EOperationStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
export enum EOperationStatus {
INCLUDED_PENDING = 0,
AWAITING_INCLUSION = 1,
FINAL = 2,
INCONSISTENT = 3,
FINAL_SUCCESS = 2,
NOT_FOUND = 4,
INCONSISTENT = 3,
FINAL_ERROR = 5,
SPECULATIVE_SUCCESS = 6,
SPECULATIVE_ERROR = 7,
UNEXECUTED_OR_EXPIRED = 8,
}
8 changes: 5 additions & 3 deletions src/interfaces/ICallData.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Args } from '@massalabs/web3-utils';

/**
* Represents the information for a smart contract call.
*
Expand All @@ -11,13 +13,13 @@
* @see coins of type `bigint` represents the extra coins that are spent from the caller's balance and transferred to the target.
* @see targetAddress of type `string` represents the target smart contract address.
* @see functionName of type `string` represents the target function name. No function is called if empty.
* @see parameter of type `Array<number>` represents the parameters to pass to the target function.
* @see parameter of type `Array<number>` or an Args represents the parameters to pass to the target function.
*/
export interface ICallData {
fee: bigint;
maxGas: bigint;
coins: bigint;
coins?: bigint;
targetAddress: string;
functionName: string;
parameter: Array<number>;
parameter: Array<number> | Args;
}
4 changes: 3 additions & 1 deletion src/interfaces/IReadData.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Args } from '@massalabs/web3-utils';

/**
* Represents the data of a read operation.
*
Expand All @@ -11,6 +13,6 @@ export interface IReadData {
maxGas: bigint;
targetAddress: string;
targetFunction: string;
parameter: Array<number>;
parameter: Array<number> | Args;
callerAddress?: string;
}
1 change: 1 addition & 0 deletions src/interfaces/ISignature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
* @see base58Encoded - The base58 encoded signature.
*/
export interface ISignature {
publicKey: string;
base58Encoded: string;
}
9 changes: 8 additions & 1 deletion src/web3/BaseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,14 @@ export class BaseClient {
);

// parameter
const parametersEncoded = new Uint8Array((data as ICallData).parameter);
const param = (data as ICallData).parameter;
let serializedParam: number[]; // serialized parameter
if (param instanceof Array) {
serializedParam = param;
} else {
serializedParam = param.serialize();
}
const parametersEncoded = new Uint8Array(serializedParam);
const parametersLengthEncoded = Buffer.from(
varintEncode(parametersEncoded.length),
);
Expand Down
2 changes: 2 additions & 0 deletions src/web3/PublicApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ export class PublicApiClient extends BaseClient implements IPublicApiClient {
* @param addressesKeys - An array of objects containing address and key data.
*
* @returns A promise that resolves to an array of datastore entries.
*
* @remarks returned values could be easily converted into string if needed using e.g.: bytesToStr(scStorageValue[0].final_value)
*/
public async getDatastoreEntries(
addressesKeys: Array<IDatastoreEntryInput>,
Expand Down
56 changes: 47 additions & 9 deletions src/web3/SmartContractsClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
IContractReadOperationResponse,
IContractReadOperationData,
IEvent,
Args,
} from '@massalabs/web3-utils';

const MAX_READ_BLOCK_GAS = BigInt(4_294_967_295);
Expand Down Expand Up @@ -76,7 +77,7 @@ export class SmartContractsClient
}

/**
* Deploy a smart contract on th massa blockchain by creating and sending
* Deploy a smart contract on the massa blockchain by creating and sending
* an operation containing byte code.
*
* @remarks
Expand Down Expand Up @@ -119,6 +120,24 @@ export class SmartContractsClient
if (!sender) {
throw new Error(`No tx sender available`);
}
// check the max. allowed gas
if (callData.maxGas > MAX_READ_BLOCK_GAS) {
throw new Error(
`The gas submitted ${callData.maxGas.toString()} exceeds the max. allowed block gas of ${MAX_READ_BLOCK_GAS.toString()}`,
);
}

callData.coins = callData.coins || BigInt(0);

// check that the sender has enough balance to pay for coins
const senderBalance: IBalance = await this.walletClient.getAccountBalance(
sender.address(),
);
if (senderBalance.final < callData.coins) {
throw new Error(
`The sender ${sender.address()} does not have enough balance to pay for the coins`,
);
}
return await sender.callSmartContract(callData);
}

Expand All @@ -140,6 +159,9 @@ export class SmartContractsClient
);
}

if (readData.parameter instanceof Args)
readData.parameter = readData.parameter.serialize();

// request data
let baseAccountSignerAddress: string | null = null;
if (this.walletClient.getBaseAccount()) {
Expand Down Expand Up @@ -295,9 +317,9 @@ export class SmartContractsClient
});
}
return {
returnValue: jsonRpcCallResult[0].result.Ok as Uint8Array,
info: jsonRpcCallResult[0] as IExecuteReadOnlyData,
} as IExecuteReadOnlyResponse;
returnValue: new Uint8Array(jsonRpcCallResult[0].result.Ok),
info: jsonRpcCallResult[0],
};
}

/**
Expand All @@ -313,15 +335,31 @@ export class SmartContractsClient
if (!operationData || operationData.length === 0)
return EOperationStatus.NOT_FOUND;
const opData = operationData[0];
if (opData.is_operation_final) {
return EOperationStatus.FINAL;
}
if (opData.in_blocks.length > 0) {
return EOperationStatus.INCLUDED_PENDING;
if (opData.is_operation_final === null && opData.op_exec_status === null) {
return EOperationStatus.UNEXECUTED_OR_EXPIRED;
}
if (opData.in_pool) {
return EOperationStatus.AWAITING_INCLUSION;
}
if (opData.is_operation_final && opData.op_exec_status) {
return EOperationStatus.FINAL_SUCCESS;
}
// since null is a falsy value, we need to check for false explicitly
if (opData.is_operation_final && opData.op_exec_status === false) {
return EOperationStatus.FINAL_ERROR;
}
if (opData.is_operation_final === false && opData.op_exec_status) {
return EOperationStatus.SPECULATIVE_SUCCESS;
}
if (
opData.is_operation_final === false &&
opData.op_exec_status === false
) {
return EOperationStatus.SPECULATIVE_ERROR;
}
if (opData.in_blocks.length > 0) {
return EOperationStatus.INCLUDED_PENDING;
}

return EOperationStatus.INCONSISTENT;
}
Expand Down
13 changes: 10 additions & 3 deletions src/web3/WalletClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,10 @@ export class WalletClient extends BaseClient implements IWalletClient {
} else {
account = new Web3Account(signerAccount, this.publicApiClient);
}
return account.sign(Buffer.from(data));
if (typeof data === 'string') {
data = Buffer.from(data);
}
return account.sign(data);
}

/**
Expand Down Expand Up @@ -427,10 +430,9 @@ export class WalletClient extends BaseClient implements IWalletClient {
public async verifySignature(
data: string | Buffer,
signature: ISignature,
signerPubKey: string,
): Promise<boolean> {
// setup the public key.
const publicKey: PublicKey = PublicKey.fromString(signerPubKey);
const publicKey: PublicKey = PublicKey.fromString(signature.publicKey);

// setup the message digest.
const bytesCompact: Buffer = Buffer.from(data);
Expand All @@ -450,6 +452,11 @@ export class WalletClient extends BaseClient implements IWalletClient {
`Invalid signature length. Expected 64, got ${signatureBytes.length}`,
);
}
if (publicKey.bytes.length != 32) {
throw new Error(
`Invalid public key length. Expected 32, got ${publicKey.bytes.length}`,
);
}
// verify signature.
const isVerified = await ed.verify(
signatureBytes,
Expand Down
22 changes: 19 additions & 3 deletions src/web3/accounts/WalletProviderAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ import { IRollsData } from '../../interfaces/IRollsData';
import { ITransactionData } from '../../interfaces/ITransactionData';
import { ICallData } from '../../interfaces/ICallData';
import { IContractData } from '../../interfaces/IContractData';
import { Args } from '@massalabs/web3-utils';

export class WalletProviderAccount implements IBaseAccount {
private account: IAccount;
constructor(account: IAccount) {
this.account = account;
}

public async sign(data: Buffer): Promise<ISignature> {
let bytes_signature = (await this.account.sign(data)).signature;
public async sign(data: Buffer | Uint8Array | string): Promise<ISignature> {
if (data instanceof Uint8Array) {
data = Buffer.from(data);
}
const signatureData = await this.account.sign(data);
let bytes_signature = signatureData.signature;
const base58Encoded = base58Encode(bytes_signature);
return {
publicKey: signatureData.publicKey,
base58Encoded,
};
}
Expand Down Expand Up @@ -45,10 +51,20 @@ export class WalletProviderAccount implements IBaseAccount {
}

public async callSmartContract(callData: ICallData): Promise<string> {
let params: number[] | Args = callData.parameter;
let paramToSend: Uint8Array | Args;

if (params instanceof Array) {
paramToSend = new Uint8Array(params);
}
if (params instanceof Args) {
paramToSend = params;
}

let res = await this.account.callSC(
callData.targetAddress,
callData.functionName,
new Uint8Array(callData.parameter),
paramToSend,
callData.coins,
callData.fee,
callData.maxGas,
Expand Down
Loading

0 comments on commit d370c74

Please sign in to comment.