接入钱包
Provider API

Provider API#

什么是 Injected provider API?#

欧易 Injected providers API 是一个 JavaScript API,欧易将其注入用户访问的网站。您的 DApp 可以使用此 API 请求用户帐户,从用户连接的区块链读取数据,帮助用户签署消息和交易。

连接账户#

window.okxwallet.aptos.connect()

描述

通过调用 window.okxwallet.aptos.connect() 连接欧易 Web3 钱包。

当成功调用 window.okxwallet.aptos.connect(),将会唤起欧易 Web3 钱包连接钱包页面,用户可以决定是否连接当前 DApp,如果用户同意将会返回地址 (address) 和公钥 (public key)。

try {
    const response = await window.okxwallet.aptos.connect();
    console.log(response);
    // { address: string, publicKey: string }
  } catch (error) {
    console.log(error);
    // { code: 4001, message: "User rejected the request."}
  }

例子

codeopen中打开。

HTML
JavaScript
<button class="connectAptosButton">Connect Aptos</button>
const connectAptosButton = document.querySelector('.connectAptosButton');

connectAptosButton.addEventListener('click', () => {
  try {
    const response = await window.okxwallet.aptos.connect();
    console.log(response);
    // { address: string, publicKey: string }
  } catch (error) {
    console.log(error);
    // { code: 4001, message: "User rejected the request."}
  }
});

签名交易#

window.okxwallet.aptos.signAndSubmitTransaction(transaction)

描述

在欧易 Web3 钱包中通过调用 window.okxwallet.aptos.signAndSubmitTransaction(transaction) 方法来发起一笔 Aptos 链上交易,这个方法将会返回一个待确认的交易信息给 DApp

const transaction = {
  arguments: [address, '717'],
  function: '0x1::coin::transfer',
  type: 'entry_function_payload',
  type_arguments: ['0x1::aptos_coin::AptosCoin'],
};

try {
  const pendingTransaction = await window.okxwallet.aptos.signAndSubmitTransaction(transaction);

  const client = new AptosClient('https://fullnode.mainnet.aptoslabs.com/');
  const txn = await client.waitForTransactionWithResult(
      pendingTransaction.hash,
  );
} catch (error) {
  // see "Errors"
}

当然也可以通过 window.okxwallet.aptos.signTransaction(transaction) 仅仅是签名交易,而不发起上链操作,此方法将返回一个签名的Buffer

提示
重要提醒:这个方法并不常用,而且对用户来说也非常的不安全,建议不要使用这个方法
const transaction = {
  arguments: [address, '717'],
  function: '0x1::coin::transfer',
  type: 'entry_function_payload',
  type_arguments: ['0x1::aptos_coin::AptosCoin'],
};

try {
  const signTransaction = await window.okxwallet.aptos.signTransaction(transaction);
} catch (error) {
  // see "Errors"
}

例子

codeopen中打开。

HTML
JavaScript
<button class="connectAptosButton btn">Connect Aptos</button>
<button class="signTransactionButton btn">Sign Transaction</button>
const connectAptosButton = document.querySelector('.connectAptosButton');
const signTransactionButton = document.querySelector('.signTransactionButton');
let address='';

signTransactionButton.addEventListener('click', async() => {
  try {
    const transaction = {
      arguments: [address, '717'],
      function: '0x1::coin::transfer',
      type: 'entry_function_payload',
      type_arguments: ['0x1::aptos_coin::AptosCoin'],
    };

    const pendingTransaction = await window.okxwallet.aptos.signAndSubmitTransaction(transaction);
    console.log(pendingTransaction);
  } catch (error) {
    console.log(error)
  }
});

connectAptosButton.addEventListener('click', async() => {
   console.log(res);
   const res = await window.okxwallet.aptos.connect();
   address = res.address;
});

签名信息#

window.okxwallet.aptos.signMessage(message)

描述

