Reputation:
Reference to my smart contract file: https://github.com/amirsaranBIH/nearkick/blob/13-create-logic-for-users-to-remove-themselves-from-projects/contract/src/lib.rs
My main state struct looks like this:
#[derive(Serialize, Deserialize, BorshDeserialize, BorshSerialize, Debug)]
#[serde(crate = "near_sdk::serde")]
pub struct Project {
pub id: u64,
pub owner: AccountId,
pub name: String,
pub description: String,
pub supporters: HashMap<AccountId, Supporter>,
pub balance: Balance,
pub goal: Balance,
pub end_time: u64,
pub status: ProjectStatus,
pub plan: SupporterPlans,
pub level_amounts: HashMap<SupporterType, Balance>,
pub images: Vec<String>,
}
The Balance
type is just pub type Balance = u128;
.
I will use the pub fn add_project
method to explain my problem.
pub fn add_project(
&mut self,
goal: U128,
name: String,
description: String,
plan: SupporterPlans,
end_time: u64,
cadence: String,
basic_supporter_amount: U128,
intermediate_supporter_amount: U128,
advanced_supporter_amount: U128,
images: Vec<String>,
) -> u64
Because JavaScript has poor big number support I had to use U128
for my pub fn add_project
parameters (goal: U128
, basic_supporter_amount: U128
, intermediate_supporter_amount: U128
and advanced_supporter_amount: U128
).
For example:
In JavaScript the number 5000000000000000000000000
would be transformed into 5e+24
and be sent over as a parameter of my smart contract call. This would cause the smart contract to panic.
Right now I am just sending big numbers as strings and it works. The values are stored in state.
======================
The problem is with my view methods. The balance: Balance
, goal: Balance
and level_amounts: HashMap<SupporterType, Balance>
properties are u128
.
When returned into my JavaScript code and turned into an Object the numbers are just 5e+24
.
It is also like this when called trough the near-cli (Here is an example: near view dev-1657316029595-71822829120195 get_all_projects '{}'
)
Some solutions that I have thought of:
U128
instead of Balance
for my state properties. -> This is not that great because I would have to convert from U128
to u128
every time I had to do some arithmetic operations.5e+24
to "5000000000000000000000000"
. -> Some conversion methods that I have found are not precise. (Tried these: How to avoid scientific notation for large numbers in JavaScript?)Is there a way to use Balance/u128
types for my number properties and to have "string-like" numbers in JavaScript?
Upvotes: 2
Views: 165
Reputation: 399
I'm afraid the best way to go is actually to use the U128
type from near-sdk-rs
that will return large numbers as strings to your client side app, saving you from writing logic for handling numbers like 5e+24
.
Upvotes: 1