Search Apps Documentation Source Content File Folder Download Copy Actions Download

converter.gno

1.86 Kb · 62 lines
 1// Package ctg is a simple utility package with helpers
 2// for bech32 address conversions.
 3package ctg
 4
 5import (
 6	"crypto/bech32"
 7
 8	"gno.land/p/nt/ufmt"
 9)
10
11// ConvertCosmosToGno takes a Bech32 Cosmos address (prefix "cosmos")
12// and returns the same address re-encoded with the gno.land prefix "g".
13func ConvertCosmosToGno(addr string) (address, error) {
14	prefix, decoded, err := bech32.Decode(addr)
15	if err != nil {
16		return "", ufmt.Errorf("bech32 decode failed: %v", err)
17	}
18
19	if prefix != "cosmos" {
20		return "", ufmt.Errorf("expected a cosmos address, got prefix %q", prefix)
21	}
22
23	return address(mustEncode("g", decoded)), nil
24}
25
26func mustEncode(hrp string, data []byte) string {
27	enc, err := bech32.Encode(hrp, data)
28	if err != nil {
29		panic(err)
30	}
31	return enc
32}
33
34// ConvertAnyToGno converts *any* valid Bech32 address to its gno.land form
35// by preserving the underlying payload but replacing the prefix with "g".
36// No prefix check is performed; invalid Bech32 input still returns an error.
37func ConvertAnyToGno(addr string) (address, error) {
38	_, decoded, err := bech32.Decode(addr)
39	if err != nil {
40		return "", ufmt.Errorf("bech32 decode failed: %v", err)
41	}
42	return address(mustEncode("g", decoded)), nil
43}
44
45// ConvertGnoToAny converts a gno.land address (prefixed with "g") to another Bech32
46// prefix given by prefix. The function ensures the source address really
47// is a gno.land address before proceeding.
48//
49// Example:
50//
51//	cosmosAddr, _ := ConvertGnoToAny("cosmos", "g1k98jx9...")
52//	fmt.Println(cosmosAddr) // → cosmos1....
53func ConvertGnoToAny(prefix string, addr address) (string, error) {
54	origPrefix, decoded, err := bech32.Decode(string(addr))
55	if err != nil {
56		return "", ufmt.Errorf("bech32 decode failed: %v", err)
57	}
58	if origPrefix != "g" {
59		return "", ufmt.Errorf("expected a gno address but got prefix %q", origPrefix)
60	}
61	return mustEncode(prefix, decoded), nil
62}