Created
February 6, 2024 21:55
-
-
Save JackyWYX/2bd9dea336325158572e1187c16c0eee to your computer and use it in GitHub Desktop.
MSafe wallet account creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PublicKey, SIGNATURE_FLAG_TO_SCHEME } from '@mysten/sui.js/cryptography'; | |
import { Ed25519PublicKey } from '@mysten/sui.js/keypairs/ed25519'; | |
import { MultiSigPublicKey } from '@mysten/sui.js/multisig'; | |
import { OwnerWeightPubKey, PublicKeyWithSchema, Weight } from '@/types'; | |
export const NONCE_PREFIX_MAX_SIZE = 16; | |
export const NONCE_PK_PREFIX = 'maven'; | |
export const NONCE_PK_WEIGHT = 1; | |
export function computeMSafeAddress(input: { | |
owners: OwnerWeightPubKey[]; | |
threshold: Weight; | |
nonce: number | undefined; | |
}): string { | |
const { owners, threshold, nonce } = input; | |
const pks = owners.map((owner) => ({ | |
publicKey: owner.publicKey, | |
weight: owner.weight, | |
})); | |
if (nonce !== undefined) { | |
// append nonce public key, weight is 1 because 0 is not allowed | |
pks.push({ | |
publicKey: noncePublicKey(nonce).publicKey, | |
weight: NONCE_PK_WEIGHT, | |
}); | |
} | |
return MultiSigPublicKey.fromPublicKeys({ threshold, publicKeys: pks }).toSuiAddress(); | |
} | |
export function noncePublicKeyWithWeight(nonce: number) { | |
return { | |
pubKey: noncePublicKey(nonce).publicKey, | |
weight: NONCE_PK_WEIGHT, | |
}; | |
} | |
export function noncePublicKey(nonce: number): PublicKeyWithSchema { | |
const buffer = new ArrayBuffer(Ed25519PublicKey.SIZE); | |
const textEncoder = new TextEncoder(); | |
textEncoder.encodeInto(NONCE_PK_PREFIX, new Uint8Array(buffer, 0, NONCE_PREFIX_MAX_SIZE)); | |
const nonceView = new DataView(buffer, NONCE_PREFIX_MAX_SIZE, 4); | |
nonceView.setUint32(0, nonce, true); | |
const pk = new Ed25519PublicKey(new Uint8Array(buffer)); | |
return { | |
publicKey: pk, | |
schema: getSchemaFromPublicKey(pk), | |
}; | |
} | |
export function getSchemaFromPublicKey(pk: PublicKey) { | |
const flag = pk.flag() as keyof typeof SIGNATURE_FLAG_TO_SCHEME; | |
if (!SIGNATURE_FLAG_TO_SCHEME[flag]) { | |
throw new Error('Invalid public key'); | |
} | |
return SIGNATURE_FLAG_TO_SCHEME[flag]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment