Skip to content

Commit

Permalink
update for aptos
Browse files Browse the repository at this point in the history
  • Loading branch information
lever.wang.wenjia committed Nov 16, 2023
1 parent 5b897be commit 35bc9fe
Show file tree
Hide file tree
Showing 29 changed files with 1,881 additions and 899 deletions.
3 changes: 2 additions & 1 deletion packages/coin-aptos/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"typescript": "^4.6.2"
},
"dependencies": {
"@okxweb3/coin-base": "^1.0.0",
"@okxweb3/crypto-lib": "^1.0.0",
"@okxweb3/coin-base": "^1.0.0"
"tweetnacl": "^1.0.3"
}
}
16 changes: 15 additions & 1 deletion packages/coin-aptos/src/AptosWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,15 @@ import {
generateBCSTransaction,
mintCoin,
offerNFTTokenPayload,
offerNFTTokenPayloadObject,
registerCoin,
transferCoin,
transferPayload,
} from './index';
import * as client from './client'

export type AptosParam = {
type: "transfer" | "tokenTransfer" | "tokenMint" | "tokenBurn" | "tokenRegister" | "dapp" | "simulate" | "offerNft" | "claimNft" | "offerNft_simulate" | "claimNft_simulate"
type: "transfer" | "tokenTransfer" | "tokenMint" | "tokenBurn" | "tokenRegister" | "dapp" | "simulate" | "offerNft"| "offerNftObject"| "claimNft" | "offerNft_simulate" | "claimNft_simulate"
base: AptosBasePram,
data: any
}
Expand Down Expand Up @@ -81,6 +82,11 @@ export type AptosOfferNFTParam = {
version: string
amount: string
}
export type AptosOfferNFTObjectParam = {
nftObject: string,
receiver: string,
amount: string
}

