CAIP10.sol 1.7 KB

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