input-output-hk / js-cardano-wasm

various cardano javascript using wasm bindings
MIT License
31 stars 21 forks source link

Add is_valid address function #84

Closed SebastienGllmt closed 4 years ago

SebastienGllmt commented 4 years ago

In Shelley, we often have to do

if byron_address
  do X
else if shelley_address
  do Y

Why we need a special function

The problem is that due to https://github.com/rustwasm/wasm-bindgen/issues/1963 returning a Result that represents an error on the Rust side actually causes stack space to be permanently lost.

This causes Yoroi to crash running out of stack space after some time.

To solve this, I introduce a new function called is_valid that instead returns a boolean.

You can tell this fix works based on the following:

let err = null;
for (let j = 0; j < 100000; j++) {
  try {
    // uncommenting  will not cause a crash
    console.log(Wallet.Address.is_valid("asdf"));

    // uncommenting this will cause a crash due to lack of stack space
    // console.log(Wallet.Address.from_base58("a"));
  } catch (e) {
    if (err == null) {
      err = e;
      continue;
    }
    if (e === err) {
      continue;
    }
    console.log('iteration', j);
    throw e;
  }
}

How to use this function

// false
console.log(Wallet.Address.is_valid("asdf"));

// true
console.log(Wallet.Address.is_valid("Ae2tdPwUPEZAD1KmgTQ4zS6Q5s4VXWDXqB3ZmM1abQGoyrGN8qCsZyXc3vf"));

// true
console.log(Wallet.Address.is_valid("DdzFFzCqrht74dr7DYmiyCobGFQcfLCsHJCCM6nEBTztrsEk5kwv48EWKVMFU9pswAkLX9CUs4yVhVxqZ7xCVDX1TdatFwX5W39cohvm"));