export type AptosClaimNFTParam = {
sender: string,
Expand Down Expand Up @@ -225,6 +231,14 @@ export class AptosWallet extends BaseWallet {
tx = generateBCSSimulateTransaction(account, rawTxn);
break
}
case "offerNftObject": {
const baseParam = ap.base
const data = ap.data as AptosOfferNFTObjectParam
const payload = offerNFTTokenPayloadObject(HexString.ensure(data.nftObject), HexString.ensure(data.receiver), BigInt(data.amount))
const rawTxn = createRawTransaction(sender, payload, BigInt(baseParam.sequenceNumber), baseParam.chainId, BigInt(baseParam.maxGasAmount), BigInt(baseParam.gasUnitPrice), BigInt(baseParam.expirationTimestampSecs))
tx = generateBCSTransaction(account, rawTxn);
break
}
case "offerNft": {
const baseParam = ap.base
const data = ap.data as AptosOfferNFTParam
Expand Down
134 changes: 113 additions & 21 deletions packages/coin-aptos/src/aptos_account.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { HexString, MaybeHexString } from "./hex_string";
import { MoveTypes } from "./transaction_builder";
import { base, signUtil } from '@okxweb3/crypto-lib';

import nacl from "tweetnacl";
import * as bip39 from "@scure/bip39";
import { bytesToHex } from "@noble/hashes/utils";
import { sha256 } from "@noble/hashes/sha256";
import { sha3_256 as sha3Hash } from "@noble/hashes/sha3";
import { derivePath } from "./utils/hd-key";
import { Memoize } from "./utils";
import {AccountAddress, AuthenticationKey, Ed25519PublicKey} from "./transaction_builder/aptos_types";
import {bcsToBytes} from "./transaction_builder/bcs";
import {TextEncoder} from "util";
export interface AptosAccountObject {
address?: string;
address?: MoveTypes.HexEncodedBytes;
publicKeyHex?: MoveTypes.HexEncodedBytes;
privateKeyHex: MoveTypes.HexEncodedBytes;
}
Expand All @@ -15,30 +23,66 @@ export class AptosAccount {
/**
* A private key and public key, associated with the given account
*/
private readonly publicKey: Uint8Array
private readonly privateKey: Uint8Array
readonly signingKey: nacl.SignKeyPair;

/**
* Address associated with the given account
*/
private readonly accountAddress: HexString;

// Generate an account from the private key
static fromAptosAccountObject(obj: AptosAccountObject): AptosAccount {
return new AptosAccount(HexString.ensure(obj.privateKeyHex).toUint8Array(), obj.address);
}

static fromPrivateKey(privateKey: HexString): AptosAccount {
return new AptosAccount(privateKey.toUint8Array());
}

/**
* Check's if the derive path is valid
*/
static isValidPath(path: string): boolean {
return /^m\/44'\/637'\/[0-9]+'\/[0-9]+'\/[0-9]+'+$/.test(path);
}

/**
* Creates new account with bip44 path and mnemonics,
* @param path. (e.g. m/44'/637'/0'/0'/0')
* Detailed description: {@link https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki}
* @param mnemonics.
* @returns AptosAccount
*/
static fromDerivePath(path: string, mnemonics: string): AptosAccount {
if (!AptosAccount.isValidPath(path)) {
throw new Error("Invalid derivation path");
}

const normalizeMnemonics = mnemonics
.trim()
.split(/\s+/)
.map((part) => part.toLowerCase())
.join(" ");

const { key } = derivePath(path, bytesToHex(bip39.mnemonicToSeedSync(normalizeMnemonics)));

return new AptosAccount(key);
}

/**
* Creates new account instance. Constructor allows passing in an address,
* to handle account key rotation, where auth_key != public_key
* @param privateKeyBytes Private key from which account key pair will be generated.
* If not specified, new key pair is going to be created.
* @param address Account address (e.g. 0xe8012714cd17606cee7188a2a365eef3fe760be598750678c8c5954eb548a591).
* If not specified, a new one will be generated from public key
*/
constructor(privateKeyBytes: Uint8Array) {
this.privateKey = privateKeyBytes
this.publicKey = signUtil.ed25519.publicKeyCreate(privateKeyBytes)
this.accountAddress = HexString.ensure(this.authKey().hex());
constructor(privateKeyBytes?: Uint8Array | undefined, address?: MaybeHexString) {
if (privateKeyBytes) {
this.signingKey = nacl.sign.keyPair.fromSeed(privateKeyBytes.slice(0, 32));
} else {
this.signingKey = nacl.sign.keyPair();
}
this.accountAddress = HexString.ensure(address || this.authKey().hex());
}

/**
Expand All @@ -54,14 +98,46 @@ export class AptosAccount {
/**
* This key enables account owners to rotate their private key(s)
* associated with the account without changing the address that hosts their account.
* See here for more info: {@link https://aptos.dev/basics/basics-accounts#single-signer-authentication}
* See here for more info: {@link https://aptos.dev/concepts/accounts#single-signer-authentication}
* @returns Authentication key for the associated account
*/
@Memoize()
authKey(): HexString {
const hash = base.sha3_256.create();
hash.update(Buffer.from(this.publicKey));
hash.update("\x00");
return new HexString(base.toHex(hash.digest()))
const pubKey = new Ed25519PublicKey(this.signingKey.publicKey);
const authKey = AuthenticationKey.fromEd25519PublicKey(pubKey);
return authKey.derivedAddress();
}

/**
* Takes source address and seeds and returns the resource account address
* @param sourceAddress Address used to derive the resource account
* @param seed The seed bytes
* @returns The resource account address
*/
static getResourceAccountAddress(sourceAddress: MaybeHexString, seed: Uint8Array): HexString {
const source = bcsToBytes(AccountAddress.fromHex(sourceAddress));

const bytes = new Uint8Array([...source, ...seed, AuthenticationKey.DERIVE_RESOURCE_ACCOUNT_SCHEME]);

const hash = sha3Hash.create();
hash.update(bytes);

return HexString.fromUint8Array(hash.digest());
}

/**
* Takes creator address and collection name and returns the collection id hash.
* Collection id hash are generated as sha256 hash of (`creator_address::collection_name`)
*
* @param creatorAddress Collection creator address
* @param collectionName The collection name
* @returns The collection id hash
*/
static getCollectionID(creatorAddress: MaybeHexString, collectionName: string): HexString {
const seed = new TextEncoder().encode(`${creatorAddress}::${collectionName}`);
const hash = sha256.create();
hash.update(seed);
return HexString.fromUint8Array(hash.digest());
}

/**
Expand All @@ -70,17 +146,17 @@ export class AptosAccount {
* @returns The public key for the associated account
*/
pubKey(): HexString {
return HexString.ensure(base.toHex(this.publicKey));
return HexString.fromUint8Array(this.signingKey.publicKey);
}

/**
* Signs specified `buffer` with account's private key
* @param buffer A buffer to sign
* @returns A signature HexString
*/
signBuffer(buffer: Buffer): HexString {
const signature = signUtil.ed25519.sign(buffer, this.privateKey);
return HexString.ensure(base.toHex(signature).slice(0, 128));
signBuffer(buffer: Uint8Array): HexString {
const signature = nacl.sign.detached(buffer, this.signingKey.secretKey);
return HexString.fromUint8Array(signature);
}

/**
Expand All @@ -89,10 +165,21 @@ export class AptosAccount {
* @returns A signature HexString
*/
signHexString(hexString: MaybeHexString): HexString {
const toSign = HexString.ensure(hexString).toBuffer();
const toSign = HexString.ensure(hexString).toUint8Array();
return this.signBuffer(toSign);
}

/**
* Verifies the signature of the message with the public key of the account
* @param message a signed message
* @param signature the signature of the message
*/
verifySignature(message: MaybeHexString, signature: MaybeHexString): boolean {
const rawMessage = HexString.ensure(message).toUint8Array();
const rawSignature = HexString.ensure(signature).toUint8Array();
return nacl.sign.detached.verify(rawMessage, rawSignature, this.signingKey.publicKey);
}

/**
* Derives account address, public key and private key
* @returns AptosAccountObject instance.
Expand All @@ -110,7 +197,12 @@ export class AptosAccount {
return {
address: this.address().hex(),
publicKeyHex: this.pubKey().hex(),
privateKeyHex: HexString.fromUint8Array(this.privateKey.slice(0, 32)).hex(),
privateKeyHex: HexString.fromUint8Array(this.signingKey.secretKey.slice(0, 32)).hex(),
};
}
}

// Returns an account address as a HexString given either an AptosAccount or a MaybeHexString.
export function getAddressFromAccountOrAddress(accountOrAddress: AptosAccount | MaybeHexString): HexString {
return accountOrAddress instanceof AptosAccount ? accountOrAddress.address() : HexString.ensure(accountOrAddress);
}
Loading

0 comments on commit 35bc9fe

Please sign in to comment.