top-block-game-cocos-sdk/assets/WalletSdkUtils.ts

80 lines
2.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Web3 from 'web3/dist/web3.min.js';
import {ContractABI} from "db://assets/scripts/WalletSDK/ABI";
/**
* Predefined variables
* Name = WalletUtils
* DateTime = Fri Aug 26 2022 18:07:14 GMT+0800 (中国标准时间)
* Author = 阿离我的
* FileBasename = WalletUtils.ts
* FileBasenameNoExtension = WalletUtils
* URL = db://assets/scripts/WalletSdk/WalletUtils.ts
* ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
*
*/
// 钱包sdk类型
export enum WalletSdkType {
Web, // 网页端 mobile pc
Native, // 原生端 android ios
}
// 钱包连接类型
export enum WalletConnectType {
Api, // api连接
QRCode, // 二维码连接
}
// 钱包类型
export enum WalletType {
MetaMask,
TronLink,
IMToken,
TokenPocket,
}
export interface IWalletSdk {
init(): Promise<void>;
connect(): any;
customSignRequest(): any;
customRequest(from: string, contractAddress: string, fnName: string, ...args: any[]): any;
}
const web3 = new Web3();
// 补齐64位不够前面用0补齐
function addPreZero(num: string) {
return num.toString().padStart(64, '0');
}
/**
* 发起合约请求
* @param from 调用者的地址
* @param contractAddress 合约地址
* @param fnName ABI内type为function的可调用函数名
* @param args 参数列表
*/
export function createRequestData(from: string, contractAddress: string, fnName: string, ...args: any[]) {
// 查找对应方法并获取对应的函数签名
const functionInfo = ContractABI.find((item) => item.type === 'function' && item.name === fnName);
// @ts-ignore
const functionSignature = web3.eth.abi.encodeFunctionSignature(functionInfo);
// 发起请求
return {
// 注意这里是代币合约地址
from,
to: contractAddress,
// 调用合约转账value这里留空
value: "",
// data的组成0x + 要调用的合约方法的function signature + 要传递的方法参数每个参数都为64位(去掉前面0x然后补齐为64位)
data: functionSignature + args.map((v) => addPreZero(web3.utils.toHex(v).substring(2))).join(''),
};
}