stacks.js icon indicating copy to clipboard operation
stacks.js copied to clipboard

Add `getNetworkFromAddress` method

Open janniks opened this issue 2 years ago • 7 comments

It might make sense to add network mode that determines how addresses are encoded. This is used in the explorer Like a getNetworkFromAddress? It would result in Testnet for Devnet/Mocknet addresses, since there's no difference. Is that acceptable?

Issue brought up by @friedger in #1470

janniks avatar Apr 19 '23 14:04 janniks

Hi @janniks! can you explain what needs to be done with an example?

ri-dev-git avatar Apr 30 '23 06:04 ri-dev-git

Hi, would you like to contribute? ✨

In short I would: Add a function networkFromAddress(address: string) to the transactions package (packages/transactions/src/utils.ts) which decodes the given address (using c32addressDecode) and compares the version (of the address) to mainnet vs testnet, then returns a new instance of that network. Add some simple test cases (to utils.test.ts) which cover an address for each network (devnet/mocknet also just use testnet address versions)

pseudo example

const network = networkFromAddress("SP8931298312");
    //^? instance of StacksMainnet()

Although maybe it's better to add other helpers like isMainnet(address) which could be combined easily. 🤷‍♂

janniks avatar May 03 '23 14:05 janniks

How can you differentiate between devnet, testnet, etc when they all use the same address

friedger avatar May 03 '23 15:05 friedger

Exactly, that doesn’t work and why I believe some other method might be better suited. 😕 The network would have the correct version, but shouldn’t be used for broadcast etc.

janniks avatar May 03 '23 16:05 janniks

hey @janniks! i have implemented it as something like this:

export const networkFromAddress=(address: string): {network:string,address:string} =>{
  try {
    const decode=c32addressDecode(address);
    if(isTestnetAddress(decode)){
      return {
        network:"Testnet",
        address: address
      }
    }else{
      return{
        network:"Testnet",
        address: address
      }
    }
  }
  catch(e){
    return e
  }
}

ri-dev-git avatar May 05 '23 09:05 ri-dev-git

Hi, maybe we should instead add a new method like isMainnet(address: string) which can easily be combined with others -- let's hold off on the actual implementation and gather some feedback? 🤔

e.g. easy use of isMainnet to create new helpers

const networkFromAddress = (address: string) => (isMainnet(address) ? new StacksMainnet() : new StacksTestnet());

janniks avatar May 05 '23 11:05 janniks

Yeah ok works!

ri-dev-git avatar May 06 '23 02:05 ri-dev-git