DApp 可以通过调用 window.okxwallet.aptos.signMessage(message) 来签名一段消息,当用户同意这个操作后,欧易 Web3 钱包将返回签名成功的信息、签名信息、入参和返回信息。结构如下:

参数

interface SignMessagePayload {
  address?: boolean; // Should we include the address of the account in the message
  application?: boolean; // Should we include the domain of the DApp
  chainId?: boolean; // Should we include the current chain id the wallet is connected to
  message: string; // The message to be signed and displayed to the user
  nonce: string; // A nonce the DApp should generate
}

返回值

interface SignMessageResponse {
  address: string;
  application: string;
  chainId: number;
  fullMessage: string; // The message that was generated to sign
  message: string; // The message passed in by the user
  nonce: string;
  prefix: string; // Should always be APTOS
  signature: string; // The signed full message
}

例子

codeopen中打开。

HTML
JavaScript
<button class="connectAptosButton btn">Connect Aptos</button>
<button class="signButton btn">Sign Message</button>
const connectAptosButton = document.querySelector('.connectAptosButton');
const signButton = document.querySelector('.signButton');

const signMessagePayload = {
  message: 'hello okx',
  nonce: 'okx'
};

signButton.addEventListener('click', async() => {
  try {
    const signMessage = await window.okxwallet.aptos.signMessage(signMessagePayload)
    console.log(signMessage);
    // {"signature": string, "prefix": "APTOS", "fullMessage": "APTOS nonce: okx message: hello okx", "message": "hello okx", "nonce": "okx" }
  } catch (error) {
    // see "Errors"
  }
});

connectAptosButton.addEventListener('click', () => {
  connetAccount();
});

async function connetAccount() {
  const res = await window.okxwallet.aptos.connect();
  console.log(res);
}

签名消息验证#

import nacl from 'tweetnacl';

const message = 'hello';
const nonce = 'random_string';

try {
    const response = await window.okxwallet.aptos.signMessage({
        message,
        nonce,
    });
    const { publicKey } = await window.okxwallet.aptos.account();
    // Remove the 0x prefix
    const key = publicKey!.slice(2, 66);
    const verified = nacl.sign.detached.verify(
        Buffer.from(response.fullMessage),
        Buffer.from(response.signature, 'hex'),
        Buffer.from(key, 'hex'),
);
    console.log(verified);
} catch (error) {
    console.error(error);
}

事件#

账户切换

当用户在切换欧易 Web3 钱包的时候,需要监听钱包切换事件:onAccountChange

提示
重要提醒:用户切换的钱包的时候,目前账户必须有 Aptos 地址时才会触发。
let currentAccount = await window.okxwallet.aptos.account();

// event listener for disconnecting
window.okxwallet.aptos.onAccountChange((newAccount) => {
  // If the new account has already connected to your app then the newAccount will be returned
  if (newAccount) {
    currentAccount = newAccount;
  } else {
    // Otherwise you will need to ask to connect to the new account
    currentAccount = window.okxwallet.aptos.connect();
  }
});

断开连接

当欧易 Web3 钱包断开连接的时候(欧易 Web3 钱包是多链钱包,当用户切换到的钱包不包含 Aptos 相关地址的时候,也会触发该事件)

// get current connection status
let connectionStatus = await window.okxwallet.aptos.isConnected();

// event listener for disconnecting
window.okxwallet.aptos.onDisconnect(() => {
  connectionStatus = false;
});

例子

codeopen中打开。

HTML
JavaScript
<button class="connectAptosButton">Connect Aptos</button>
const connectAptosButton = document.querySelector('.connectAptosButton');

window.okxwallet.aptos.on('connect',()=>{
  console.log('got connect event');
})

connectAptosButton.addEventListener('click', async() => {
  try {
    const res = await window.okxwallet.aptos.connect();
    console.log(res);
    // { address: string, publicKey: string }
  } catch (error) {
    console.log(error);
    // { code: 4001, message: "User rejected the request."}
  }
});