Connect to Extension Wallet
Provider API

Provider API#

What is injected provider API?#

The OKX injected provider API is a JavaScript API that OKX injects into websites visited by our users. Your DApp can use this API to request users' accounts, read data from blockchains users are connected to, and help users sign messages and transactions.

Connecting to OKX Wallet#

window.okxwallet.tronLink.request(args)

Description

OKX Wallet supports TRX transfers, signing and authorizing contracts, and other authorization functions initiated by DApps. For security reasons, OKX Wallet needs you to authorize your DApp to connect to the website. DApps must first connect to the website and wait for your permission to initiate an authorization request.

window.okxwallet.tronLink.request({ method: 'tron_requestAccounts'})

Status code

Status code
DescriptionMessage
200The site has been allowed to be connect toThe site is already in the allowlist
200User has approved the connectionUser approved the request
4000The same DApp has already initiated a request to connect to the websiteAuthorization requests are being processed. Please do not re-submit.
4001User has rejected the connectionUser rejected the request

Example

Open in codeopen.

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

connectTronButton.addEventListener('click', () => {
  window.okxwallet.tronLink.request({
    method: 'tron_requestAccounts'
  }).catch((error)=>{
    console.log(error);
  })
});

Three steps are required to initiate a transaction on the TRON network.

  1. Start a transfer transaction
  2. Sign the transaction
  3. Broadcast the signed transaction

In this process, the second step requires TronLink, while the first and third steps are done on tronWeb.

Signing transactions#

okxwallet.tronLink.tronWeb.trx.sign(transaction, privateKey)

Description

Step 1: Starting a transfer

sendTRX

This will initiate an unsigned TRX transfer.

Usage

okxwallet.tronLink.tronWeb.transactionBuilder.sendTrx(to,amount,from,options);

Parameters

ParameterDescriptionType
toAddress to transfer TRXhexStrig
amountNumber of TRX to sendinteger
fromAddress that's transferring the tokens (optional). If left blank, it will be the address associated with the private key.hexString
optionsPermission IDinteger

Example

okxwallet.tronLink.tronWeb.transactionBuilder.sendTrx("TVDGpn4hCSzJ5nkHPLetk8KQBtwaTppnkr", 100, "TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL");

Step 2: Signing a transaction

sign

This will sign the transaction.

⚠️ Caution

To prevent disclosure of the private key, don't use this request on any web or user-oriented applications.

Usage

// sign a transaction
okxwallet.tronLink.tronWeb.trx.sign(transaction, privateKey);

Parameters

ParameterDescriptionType
transactionThe trading partnerJSON
privateKeyThe private key is used for signing (optional). By default, the private key is the one passed in when the tronweb was built.string

Example

const tradeobj = await okxwallet.tronLink.tronWeb.transactionBuilder.sendTrx("TNo9e8MWQpGVqdyySxLSTw3gjgFQWE3vfg", 100,"TM2TmqauSEiRf16CyFgzHV2BVxBejY9iyR",1);
const signedtxn = await okxwallet.tronLink.tronWeb.trx.sign(tradeobj, privateKey);
console.log(signedtxn)

Step 3: Broadcasting the signed transactions

sendRawTransaction

This broadcasts the signed transactions to the network.

Usage

// sign a transaction
okxwallet.tronLink.tronWeb.trx.sendRawTransaction(signedTransaction);

Parameters

ParameterDescriptionType
signedTransactionSigned trading partnersJSON

Example

const tronWeb = okxwallet.tronLink.tronWeb;
const tradeobj = await tronWeb.transactionBuilder.sendTrx("TNo9e8MWQpGVqdyySxLSTw3gjgFQWE3vfg", 100,"TM2TmqauSEiRf16CyFgzHV2BVxBejY9iyR",1);
const signedtxn = await tronWeb.trx.sign(tradeobj, privateKey);
const receipt = await tronWeb.trx.sendRawTransaction(signedtxn);
console.log(receipt)

Example

Open in codeopen.

HTML
JavaScript
<button class="connectTronButton btn">Connect Tron</button>
<button class="signTransactionButton btn">Sign Transaction</button>
const connectTronButton = document.querySelector('.connectTronButton');
const signTransactionButton = document.querySelector('.signTransactionButton');

signTransactionButton.addEventListener('click', () => {
  if (window.okxwallet.tronLink.ready) {
    const tronweb = okxwallet.tronLink.tronWeb;
    // const fromAddress = tronweb.defaultAddress.base58;
    const fromAddress = 'TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL'
    const toAddress = "TAHQdDiZajMMP26STUnfsiRMNyXdxAJakZ";
    try {
      const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10); // Step1
      const signedTx = await tronweb.trx.sign(tx); // Step2
      await tronweb.trx.sendRawTransaction(signedTx); // Step3
    } catch (error) {
      // error handling
      console.log(error)
    }
  }
});

connectTronButton.addEventListener('click', () => {
  window.okxwallet.tronLink.request({
    method: 'tron_requestAccounts'
  }).catch((error)=>{
    console.log(error);
  })
});

Signing messages#

window.okxwallet.tronLink.tronWeb.trx.sign(message)

Description

DApps require users to sign hexadecimal messages. The signed message will be forwarded to the backend to verify whether the user's login is valid. DApps will then send a request to ask the user to connect the wallet to the website, to which the user agrees.

Parameters

ParameterDescriptionType
messagenormal string or hexadecimal stringString

Version

  • For the versions of the okx wallet prior to 2.80.0:

Regardless of whether the parameter is in hexadecimal format or not, it will undergo hexadecimal conversion before signing. Therefore, if the original message is already in hexadecimal, an additional hexadecimal conversion is required during signature verification.

  • For the versions of the okx wallet 2.80.0 and later:

If the input parameter is a hexadecimal string, no conversion is needed; it can be signed directly.

If the input parameter is a non-hexadecimal string, the wallet internally converts it to a hexadecimal string for signing. For example, for the plain string "helloworld," the corresponding hexadecimal format is "68656c6c6f776f726c64." Therefore, .sign('helloworld') is equivalent to .sign('0x68656c6c6f776f726c64').

Return value

If you choose the sign option in the pop-up window, the DApp will obtain the signed hexadecimal string. For example:

0xaa302ca153b10dff25b5f00a7e2f603c5916b8f6d78cdaf2122e24cab56ad39a79f60ff3916dde9761baaadea439b567475dde183ee3f8530b4cc76082b29c341c

If an error occurs, the following information is returned:

Uncaught (in promise) Invalid transaction provided

Example

Open in codeopen.

HTML
JavaScript
<button class="connectTronButton btn">Connect Tron</button>
<button class="signButton btn">Sign Message</button>
<button class="verifyButton btn">Verify Message</button>
const connectTronButton = document.querySelector('.connectTronButton');
const signButton = document.querySelector('.signButton');
const verifyButton = document.querySelector('.verifyButton');

signButton.addEventListener('click', async() => {
  if (window.okxwallet.tronLink.ready) {
    const tronweb = window.okxwallet.tronLink.tronWeb;
    try {
      const message = "0x1e"; // any hex string
      const signedString = await tronweb.trx.sign(message);
    } catch (error) {
      // handle error
    }
  }
});

verifyButton.addEventListener('click', async() => {
  if (window.okxwallet.tronLink.ready) {
    const tronweb = window.okxwallet.tronLink.tronWeb;
    try {
      const message = "0x1e";
      const result = await tronweb.trx.verifyMessage(message, window.signedString);
    } catch (error) {
      // handle error
    }
  }
});

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

async function connetAccount() {
  await window.okxwallet.tronLink.request({
    method: 'tron_requestAccounts'
  })
}

Verify Signed Message#

window.okxwallet.tronLink.tronWeb.trx.verifyMessage(hexMsg, signedMsg[, address])

Description

verify signature

Parameters

ParameterDescriptionType
hexMsghex format message stringString
signedMsgsigned message with signatureString
addressaccount address, optionalString

Version

Take the example of the above helloworld and its corresponding hexadecimal 0x68656c6c6f776f726c64.

  • For the versions of the okx wallet before 2.80.0:

Non-hexadecimal string:

const signedMsg = await window.okxwallet.tronLink.tronWeb.trx.sign('helloworld')
const validate = await window.okxwallet.tronLink.tronWeb.trx.verifyMessage('0x68656c6c6f776f726c64', signedMsg)

Hexadecimal string:

const signedMsg = await window.okxwallet.tronLink.tronWeb.trx.sign('0x68656c6c6f776f726c64')
// one more step to convert the original message to hexadecimal
const hexed = await window.okxwallet.tronLink.tronWeb.toHex('0x68656c6c6f776f726c64')
const validate = await window.okxwallet.tronLink.tronWeb.trx.verifyMessage(hexed, signedMsg)
  • For the versions of the okx wallet 2.80.0 and later:

Non-hexadecimal string:

const signedMsg = await window.okxwallet.tronLink.tronWeb.trx.sign('helloworld')
const validate = await window.okxwallet.tronLink.tronWeb.trx.verifyMessage('0x68656c6c6f776f726c64', signedMsg)

Hexadecimal string:

const signedMsg = await window.okxwallet.tronLink.tronWeb.trx.sign('0x68656c6c6f776f726c64')
const validate = await window.okxwallet.tronLink.tronWeb.trx.verifyMessage('0x68656c6c6f776f726c64', signedMsg)

Return value

(Promise) boolean: true or false

Events#

connect

This message will be generated during the following events:

  1. The DApp requests to connect, and the user approves the connection in the pop-up.
  2. The user connects to the website.

Usage

window.addEventListener('message', function (e) {
  if (e.data.message && e.data.message.action == "connect") {
    // handler logic
    console.log('got connect event', e.data)
  }
})

disconnect

This message will be generated during the following events:

  1. The DApp requests to connect, and the user rejects the connection in the pop-up
  2. The user disconnects from the website

Usage

window.addEventListener('message', function (e) {
  if (e.data.message && e.data.message.action == "disconnect") {
    // handler logic
    console.log('got connect event', e.data)
  }
})

accountsChanged

This message will be generated during the following events:

  1. The user logs in
  2. The user switches account
  3. The user locks the account.
  4. The wallet automatically locks after timeout.

Usage

window.addEventListener('message', function (e) {
  if (e.data.message && e.data.message.action === "accountsChanged") {
    // handler logic
    console.log('got accountsChanged event', e.data)
  }
})

Return value

interface MessageEventAccountsChangedData {
  isTronLink: boolean;
  message: {
    action: string;
    data: {
      address: string | boolean;
    }
  }
}

Example

Open in codeopen.

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

window.addEventListener('message', function (e) {
  if (e.data.message && e.data.message.action == "connect") {
    // handler logic
    console.log('got connect event', e.data)
  }
})

connectTronButton.addEventListener('click', () => {
  window.okxwallet.tronLink.request({
    method: 'tron_requestAccounts'
  }).catch((error)=>{
    console.log(error);
  })
});