Skip to content

Commit

Permalink
Merge pull request #42 from massalabs/fix-balance
Browse files Browse the repository at this point in the history
Fix balance for testnet15
  • Loading branch information
Adrien LF authored Oct 7, 2022
2 parents 5757539 + 9cc8347 commit ae952d2
Show file tree
Hide file tree
Showing 11 changed files with 65 additions and 69 deletions.
17 changes: 8 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
DefaultProviderUrls,
IAccount,
IProvider,
ProviderType
ProviderType
} from "@massalabs/massa-web3";

// create a base account for signing transactions
Expand All @@ -50,7 +50,7 @@ import {
DefaultProviderUrls,
IAccount,
IProvider,
ProviderType
ProviderType
} from "@massalabs/massa-web3";

// create a base account for signing transactions
Expand Down Expand Up @@ -307,9 +307,9 @@ Available class methods are:
baseAccount
);
```
- `getAccountSequentialBalance`
- `getAccountBalance`
```ts
const balance: IBalance = await web3Client.wallet().getAccountSequentialBalance("A12PWTzCKkkE9P5Supt3Fkb4QVZ3cdfB281TGaup7Nv1DY12a6F1");
const balance: IBalance = await web3Client.wallet().getAccountBalance("A12PWTzCKkkE9P5Supt3Fkb4QVZ3cdfB281TGaup7Nv1DY12a6F1");
```

In addition to the class methods, there are also static methods for direct use:
Expand Down Expand Up @@ -455,10 +455,10 @@ const status: EOperationStatus = await web3Client.smartContracts().awaitRequired

### Smart contract balance

Smart contract balances could be easily obtained via usign the `getParallelBalance` method:
Smart contract balances could be easily obtained via using the `getContractBalance` method:

```ts
const balance: IBalance|null = await web3Client.smartContracts().getParallelBalance(contractAddress);
const balance: IBalance|null = await web3Client.smartContracts().getContractBalance(contractAddress);
```

### Smart contract read and write calls
Expand Down Expand Up @@ -487,8 +487,7 @@ const data: Array<string> = await web3Client.smartContracts().callSmartContract(
fee: 0,
gasPrice: 0,
maxGas: 200000,
parallelCoins: 0,
sequentialCoins: 0,
coins: 0,
targetAddress: scAddress,
functionName: "play",
parameter: JSON.stringify({index : 1}),
Expand All @@ -509,4 +508,4 @@ const data: Array<IExecuteReadOnlyResponse> = await web3Client.smartContracts().
} as IContractData,
baseAccount
);
```
```
5 changes: 2 additions & 3 deletions examples/smartContracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ const ora = require("ora");
fee: 0,
gasPrice: 0,
maxGas: 200000,
parallelCoins: 0,
sequentialCoins: 0,
coins: 0,
targetAddress: scAddress,
functionName: "play",
parameter: JSON.stringify({index : 1}),
Expand Down Expand Up @@ -95,4 +94,4 @@ const ora = require("ora");
const msg = chalk.red(`Error = ${ex.message}`);
if (spinner) spinner.fail(msg);
}
})();
})();
60 changes: 29 additions & 31 deletions src/interfaces/IAddressInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,43 +17,41 @@ export interface ILedgerDatastore {
[name: string]: [number];
}

export interface ICycleInfos {
active_rolls: number;
cycle: number;
is_final: boolean;
nok_count: number;
ok_count: number;
}

export interface IDeferredCredits {
slot: {
period: number,
thread: number,
};
amount: number;
}

export interface IAddressInfo {
address: string;
balance: {
candidate_balance: string, // represent an Amount in coins
final_balance: string, // represent an Amount in coins
locked_balance: string, // represent an Amount in coins
};
block_draws: [
candidate_balance: string; // represent an Amount in coins
candidate_datastore_keys: string;
candidate_roll_count: number;
created_blocks: Array<string>;
created_endorsements: Array<string>;
created_operations: Array<string>;
cycle_infos: Array<ICycleInfos>;
deferred_credits: Array<IDeferredCredits>;
final_balance: string; // represent an Amount in coins
final_datastore_keys: Array<string>;
final_roll_count: number;
next_block_draws: [
{
period: number,
thread: number,
},
];
blocks_created: [string]; // Block ids
endorsement_draws: Array<IEndorsementDraws>;
involved_in_endorsements: [string]; // Endorsement Id
involved_in_operations: [string]; // Operation id
production_stats: Array<IProductionStats>;
rolls: {
active_rolls: number,
candidate_rolls: number,
final_rolls: number,
};
next_endorsement_draws: Array<IEndorsementDraws>;
thread: number;
ledger_info: {
candidate_ledger_info: {balance: string} // represents an amount
final_ledger_info: {balance: string} // stored bytecode
locked_balance: string
};
final_sce_ledger_info: {
balance: string // represents an amount
module: null | [number] // stored bytecode
datastore: ILedgerDatastore
};
candidate_sce_ledger_info: {
balance: string // represents an amount
module: null | [number] // stored bytecode
datastore: ILedgerDatastore
};
}
6 changes: 2 additions & 4 deletions src/interfaces/ICallData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ export interface ICallData {
maxGas: number;
/// The price per unit of gas that the caller is willing to pay for the execution.
gasPrice: number;
/// Extra coins that are spent from the caller's parallel balance and transferred to the target
parallelCoins: number;
/// Extra coins that are spent from the caller's sequential balance and transferred to the target
sequentialCoins: number;
/// Extra coins that are spent from the caller's balance and transferred to the target
coins: number;
/// Target smart contract address
targetAddress: string;
/// Target function name. No function is called if empty.
Expand Down
2 changes: 1 addition & 1 deletion src/interfaces/ISmartContractsClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface ISmartContractsClient {
deploySmartContract(contractData: IContractData, executor?: IAccount): Promise<Array<string>>;
callSmartContract(callData: ICallData, executor?: IAccount): Promise<Array<string>>;
readSmartContract(readData: IReadData): Promise<Array<IContractReadOperationData>>;
getParallelBalance(address: string): Promise<IBalance | null>;
getContractBalance(address: string): Promise<IBalance | null>;
getFilteredScOutputEvents(eventFilterData: IEventFilter): Promise<Array<IEvent>>;
executeReadOnlySmartContract(contractData: IContractData): Promise<Array<IExecuteReadOnlyResponse>>;
getOperationStatus(opId: string): Promise<EOperationStatus>;
Expand Down
2 changes: 1 addition & 1 deletion src/interfaces/IWalletClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface IWalletClient {
removeAddressesFromWallet(addresses: Array<string>): void;
walletInfo(): Promise<Array<IFullAddressInfo>>;
signMessage(data: string | Buffer, accountSignerAddress: string): Promise<ISignature>;
getAccountSequentialBalance(address: string): Promise<IBalance | null>;
getAccountBalance(address: string): Promise<IBalance | null>;
sendTransaction(txData: ITransactionData, executor: IAccount): Promise<Array<string>>;
buyRolls(txData: IRollsData, executor: IAccount): Promise<Array<string>>;
sellRolls(txData: IRollsData, executor: IAccount): Promise<Array<string>>;
Expand Down
3 changes: 1 addition & 2 deletions src/interfaces/OperationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ export interface ICallSmartContractOpType {
CallSC: {
gas_price: string;
max_gas: number;
parallel_coins: string;
param: string;
sequential_coins: string;
coins: string;
target_addr: string;
target_func: string;
};
Expand Down
10 changes: 4 additions & 6 deletions src/web3/BaseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,8 @@ export class BaseClient {
// max gas
const maxGasEncoded = Buffer.from(varintEncode((data as ICallData).maxGas));

// parallel coins to send
const parallelCoinsEncoded = Buffer.from(varintEncode((data as ICallData).parallelCoins));

// sequential coins to send
const sequentialCoinsEncoded = Buffer.from(varintEncode((data as ICallData).sequentialCoins));
// coins to send
const coinsEncoded = Buffer.from(varintEncode((data as ICallData).coins));

// gas price
const gasPriceEncoded = Buffer.from(varintEncode((data as ICallData).gasPrice));
Expand All @@ -203,7 +200,8 @@ export class BaseClient {
const parametersEncoded = new Uint8Array(Buffer.from((data as ICallData).parameter, "utf8"));
const parametersLengthEncoded = Buffer.from(varintEncode(parametersEncoded.length));

return Buffer.concat([feeEncoded, expirePeriodEncoded, typeIdEncoded, maxGasEncoded, parallelCoinsEncoded, sequentialCoinsEncoded, gasPriceEncoded, targetAddressEncoded, functionNameLengthEncoded, functionNameEncoded, parametersLengthEncoded, parametersEncoded]);
return Buffer.concat([feeEncoded, expirePeriodEncoded, typeIdEncoded, maxGasEncoded, coinsEncoded, gasPriceEncoded, targetAddressEncoded,
functionNameLengthEncoded, functionNameEncoded, parametersLengthEncoded, parametersEncoded]);
}
case OperationTypeId.Transaction: {
// transfer amount
Expand Down
8 changes: 7 additions & 1 deletion src/web3/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class Client implements IClient {
private smartContractsClient: SmartContractsClient;
private vaultClient: VaultClient;

public constructor(clientConfig: IClientConfig, baseAccount?: IAccount) {
public constructor(private clientConfig: IClientConfig, baseAccount?: IAccount) {
this.publicApiClient = new PublicApiClient(clientConfig);
this.privateApiClient = new PrivateApiClient(clientConfig);
this.walletClient = new WalletClient(clientConfig, this.publicApiClient, baseAccount);
Expand Down Expand Up @@ -66,6 +66,12 @@ export class Client implements IClient {
this.smartContractsClient.setProviders(providers);
}

/** get currently set providers */
public getProviders(): Array<IProvider> {
return this.clientConfig.providers;
}

/** sets a new default provider */
public setNewDefaultProvider(provider: DefaultProviderUrls): void {
const providers = new Array({
url: provider,
Expand Down
11 changes: 5 additions & 6 deletions src/web3/SmartContractsClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { JSON_RPC_REQUEST_METHOD } from "../interfaces/JsonRpcMethods";
import { OperationTypeId } from "../interfaces/OperationTypes";
import { trySafeExecute } from "../utils/retryExecuteFunction";
import { wait } from "../utils/Wait";
import { base58Encode, hashBlake3 } from "../utils/Xbqcrypto";
import { BaseClient } from "./BaseClient";
import { PublicApiClient } from "./PublicApiClient";
import { WalletClient } from "./WalletClient";
Expand All @@ -42,7 +41,7 @@ export class SmartContractsClient extends BaseClient implements ISmartContractsC
this.getOperationStatus = this.getOperationStatus.bind(this);
this.callSmartContract = this.callSmartContract.bind(this);
this.readSmartContract = this.readSmartContract.bind(this);
this.getParallelBalance = this.getParallelBalance.bind(this);
this.getContractBalance = this.getContractBalance.bind(this);
}

/** create and send an operation containing byte code */
Expand Down Expand Up @@ -135,14 +134,14 @@ export class SmartContractsClient extends BaseClient implements ISmartContractsC
}
}

/** Returns the parallel balance which is the smart contract side balance */
public async getParallelBalance(address: string): Promise<IBalance | null> {
/** Returns the balance of the smart contract */
public async getContractBalance(address: string): Promise<IBalance | null> {
const addresses: Array<IAddressInfo> = await this.publicApiClient.getAddresses([address]);
if (addresses.length === 0) return null;
const addressInfo: IAddressInfo = addresses.at(0);
return {
candidate: addressInfo.candidate_sce_ledger_info.balance,
final: addressInfo.final_sce_ledger_info.balance
candidate: addressInfo.candidate_balance,
final: addressInfo.final_balance
} as IBalance;
}

Expand Down
10 changes: 5 additions & 5 deletions src/web3/WalletClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class WalletClient extends BaseClient implements IWalletClient {
this.sendTransaction = this.sendTransaction.bind(this);
this.sellRolls = this.sellRolls.bind(this);
this.buyRolls = this.buyRolls.bind(this);
this.getAccountSequentialBalance = this.getAccountSequentialBalance.bind(this);
this.getAccountBalance = this.getAccountBalance.bind(this);
}

/** set the default (base) account */
Expand Down Expand Up @@ -326,14 +326,14 @@ export class WalletClient extends BaseClient implements IWalletClient {
return secretKeyBase58Decoded;
}

/** Returns the account sequential balance - the consensus side balance */
public async getAccountSequentialBalance(address: string): Promise<IBalance | null> {
/** Returns the account balance */
public async getAccountBalance(address: string): Promise<IBalance | null> {
const addresses: Array<IAddressInfo> = await this.publicApiClient.getAddresses([address]);
if (addresses.length === 0) return null;
const addressInfo: IAddressInfo = addresses.at(0);
return {
candidate: addressInfo.ledger_info.candidate_ledger_info.balance,
final: addressInfo.ledger_info.final_ledger_info.balance
candidate: addressInfo.candidate_balance,
final: addressInfo.final_balance
} as IBalance;
}

Expand Down

0 comments on commit ae952d2

Please sign in to comment.