CAIP2.sol 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.24;
  3. import {Bytes} from "./Bytes.sol";
  4. import {Strings} from "./Strings.sol";
  5. /**
  6. * @dev Helper library to format and parse CAIP-2 identifiers
  7. *
  8. * https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md[CAIP-2] defines chain identifiers as:
  9. * chain_id: namespace + ":" + reference
  10. * namespace: [-a-z0-9]{3,8}
  11. * reference: [-_a-zA-Z0-9]{1,32}
  12. */
  13. library CAIP2 {
  14. using Strings for uint256;
  15. using Bytes for bytes;
  16. /// @dev Return the CAIP-2 identifier for the current (local) chain.
  17. function local() internal view returns (string memory) {
  18. return format("eip155", block.chainid.toString());
  19. }
  20. /**
  21. * @dev Return the CAIP-2 identifier for a given namespace and reference.
  22. *
  23. * NOTE: This function does not verify that the inputs are properly formatted.
  24. */
  25. function format(string memory namespace, string memory ref) internal pure returns (string memory) {
  26. return string.concat(namespace, ":", ref);
  27. }
  28. /**
  29. * @dev Parse a CAIP-2 identifier into its components.
  30. *
  31. * NOTE: This function does not verify that the CAIP-2 input is properly formatted.
  32. */
  33. function parse(string memory caip2) internal pure returns (string memory namespace, string memory ref) {
  34. bytes memory buffer = bytes(caip2);
  35. uint256 pos = buffer.indexOf(":");
  36. return (string(buffer.slice(0, pos)), string(buffer.slice(pos + 1)));
  37. }
  38. }